You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Web3解码BSC交易Input Data时decode_function_input报错解决

解码BSC交易InputData的解决方案

示例图片

报错原因

你调用方法的路径错误,decode_function_input是合约实例的原生方法,不属于contract.functions子模块。你之前的写法会被web3识别为要调用链上合约的decode_function_input方法,自然会触发ABI未定义的报错。

正确可运行的代码

import web3
from web3 import Web3

# 初始化BSC节点连接
w3 = Web3(Web3.HTTPProvider("https://bsc-dataseed.binance.org/"))
# 初始化合约实例
contract = w3.eth.contract(address=Web3.toChecksumAddress(tokenAddress), abi=abi)
# 直接通过合约实例调用解码方法,不需要加.functions
func, input_params = contract.decode_function_input(transaction["input"])

# 输出结果
print("调用的合约函数名:", func.fn_name)
print("传入的参数明细:", input_params)

其他替代解码方案

方案1:仅用ABI片段解码

如果没有完整ABI,只有目标函数的ABI定义,可以直接使用web3的abi工具解码:

# 示例为transfer函数的ABI片段
target_func_abi = {
    "inputs": [
        {"internalType": "address", "name": "to", "type": "address"},
        {"internalType": "uint256", "name": "value", "type": "uint256"}
    ],
    "name": "transfer",
    "outputs": [{"internalType": "bool", "name": "", "type": "bool"}],
    "stateMutability": "nonpayable",
    "type": "function"
}

func, params = w3.eth.abi.decode_function_input(target_func_abi, transaction["input"])

方案2:手动拆分解码

InputData前10个字符(0x+4字节)为函数选择器,后续为参数编码,可拆分后单独解码参数:

# 拆分InputData
selector = transaction["input"][:10]
params_raw = "0x" + transaction["input"][10:]
# 按参数类型顺序解码,示例为transfer函数的两个参数类型
decoded_params = w3.eth.abi.decode(["address", "uint256"], params_raw)

内容的提问来源于stack exchange,提问作者Penko_Mlakar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:45:04