Web3Js订阅Log示例

1.web3.eth.subscribe(‘logs’, options [, callback])
Object 订阅选项
fromBlock- Number:最早的块编号。默认情况下null。
address- String|Array:仅从特定帐户获取日志的地址或地址列表。
topics- Array:一个值数组,每个值都必须出现在日志条目中。如果您想不使用主题,则顺序很重要null,例如。您还可以为每个主题传递另一个数组,并带有该主题的选项,例如[null, ‘0x00…’][null, [‘option1’, ‘option2’]]

先看文档
web3js文档是这么写的,看得懂就怪了

address和topic到底是个啥,怎么填这是个问题,请看下面
用到web3.eth.abi编码

// From a JSON interface object
web3.eth.abi.encodeFunctionSignature({
    name: 'myMethod',
    type: 'function',
    inputs: [{
        type: 'uint256',
        name: 'myNumber'
    },{
        type: 'string',
        name: 'myString'
    }]
})
> 0x24ee0097

// Or string
web3.eth.abi.encodeFunctionSignature('myMethod(uint256,string)')
> '0x24ee0097'


不错,这就是我们需要的topic,比方说我们可以监听erc20转账的事件
获取erc20转账事件的编码就是我们的topic了

var x =   web3.eth.abi.encodeEventSignature({
    name: 'Transfer',
    type: 'event',
    inputs: [{
        type: 'address',
        name: 'from'
    },{
        type: 'address',
        name: 'to'
    },{
      type: 'uint256',
      name: 'value'
  }]
});
console.log(x);//0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef



然后开始log

var subscription = web3.eth.subscribe('logs', {
  address: '0x80aae114cd8482d6a86d279c38e56a8e64799500',
  topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef']
}, function(error, result){
    if (!error)
        console.log(result);
})
.on("connected", function(subscriptionId){
    console.log(subscriptionId);
})
.on("data", function(log){
    console.log(log);
})
.on("changed", function(log){
});


再看文档理解了,address可以是账户可以是合约地址,看你想监听什么,topic可以写多个,毕竟一个合约里可以有多个函数多个事件,编码完后就可以订阅

另外还可以获取过去日志
web3.eth.getPastLogs文档在这再看的话就理解多了
 

猜你喜欢

转载自blog.csdn.net/weixin_39842528/article/details/123524889
今日推荐