如何用Python读取Solidity事件中的subId字段
提取Solidity事件中的subId字段
假设你用web3.py调用合约函数后,已经拿到了包含SubscriptionCreated事件的完整OrderedDict格式数据,可以按以下方式提取subId:
1. 先确认事件数据结构
web3.py解析事件后,数据会包含args字段,里面存储了事件定义的所有参数。示例事件数据大概长这样:
from collections import OrderedDict # 示例事件数据 event_data = OrderedDict([ ('args', OrderedDict([ ('subId', 123), ('owner', '0x1234567890abcdef1234567890abcdef12345678'), ('interval', 86400) ])), ('event', 'SubscriptionCreated'), ('logIndex', 1), ('transactionHash', '0x...'), ('address', '0x...'), ('blockNumber', 123456) ])
2. 直接提取subId
从args字典里直接取值即可:
sub_id = event_data['args']['subId'] print(sub_id) # 输出:123
3. 完整调用+提取流程示例
如果是刚调用createSubscription函数,完整代码流程参考:
from web3 import Web3 # 初始化web3连接 w3 = Web3(Web3.HTTPProvider('https://your-rpc-url')) # 合约ABI(保留相关部分即可) contract_abi = [ { "inputs": [{"internalType": "uint256", "name": "interval", "type": "uint256"}], "name": "createSubscription", "outputs": [], "stateMutability": "nonpayable", "type": "function" }, { "anonymous": False, "inputs": [ {"indexed": True, "internalType": "uint256", "name": "subId", "type": "uint256"}, {"indexed": True, "internalType": "address", "name": "owner", "type": "address"}, {"indexed": False, "internalType": "uint256", "name": "interval", "type": "uint256"} ], "name": "SubscriptionCreated", "type": "event" } ] # 合约地址 contract_address = '0xYourContractAddress' contract = w3.eth.contract(address=contract_address, abi=contract_abi) # 调用createSubscription函数(需提前解锁账户) tx_hash = contract.functions.createSubscription(86400).transact({'from': '0xYourAddress'}) # 等待交易上链,获取收据 tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash) # 解析事件 events = contract.events.SubscriptionCreated.processReceipt(tx_receipt) # 提取第一个事件的subId(单交易一般只触发一次) if events: sub_id = events[0]['args']['subId'] print(f"创建的订阅ID:{sub_id}")
注意事项
- 如果
subId是indexed参数,它也会出现在事件数据的topics列表里,但直接从args提取更直观,无需手动解码。 - 若一次交易触发多个相同事件,需要遍历
events列表逐个提取对应subId。
内容的提问来源于stack exchange,提问作者Usman Farooq
相关产品推荐
相关产品推荐

