以太坊中的Event监听

本来是全职做EOS方面工作的,但是,今天有些情况需要和其他公司有交流,他们咨询关于以太坊开发的问题,感觉有些问题还不错,做个整理;但是本篇文章先把一个比较复杂的过程介绍下,就是event的事件监听:

前提准备

( web3有一个0.1x.0的版本,还有1.0.0 Beta的版本,本文都是使用的1.0.0 Beta;)

首先,通常我们启动节点,都是启动rpc连接接口,但是既然是事件监听,短连接的rpc肯定不行,需要使用websocket的方式,在启动geth的时候,请使用如下方式:

geth --rpcapi "db,eth,net,web3,personal" --ws --wsaddr "localhost" --wsport "8545" --wsorigins "*" --identity "TestNode" --datadir "./data" --testnet

相应的,在使用web3进行连接的时候使用:

const web3 = new Web3(new Web3.providers.WebsocketProvider('http://IP:8545'));

这样就OK了。

合约的编译和部署

首先,编写简单的测试代码:

pragma solidity ^0.4.0;

contract Calc{
    /*区块链存储*/
    uint count;
    event ReturnValue(address indexed _from, uint _value);

    /*执行会写入数据,所以需要`transaction`的方式执行。*/
    function add(uint a, uint b) public returns(uint) {
        count++;
        emit ReturnValue(msg.sender, a+b);
        return a + b;
    }

    /*执行不会写入数据,所以允许`call`的方式执行。*/
    function getCount() public constant returns (uint) {
        return count;
    }
}

然后,编译代码,可以使用solc的编译工具,也可以使用网站 Remix ;
编译完成的json abi和二进制code就贴上来了。

部署代码:

//先解锁你的钱包

var calcContract = new web3.eth.Contract(YouCalcABI, null, {
    from: '0xfaad1dec3e7db9d5a45fdabb90ab56f52a325d84' 
});

calcContract.deploy().send({
    from: '0xfaad1dec3e7db9d5a45fdabb90ab56f52a325d84',
    gas: 1500000,
    gasPrice: '30000000000000'
}, function(error, transactionHash){
    console.log("deploy tx hash:"+transactionHash)
})
.on('error', function(error){ console.error(error) })
.on('transactionHash', function(transactionHash){ console.log("hash:",transactionHash)})
.on('receipt', function(receipt){
   console.log(receipt.contractAddress) // contains the new contract address
})
.on('confirmation', function(confirmationNumber, receipt){console.log("receipt,",receipt)})
.then(function(newContractInstance){
    console.log(newContractInstance.options.address) // instance with the new contract address
});

部署成功之后,会打印结果,以及合约地址;

然后,以后想获得合约结构,就要用到abi和合约地址,比如:

var calc = new web3.eth.Contract([ abi 内容],'0x16706C380579d13eC3d6EBC5E0cbaf35a2bE8DB0');

监听event

监听方式很简单,看代码:

calc.events.ReturnValue(
    {
        filter:
            {_from:'0xfaad1dec3e7db9d5a45fdabb90ab56f52a325d84'},
            fromBlock:'latest'
    }, 
    function(error, event) {
        console.log("******result:*******\n"+JSON.stringify(event));
    }
);

然后,你可以在其他地方,发送合约函数add:

calc.methods.add(5,4).send({from:coin}).then(function(receipt){console.log("fuck!");console.log(receipt)});

然后,你就能在监听终端看见监听结果了:
image.png

OK,你已经搞定监听了。
当然,还有很多方式:比如once、allEvent等,可以去看官方文档:web3

你可能感兴趣的:(以太坊中的Event监听)