Python无ABI文件打包EVM合约方法名及参数方法
# pip install eth-abi
import eth_abi
# pip install safe-pysha3
from sha3 import keccak_256
def keccak_256_hash(data: str) -> bytes:
k = keccak_256()
k.update(data.encode())
return k.digest()
def get_method_id(method_sig: str) -> bytes:
return keccak_256_hash(method_sig)[:4]
def pack_abi_data(method: str = None, params: list = None) -> bytes:
"""
打包evm合约方法及参数
:param method: 合约方法,打包合约初始化参数时method=None
:param params: 合约参数,例如[("uint256": 10000),("address", "0xa166c92f4c8118905ad984919dc683a7bdb295c1")]
:return: 打包后的数据
"""
params_data = b''
types, values = [], []
if params:
for param_type, param_value in params:
types.append(param_type)
values.append(param_value)
params_data = eth_abi.encode(tuple(types), tuple(values))
if method:
method_sig = f"{method}({','.join(types)})"
method_id = get_method_id(method_sig)
return b'%s%s' % (method_id, params_data)
return params_data
使用示例
data = pack_abi_data("updateBalance", params=[
("uint256", 10000),
("address", "0xa166c92f4c8118905ad984919dc683a7bdb295c1")])
print(data.hex())