# 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 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 = keccak_256_hash(method_sig)[:4]
return b'%s%s' % (method_id, params_data)
return params_data
使用示例
data = pack_abi_data("updateBalance", params=[
("uint256", 10000),
("address", "0xa166c92f4c8118905ad984919dc683a7bdb295c1")])
print(data.hex())
标签:EVM,Python,ABI,keccak,param,params,abi,data,method
From: https://www.cnblogs.com/superhin/p/18321436/python_pack_abi_data_without_abi_file