abi
Documentation for eth_defi.abi Python module.
ABI loading from the precompiled bundle.
Provides functions to load ABI files and construct web3.contract.Contract types.
The results are cached for the speedup.
We also provide some helper functions to deal with ABI encode/decode.
See Github for available contracts ABI files.
Module Attributes
Ethereum 0x0000000000000000000000000000000000000000 address as a string. |
|
Ethereum 0x0000000000000000000000000000000000000000 address |
|
Ethereum 0x address as bytes |
|
Used by Gnosis Safe in linked lists https://github.com/safe-global/safe-smart-account/pull/993 |
Functions
|
Decode binary CALL or CALLDATA to a Solidity function, |
|
Decode raw return value of Solidity function using Contract proxy object. |
|
Encode function selector + its arguments as data payload. |
|
Encode multiple contract function calls into a single multicall payload for contract built-in multicall functionality. |
|
Mimic Solidity's abi.encodeWithSignature() in Python. |
|
Print curl command line syntax to repeat a failed contract call. |
|
Reads a embedded ABI file and returns it. |
|
Get Contract proxy class from ABI JSON file. |
|
Get Contract proxy class with Forge library linking. |
|
Get a Contract proxy objec for a contract deployed at a specific address. |
|
Get function ABI by its name. |
|
Get Solidity function selector. |
|
Create a Contract proxy class from our bundled contracts or filesystem and links it Solidity bytecode. |
Get topic signature for an Event class. |
|
Get the "Data" payload of a transaction. |
|
Make decoded arguments more human readable. |
|
|
Link Solidity libraries in Forge-compiled bytecode. |
|
Link Solidity libraries based on Hardhat deployment. |
Try make Solidity call args human readable. |
- ZERO_ADDRESS_STR = '0x0000000000000000000000000000000000000000'
Ethereum 0x0000000000000000000000000000000000000000 address as a string.
Legacy. Use one below.
- ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'
Ethereum 0x0000000000000000000000000000000000000000 address
- ZERO_ADDRESS_BYTES = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
Ethereum 0x address as bytes
- ONE_ADDRESS_STR = '0x0000000000000000000000000000000000000001'
Used by Gnosis Safe in linked lists https://github.com/safe-global/safe-smart-account/pull/993
- get_abi_by_filename(fname)
Reads a embedded ABI file and returns it.
Example:
abi = get_abi_by_filename("ERC20Mock.json")You are most likely interested in the keys abi and bytecode of the JSON file.
Loaded ABI files are cache in in-process memory to speed up future loading.
Any results are cached.
- Parameters
web3 – Web3 instance
fname (str) – JSON filename from supported contract lists.
- Returns
Full contract interface, including bytecode.
- Return type
- get_contract(web3, fname, bytecode=None)
Get Contract proxy class from ABI JSON file.
Read ABI file from - Our bundled contracts in the Python package - Filesystem using absolute path - ABI file can be a solc compiling artifact or Etherscan copy-pasted ABI.
See Web3.py documentation on Contract instances.
Any results are cached. Web3 connection is part of the cache key.
Note
If the contract requires library linking (Forge
linkReferences), useget_contract_with_forge_libraries()instead.Example:
IERC20 = get_contract(web3, "sushi/IERC20.json")
- Parameters
web3 (web3.main.Web3) – Web3 instance
bytecode (Optional[str]) – Override bytecode payload for the contract
fname (str | pathlib.Path) –
Solidity compiler artifact.
Use slash prefixed path for absolute lookups.
- Returns
Contract proxy class
- Return type
Type[web3.contract.contract.Contract]
- get_contract_with_forge_libraries(web3, fname, library_addresses)
Get Contract proxy class with Forge library linking.
Similar to
get_contract()but resolves ForgelinkReferencesplaceholders in the creation bytecode before constructing the Contract class.Use this for contracts that depend on Solidity libraries compiled with Forge. The library must be deployed first and its address passed in
library_addresses.On chains where the library is not needed (its code paths are never entered), pass
ZERO_ADDRESSas the library address to produce valid bytecode without deploying the library.Example:
from eth_defi.abi import get_contract_with_forge_libraries, ZERO_ADDRESS # On HyperEVM: deploy library first lib = deploy_contract(web3, "guard/HypercoreVaultLib.json", deployer) Contract = get_contract_with_forge_libraries(web3, "guard/SimpleVaultV0.json", {"HypercoreVaultLib": lib.address}) # On other chains: link with zero address (library never called) Contract = get_contract_with_forge_libraries(web3, "guard/SimpleVaultV0.json", {"HypercoreVaultLib": ZERO_ADDRESS})
- Parameters
web3 (web3.main.Web3) – Web3 instance.
fname (str | pathlib.Path) – ABI JSON filename (Forge compiler artifact).
library_addresses (dict[str, Union[str, eth_typing.evm.HexAddress]]) – Mapping of library name to deployed address.
- Returns
Contract proxy class with linked bytecode ready for deployment.
- Return type
Type[web3.contract.contract.Contract]
- get_linked_contract(web3, fname, hardhat_export_data=None)
Create a Contract proxy class from our bundled contracts or filesystem and links it Solidity bytecode.
Needed when contracts contain references to libraries. The contract bytecode must be processed and placeholders must be replaced by the on-chain addresses of the deployed library contracts.
Example:
path = self.path.joinpath("artifacts/@aave/core-v3/contracts/mocks/tokens/MintableERC20.sol/MintableERC20.json") return get_linked_contract(web3, path, get_aave_hardhard_export())
Note
If you do not need linking use
get_contract()which is faster.- Parameters
web3 (web3.main.Web3) – Web3 instance
fname (str | pathlib.Path) –
Solidity compiler artifact.
Use slash prefixed path for absolute lookups.
hardhat_export_data (Optional[dict]) –
Hardhat deployment export data to link bytecode.
A JSON file generated by hardhat deploy –export command.
- Returns
Contract proxy class
- Return type
Type[web3.contract.contract.Contract]
- get_deployed_contract(web3, fname, address, register_for_tracing=True)
Get a Contract proxy objec for a contract deployed at a specific address.
See Web3.py documentation on Contract instances.
- Parameters
web3 (web3.main.Web3) – Web3 instance
fname (str | pathlib.Path) –
address (Union[eth_typing.evm.HexAddress, str]) – Ethereum address of the deployed contract
register_for_tracing (bool) – Add the contract to the deployment registry if not already there.
- Returns
web3.contract.Contract proxy
- Return type
web3.contract.contract.Contract
- get_transaction_data_field(tx)
Get the “Data” payload of a transaction.
Ethereum Tester has this in tx.data while Ganache has this in tx.input. Yes, it is madness.
Example:
tx = web3.eth.get_transaction(tx_hash) function, input_args = router.decode_function_input(get_transaction_data_field(tx)) print("Transaction {tx_hash} called function {function}")- Parameters
tx (web3.datastructures.AttributeDict) –
- Return type
- encode_with_signature(function_signature, args)
Mimic Solidity’s abi.encodeWithSignature() in Python.
This is a Python equivalent for abi.encodeWithSignature().
Example:
payload = encode_with_signature("init(address)", [my_address]) assert type(payload) == bytes
- decode_function_output(func, data)
Decode raw return value of Solidity function using Contract proxy object.
Uses web3.Contract.functions prepared function as the ABI source.
- encode_function_call(func, args=None)
Encode function selector + its arguments as data payload.
Uses web3.Contract.functions prepared function as the ABI source.
See also
encode_function_args().Example:
- Parameters
- Returns
Solidity’s function selector + argument payload.
- Return type
hexbytes.main.HexBytes
- decode_function_args(func, data)
Decode binary CALL or CALLDATA to a Solidity function,
Uses web3.Contract.functions prepared function as the ABI source.
- humanise_decoded_arg_data(args)
Make decoded arguments more human readable.
All arguments are converted to good text types
- link_libraries_forge(bytecode, link_references, library_addresses)
Link Solidity libraries in Forge-compiled bytecode.
Replaces
__$<hash>$__placeholder patterns in the bytecode hex string with the deployed library addresses.Example:
from eth_defi.abi import get_abi_by_filename, link_libraries_forge abi_data = get_abi_by_filename("guard/SimpleVaultV0.json") bytecode = abi_data["bytecode"]["object"] link_refs = abi_data["bytecode"]["linkReferences"] linked = link_libraries_forge(bytecode, link_refs, {"HypercoreVaultLib": lib_address})
- Parameters
bytecode (str) – Hex-encoded bytecode string (with or without
0xprefix). Contains__$<hash>$__placeholders at the positions described bylink_references.link_references (dict) – Forge
linkReferencesdict from the compiled ABI JSON. Format:{"source_path": {"LibName": [{"start": int, "length": 20}, ...]}}.library_addresses (dict[str, Union[str, eth_typing.evm.HexAddress]]) – Mapping of library name to deployed address. Use
ZERO_ADDRESSfor libraries that will never be called (e.g. HypercoreVaultLib on non-HyperEVM chains).
- Returns
Linked bytecode hex string (with
0xprefix).- Return type
- link_libraries_hardhat(bytecode, link_references, hardhat_export)
Link Solidity libraries based on Hardhat deployment.
Warning
Preliminary implementation
See
get_linked_contract()for details.- Parameters
bytecode (str) –
Raw bytecode of a Solidity contract.
Get from ABI file.
Bytecode must be a in string format, because placeholders are not parseable hex.
link_references (dict) –
List of binary sequences we need to replaced by a contract filename.
Get from ABI file.
hardhat_export (dict) –
Hardhat’s export format.
You get with hardhat deploy –export.
- Returns
Linked bytecode
- get_function_selector(func)
Get Solidity function selector.
Does not support multiple Solidity functions with the same name, but different arguments. On multiple functions use one first declared in ABI.
Example:
selector = get_function_selector(uniswap_v2.router.functions.swapExactTokensForTokens) assert selector.hex() == 38ed1739
- Parameters
func (web3.contract.contract.ContractFunction) – Unbound or bound contract function proxy
- Returns
Solidity function selector.
First 32-bit (4 bytes) keccak hash.
- Return type
- get_topic_signature_from_event(event)
Get topic signature for an Event class.
- Returns
0x prefixed hex string
- Parameters
event (Type[web3.contract.contract.ContractEvent]) –
- Return type
- get_function_abi_by_name(contract, function_name)
Get function ABI by its name.
- present_solidity_args(a)
Try make Solidity call args human readable.
Make sure we display bytes as hex.
Example:
contract_address = func_call.address data_payload = encode_function_call(func_call, func_call.arguments) logger.info( "Lagoon: Wrapping call to TradingStrategyModuleV0. Target: %s, function: %s (0x%s), args: %s, payload is %d bytes", contract_address, func_call.fn_name, get_function_selector(func_call).hex(), present_solidity_args(func_call.arguments), len(data_payload), )
Output:
Lagoon: Wrapping call to TradingStrategyModuleV0. Target: 0x5788F91Aa320e0610122fb88B39Ab8f35e50040b, function: exactInput (c04b8d59), args: ["['0x833589fcd6edb6e08f4c7c32d4f71b54bda029130001f442000000000000000000000000000000000000060027106921b130d297cc43754afba22e5eac0fbf8db75b', '0xEBee4d3fE83DD4755761C65b772f6a4f900A118b', '9223372036854775808', '10000000', '25455184317467649376256']"], payload is 324 bytes
- format_debug_instructions(bound_call, block_identifier='latest')
Print curl command line syntax to repeat a failed contract call.
Useful for sending information about broken nodes to dRPC team
- Parameters
bound_call (web3.contract.contract.ContractFunction) –
- Return type
- encode_multicalls(funcs)
Encode multiple contract function calls into a single multicall payload for contract built-in multicall functionality.