mt logoMyToken
总市值:
0%
恐慌指数:
0%
币种:--
交易所 --
ETH Gas:--
EN
USD
APP
Ap Store QR Code

Scan Download

墨客区块链智能合约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 watchthe event, such as transfer.

*/

var Chain3 = require('chain3');

var chain3 = new Chain3(newChain3.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

vartokenContract=chain3.mc.contract(JSON.parse(tokenabi));

var myContractInstance =tokenContract.at('0xA2580D58A58998ca06e6f5b2A96A95D8d48f1679'); //智能合约地址

chain3.setProvider(newchain3.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;

运行后处于侦听状态:

操作合约的transfer,查看监测

在http://wallet.moac.io/对erc20合约进行一次transfer操作。

打包后,检测程序显示与浏览器内容一致:

附录:对合约的调用操作

#!/usr/bin/env node

/*

Test the ERC20 contract interface on MOACnetwork.

This test requires a running MOAC node withRPC http port open at 8545

and the contract address and abi.

1. Connect to a local MOACnode.

2. Load the contract addressand abi.

*/

var Chain3 =require('chain3');

var chain3 = new Chain3(newChain3.providers.HttpProvider('http://localhost:8545'));

//Set the contract ABI andaddress to use

//The ABI info can beobtained using REMIX

//The address is the contractHASH after deploying the contract.

var tokenabi='[ {"constant": true, "inputs": [], "name":"name",............, "name": "Approval","type": "event" } ]';

//Load the contract ABI

vartokenContract=chain3.mc.contract(JSON.parse(tokenabi));

//Testnetwork token,networkid = 101

vartokenaddress='0xA2580D58A58998ca06e6f5b2A96A95XXXXXXXXXX';

//Load the contract methods

vartcalls=tokenContract.at(tokenaddress);

//check the balance

var totalBal = 0;

//test accounts

//Need to add the addr andprivate key for your own ERC20 tokens

var taccts = [{

"addr":"0x68986c1BCD54Ae5dAe69310fC64Ea5XXXXXXXXXX",

"key":"9a863cb325ba30b5f41bd285e80c14c2d96f86b21e90XXXXXXXXXXXXXXXXXXXX"

},{

"addr":"0x745c57ca5318093115D61Bbca3687cXXXXXXXXXX",

"key": ""

}];

//Connect the local MOAC nodethrough HTTP

chain3.setProvider(newchain3.providers.HttpProvider('http://localhost:8545'));

if ( chain3.isConnected() ){

console.log("RPC connected, check tokenbalance");

// console.log("code len:",chain3.mc.getCode(tokenaddress));

var contractCode = chain3.mc.getCode(tokenaddress);

if (contractCode == '0x') {

console.log("Contract address has nodata!");

return;

}

//Get token Info

console.log("Token Info\nfullname:", tcalls.name());

console.log(" symbol:", tcalls.symbol());

varsrc = 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 thecorrect network id

var networkid = chain3.version.network;

console.log("On network:",networkid);

//Add some more gas on the estimate toensure 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

*

*/

functioncallContractMethod(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("Chain3error:", err.message);

return err.message;

}

console.log("Get response from MOACnode in the feedback function!")

// res.send(response);

});

}

免责声明:本文版权归原作者所有,不代表MyToken(www.mytokencap.com)观点和立场;如有关于内容、版权等问题,请与我们联系。