• 注册
  • 墨客科普 墨客科普 关注:33 内容:79

    科普 | 智能合约event调用实例

  • 查看作者
  • 打赏作者
  • 拉黑名单
    • 墨客科普
    • 大版主
      墨客战士
      科普 | 智能合约event调用实例

      event调用过程:首先需要在合约中定义event,并在某个函数中去触发它。当我们调用该函数的时候就会触发event,然后,可以通过在该次调用智能合约产生的block上建立filter来捕获event。

      环境:

      墨客区块链版本:nuwa1.0.5.win.zip;

      操作系统:64位Windows 10家庭版。

      部署标准ERC20合约
      1. 启动本地节点
      D:\nuwa1.0.5.win\win\vnode>moac --rpc  --rpcaddr 0.0.0.0 --rpccorsdomain "*" --rpcapi="db,mc,net,chain3,personal,vnode,debug,scs"
      2. 按照《第四篇 墨客区块链(MOAC BlockChain) 部署ERC-20合约》部署智能合约。


      监测智能合约事件
      代码如下:
      #!/usr/bin/env node
      /*
         Test the ERC20 contract interface on MOAC network.
         This test requires a running MOAC node with RPC http port open at 8545
         and the contract address and abi.
      1. Connect to a local MOAC node.
      2. Load the contract address and abi.
      3. Setup a filter of the contract and watch the event, such as transfer.
      */
      var Chain3 = require('chain3');
      var chain3 = new Chain3(new Chain3.providers.HttpProvider('http://localhost:8545'));
      var tokenabi='[ { "constant": true, "inputs": [], "name": "name", ............, { "indexed": false, "name": "_value", "type": "uint256" } ], "name": "Approval", "type": "event" } ]';
      //Load the contract ABI
      var tokenContract=chain3.mc.contract(JSON.parse(tokenabi));
      var myContractInstance = tokenContract.at('0xA2580D58A58998ca06e6f5b2A96A95D8d48f1679');  //智能合约地址
      chain3.setProvider(new chain3.providers.HttpProvider('http://localhost:8545'));
      if ( chain3.isConnected() ){
          console.log("RPC connected, check token balance");
          // watch for an event with {some: 'args'}
          var events = myContractInstance.allEvents({fromBlock: 0, toBlock: 'latest'});
          events.watch(function(error, result){
              if( !error )
              {
                  var msg = result.blockNumber;
                  console.log( msg + ":" + JSON.stringify(result.TxData))
              }
              else{
                  console.log("err:" + error);
              } 
          });
      }else{
            console.log("RPC not connected!");
      }
      return;
      科普 | 智能合约event调用实例
       运行后处于侦听状态 

      操作合约的transfer,查看监测
      在 http://wallet.moac.io/ 对erc20合约进行一次transfer操作。
      科普 | 智能合约event调用实例
      打包后,检测程序显示与浏览器内容一致:
      科普 | 智能合约event调用实例
      附录:对合约的调用操作
      #!/usr/bin/env node
      /*
         Test the ERC20 contract interface on MOAC network.
         This test requires a running MOAC node with RPC http port open at 8545
         and the contract address and abi.
      1. Connect to a local MOAC node.
      2. Load the contract address and abi.
      */
      var Chain3 = require('chain3');
      var chain3 = new Chain3(new Chain3.providers.HttpProvider('http://localhost:8545'));
      //Set the contract ABI and address to use
      //The ABI info can be obtained using REMIX
      //The address is the contract HASH after deploying the contract.
      var tokenabi='[ { "constant": true, "inputs": [], "name": "name",............, "name": "Approval", "type": "event" } ]';
      //Load the contract ABI
      var tokenContract=chain3.mc.contract(JSON.parse(tokenabi));
      //Testnetwork token, networkid = 101
      var tokenaddress='0xA2580D58A58998ca06e6f5b2A96A95XXXXXXXXXX';
      //Load the contract methods
      var tcalls=tokenContract.at(tokenaddress);
      //check the balance
      var totalBal = 0;
      //test accounts
      //Need to add the addr and private key for your own ERC20 tokens
      var taccts = [{
          "addr": "0x68986c1BCD54Ae5dAe69310fC64Ea5XXXXXXXXXX",
          "key": "9a863cb325ba30b5f41bd285e80c14c2d96f86b21e90XXXXXXXXXXXXXXXXXXXX"
      },{
          "addr": "0x745c57ca5318093115D61Bbca3687cXXXXXXXXXX",
          "key": ""
      }];
      //Connect the local MOAC node through HTTP
      chain3.setProvider(new chain3.providers.HttpProvider('http://localhost:8545'));
      if ( chain3.isConnected() ){
          console.log("RPC connected, check token balance");
          // console.log("code len:", chain3.mc.getCode(tokenaddress));
          var contractCode = chain3.mc.getCode(tokenaddress);
          if (contractCode == '0x') {
              console.log("Contract address has no data!");
              return;
          }
          //Get token Info
          console.log("Token Info\nfull name:", tcalls.name());
          console.log("   symbol:", tcalls.symbol());
              var src = taccts[0].addr;
              var des = "0x745c57ca5318093115D61Bbca3687cXXXXXXXXXX";//taccts[1].addr;
              console.log("src bal:", src, ":",tcalls.balanceOf(src).toString(10));
              console.log("des bal:", des, ":",tcalls.balanceOf(des).toString(10));
              //var strData = '';
              var srcVal = tcalls.balanceOf(src);
              var desVal = tcalls.balanceOf(des);
              var amt = 123;//amout in erc20 token "m02"
              console.log(" Transfer from:\n", src, "\n to \n", des);
              var tcalldata = tcalls.transfer.getData(des, amt);
              console.log("\n Tcalldata:", tcalldata);
              let gasEstimate = chain3.mc.estimateGas({data: tcalldata});
              gasEstimate = 4000000;
              //The sign of the transaction requires the correct network id
              var networkid = chain3.version.network;
              console.log("On network:", networkid);
              //Add some more gas on the estimate to ensure the call can be processed
              callContractMethod(taccts[0], tokenaddress, gasEstimate+100, networkid, tcalldata);
        }else
            console.log("RPC not connected!");
      /*
       * Call a contract with the input byteCode
       *
      */
      function callContractMethod(src, contractAddress, gasValue, inchainID, inByteCode){
          var txcount = chain3.mc.getTransactionCount(src["addr"]);
          console.log("Get tx account", txcount)
          //Build the raw tx obj
          //note the transaction
          var rawTx = {
              from: src.addr,
              to: contractAddress,
              nonce: chain3.intToHex(txcount),
              gasPrice: chain3.intToHex(30000000000),
              gasLimit: chain3.intToHex(gasValue),
              value: '0x',
              data: inByteCode,
              chainId: chain3.intToHex(inchainID)
          }
          console.log(rawTx);
          var cmd1 = chain3.signTransaction(rawTx, src["key"]);   
          console.log("\nSend signed TX:\n", cmd1);
          chain3.mc.sendRawTransaction(cmd1, function(err, hash) {
              if (!err){
                 
                  console.log("Succeed!: ", hash);
                  return hash;
              }else{
                  console.log("Chain3 error:", err.message);
                  return err.message;
              }
          console.log("Get response from MOAC node in the feedback function!")
              // res.send(response);
          });
      }


      追踪我们:

       官网:www.moacfoundation.org

       Twitter:https://twitter.com/moac_io

       FB: https://www.facebook.com/moacchain/

       Medium: https://medium.com/moac

       Telegram: https://t.me/moacblockchain

       Telegram: https://t.me/MOACDevelopers 

       Reddit: https://www.reddit.com/r/MOAC/

       Github: https://github.com/MOACChain

      想加入MOAC墨客自治社区

      长按二维码添加MOAC墨客小酷

      自治社区等待你

      科普 | 智能合约event调用实例

      科普 | 智能合约event调用实例

      转载自墨客生态

      请登录之后再进行评论

      登录
    • 做任务
    • 实时动态
    • 偏好设置
    • 返回顶部
    • 帖子间隔 侧栏位置: