【问题标题】:how to get event data from web3py?如何从 web3py 获取事件数据?
【发布时间】:2018-09-26 00:12:57
【问题描述】:
pragma solidity ^0.4.17

contract Test {
    event greeting(string name);
    function say() pure public {
        greeting('jack');
    }
}

在 python 版本 web3.py 中调用 say() 函数时如何获取事件数据“jack”?下面是我的python代码。

contractAddress = '0x345ca3e014aaf5dca488057592ee47305d9b3e10'
contract = w3.eth.contract(address=contractAddress, abi=abiJson['abi'])
accounts = w3.eth.accounts

def handle_event(event):
    print(event)

def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
            time.sleep(poll_interval)

block_filter = w3.eth.filter({'fromBlock':'latest', 'address':contractAddress})
log_loop(block_filter, 2)

【问题讨论】:

  • 更多背景知识会有所帮助:运行代码时会发生什么?你用的是什么版本的 web3py?你用的是什么节点?你是如何触发事件的?
  • 问题已经解决了:

标签: python web3


【解决方案1】:

问题已经解决,正确的代码应该如下所示:

contractAddress = '0x345ca3e014aaf5dca488057592ee47305d9b3e10'
contract = w3.eth.contract(address=contractAddress, abi=abiJson['abi'])
accounts = w3.eth.accounts

def handle_event(event):
    receipt = w3.eth.waitForTransactionReceipt(event['transactionHash'])
    result = contract.events.greeting.processReceipt(receipt)
    print(result[0]['args'])

def log_loop(event_filter, poll_interval):
    while True:
        for event in event_filter.get_new_entries():
            handle_event(event)
            time.sleep(poll_interval)

block_filter = w3.eth.filter({'fromBlock':'latest', 'address':contractAddress})
log_loop(block_filter, 2)

【讨论】:

    【解决方案2】:

    我发现您的代码对于了解如何提取事件信息非常有帮助,但我遇到了一个问题。我会写在这里以防万一它可以帮助任何人。

    线 result = contract.events.greeting.processReceipt(receipt) 抛出错误: _parse_logs() missing 1 required positional argument: 'errors'

    digging 之后,它似乎是 Web3py 的一个限制,它可以通过事件的先前实例化来修复。所以,代码是:

    contractAddress = '0x345ca3e014aaf5dca488057592ee47305d9b3e10'
    contract = w3.eth.contract(address=contractAddress, abi=abiJson['abi'])
    accounts = w3.eth.accounts
    greeting_Event = contract.events.greeting() # Modification
    
    def handle_event(event):
        receipt = w3.eth.waitForTransactionReceipt(event['transactionHash'])
        result = greeting_Event.processReceipt(receipt) # Modification
        print(result[0]['args'])
    
    def log_loop(event_filter, poll_interval):
        while True:
            for event in event_filter.get_new_entries():
                handle_event(event)
                time.sleep(poll_interval)
    
    block_filter = w3.eth.filter({'fromBlock':'latest', 'address':contractAddress})
    log_loop(block_filter, 2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-04
      • 2018-08-19
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-02
      相关资源
      最近更新 更多