chain

Documentation for eth_defi.chain Python module.

Chain specific configuration.

Many chains like Polygon and BNB Chain may need their own Web3 connection tuning. In this module, we have helpers.

Functions

fetch_block_timestamp(web3, block_number)

Get the block mined at timestamp.

get_block_time(chain_id)

Get average block time for a chain.

get_chain_homepage(chain_id)

Translate Ethereum chain id to a link to its homepage.

get_chain_id_by_name(name)

Get chain id by its name.

get_chain_name(chain_id)

Translate Ethereum chain id to its name.

get_default_call_gas_limit(chain_id)

Get the eth_call reasonable gas limit.

get_evm_block_time(chain_id[, block_number])

Get block time for a chain at a given block, tolerating unknown chains.

get_graphql_url(provider)

Resolve potential GraphQL endpoint API for a JSON-RPC provider.

has_graphql_support(provider)

Check if a node has GoEthereum GraphQL API turned on.

install_api_call_counter_middleware(web3)

Install API call counter middleware.

install_api_call_counter_middleware_on_provider(...)

Install API call counter middleware on a specific API provider.

install_chain_middleware(web3[, ...])

Install any chain-specific middleware to Web3 instance.

install_retry_middleware(web3)

Install gracefully HTTP request retry middleware.

install_retry_muiddleware(web3)

fetch_block_timestamp(web3, block_number)

Get the block mined at timestamp.

Warning

Uses eth_getBlock. Very slow for large number of blocks. Use alternative methods for managing timestamps for large block ranges.

Example:

# Get when the first block was mined
timestamp = fetch_block_timestamp(web3, 1)
print(timestamp)
Parameters
  • web3 (web3.main.Web3) – Web3 connection

  • block_number (int) – Block number of which timestamp we are going to get

Returns

UTC naive datetime of the block timestamp

Return type

datetime.datetime

get_block_time(chain_id)

Get average block time for a chain.

Parameters

chain_id (int) – Chain id to get the block time for

Returns

Average block time in seconds.

Return type

float

get_chain_homepage(chain_id)

Translate Ethereum chain id to a link to its homepage.

Returns

name, homepage link tuple

Parameters

chain_id (int) –

Return type

tuple[str, str]

get_chain_id_by_name(name)

Get chain id by its name.

Parameters

name (str) – Case-insensitive chain name, e.g. “Ethereum”, “Polygon”, “BNB Chain”

Returns

Chain id or None if not found

Return type

Optional[int]

get_chain_name(chain_id)

Translate Ethereum chain id to its name.

Parameters

chain_id (int) –

Return type

str

get_default_call_gas_limit(chain_id)

Get the eth_call reasonable gas limit.

  • 15M except for Mantle 99M

  • Mantle has weird policy and all transactions and calls cost much more than other chains

Parameters

chain_id (int) –

Return type

int

get_evm_block_time(chain_id, block_number=None)

Get block time for a chain at a given block, tolerating unknown chains.

Unlike get_block_time(), returns None for chains missing from EVM_BLOCK_TIMES instead of crashing, so callers can degrade gracefully (e.g. skip a time-based confirmation wait).

Parameters
  • chain_id (int) – Chain id to get the block time for.

  • block_number (Optional[int]) –

    Block at which the block time should be resolved.

    Currently unused. Reserved for resolving the block time dynamically in the future: block times change over chain upgrades (e.g. Polygon shortening blocks, Arbitrum Nitro) and some chains have variable block types (HyperEVM dual-block architecture), so a static per-chain value is only an approximation.

Returns

Block time in seconds, or None if the chain is not in the lookup table.

Return type

Optional[float]

get_graphql_url(provider)

Resolve potential GraphQL endpoint API for a JSON-RPC provider.

See has_graphql_support().

Parameters

provider (web3.providers.base.BaseProvider) –

Return type

str

has_graphql_support(provider)

Check if a node has GoEthereum GraphQL API turned on.

You can check if GraphQL has been turned on for your node with:

curl -X POST             https://mynode.example.com/graphql             -H "Content-Type: application/json"             --data '{ "query": "query { block { number } }" }'

A valid response looks like:

{"data":{"block":{"number":16328259}}}
Parameters

provider (web3.providers.base.BaseProvider) –

Return type

bool

install_api_call_counter_middleware(web3)

Install API call counter middleware.

Measure total and per-API EVM call counts for your application.

  • Every time a Web3 API is called increase its count.

  • Attach web3.api_counter object to the connection

Compatible with both web3.py v6 and v7.

Example:

from eth_defi.chain import install_api_call_counter_middleware

web3 = Web3(tester)
counter = install_api_call_counter_middleware(web3)

# Make an API call
chain_id = web3.eth.chain_id
assert counter["total"] == 1
assert counter["eth_chainId"] == 1

# Make another API call
block_number = web3.eth.block_number
assert counter["total"] == 2
assert counter["eth_blockNumber"] == 1
Returns

Counter object with columns per RPC endpoint and “total”

Parameters

web3 (web3.main.Web3) –

Return type

collections.Counter

install_api_call_counter_middleware_on_provider(provider)

Install API call counter middleware on a specific API provider.

Allows per-provider API call counting when using complex provider setups.

Compatible with both web3.py v6 and v7.

See also

Returns

Counter object with columns per RPC endpoint and “total”

Parameters

provider (web3.providers.base.JSONBaseProvider) –

Return type

collections.Counter

install_chain_middleware(web3, poa_middleware=None, hint='')

Install any chain-specific middleware to Web3 instance.

Mainly this is POA middleware for BNB Chain, Polygon, Avalanche C-chain.

Example:

web3 = Web3(HTTPProvider(json_rpc_url))
print(f"Connected to blockchain, chain id is {web3.eth.chain_id}. the latest block is {web3.eth.block_number:,}")

# Read and setup a local private key
private_key = os.environ.get("PRIVATE_KEY")
assert private_key is not None, "You must set PRIVATE_KEY environment variable"
assert private_key.startswith("0x"), "Private key must start with 0x hex prefix"
account: LocalAccount = Account.from_key(private_key)
web3.middleware_onion.add(construct_sign_and_send_raw_middleware(account))

# Support Polygon, BNG chain
install_chain_middleware(web3)

# ... code goes here...z
tx_hash = erc_20.functions.transfer(to_address, raw_amount).transact({"from": account.address})
Parameters
  • poa_middleware

    If set, force the installation of proof-of-authority GoEthereum middleware.

    Needed e.g. when using forked Polygon with Anvil.

  • hint (str) – Optional hint for error logs when something goes wrong. Useful for debugging and logging.

  • web3 (web3.main.Web3) –

install_retry_middleware(web3)

Install gracefully HTTP request retry middleware.

In the case your Internet connection or JSON-RPC node has issues, gracefully do exponential backoff retries.

Parameters

web3 (web3.main.Web3) –