lifi.crosschain

Documentation for eth_defi.lifi.crosschain Python module.

Cross-chain gas feeding using LI.FI.

Check gas balances across multiple EVM chains and bridge native tokens from a source chain to any target chain that is running low.

Example:

from decimal import Decimal
from eth_defi.hotwallet import HotWallet
from eth_defi.lifi.crosschain import prepare_crosschain_swaps, execute_crosschain_swaps
from eth_defi.provider.multi_provider import create_multi_provider_web3

source_web3 = create_multi_provider_web3(os.environ["JSON_RPC_ARBITRUM"])
target_web3s = {
    8453: create_multi_provider_web3(os.environ["JSON_RPC_BASE"]),
    137: create_multi_provider_web3(os.environ["JSON_RPC_POLYGON"]),
}

wallet = HotWallet.from_private_key(os.environ["PRIVATE_KEY"])
wallet.sync_nonce(source_web3)

swaps = prepare_crosschain_swaps(
    wallet=wallet,
    source_web3=source_web3,
    target_web3s=target_web3s,
    min_gas_usd=Decimal("5"),
    top_up_usd=Decimal("20"),
)

for swap in swaps:
    print(swap)

results = execute_crosschain_swaps(
    wallet=wallet,
    source_web3=source_web3,
    swaps=swaps,
)

Module Attributes

LIFI_TERMINAL_STATUSES

LI.FI transfer statuses that indicate the transfer is complete (no more polling needed)

Functions

execute_crosschain_swaps(wallet, ...[, ...])

Execute prepared cross-chain gas top-up swaps sequentially.

fetch_crosschain_gas_balances(target_web3s, ...)

Fetch native token balances and their USD values across chains.

prepare_crosschain_swaps(wallet, ...[, ...])

Check gas balances and prepare cross-chain bridge swaps for chains that need topping up.

wait_crosschain_swaps(results[, ...])

Wait for cross-chain bridge transfers to complete on destination chains.

Classes

CrossChainGasConfig

Per-chain gas configuration for cross-chain feeding.

CrossChainSwap

A prepared cross-chain gas top-up swap.

CrossChainSwapResult

Result of an executed cross-chain gas top-up.

class CrossChainGasConfig

Bases: object

Per-chain gas configuration for cross-chain feeding.

Allows overriding the default minimum gas threshold and top-up amount on a per-chain basis.

chain_id: int

Chain ID this configuration applies to

min_gas_usd: decimal.Decimal

Minimum gas balance in USD before triggering a top-up

top_up_usd: decimal.Decimal

Amount of gas to bridge (in USD) when topping up

__init__(chain_id, min_gas_usd, top_up_usd)
Parameters
Return type

None

class CrossChainSwap

Bases: object

A prepared cross-chain gas top-up swap.

Contains all information needed to execute a bridge transaction from the source chain to a target chain.

source_chain_id: int

Source chain ID where funds are bridged from

target_chain_id: int

Target chain ID where gas is needed

from_amount_raw: int

Amount of source token to send (raw units: wei for native, or token decimals for ERC-20)

from_amount_usd: decimal.Decimal

Value of the bridged amount in USD

target_balance_usd: decimal.Decimal

Current gas balance on the target chain in USD

min_gas_usd: decimal.Decimal

Minimum gas threshold that triggered this swap (USD)

top_up_usd: decimal.Decimal

Requested top-up amount in USD

transaction_request: dict

Ready-to-sign transaction request from LI.FI

Contains from, to, data, value, gasLimit, gasPrice, chainId.

quote: eth_defi.lifi.quote.LifiQuote

The LI.FI quote used to build this swap

is_valid(max_age_seconds=120)

Check if the underlying quote is still fresh enough to execute.

Delegates to is_valid().

Parameters

max_age_seconds (float) – Maximum acceptable age in seconds (default 120s)

Return type

bool

__init__(source_chain_id, target_chain_id, from_amount_raw, from_amount_usd, target_balance_usd, min_gas_usd, top_up_usd, transaction_request, quote)
Parameters
Return type

None

class CrossChainSwapResult

Bases: object

Result of an executed cross-chain gas top-up.

swap: eth_defi.lifi.crosschain.CrossChainSwap

The swap that was executed

tx_hash: hexbytes.main.HexBytes

Transaction hash on the source chain

__init__(swap, tx_hash)
Parameters
Return type

None

fetch_crosschain_gas_balances(target_web3s, wallet_address, api_timeout=30)

Fetch native token balances and their USD values across chains.

Parameters
  • target_web3s (dict[int, web3.main.Web3]) – Dict mapping chain_id to Web3 instance

  • wallet_address (str) – Wallet address to check balances for

  • api_timeout (float) – API request timeout in seconds

Returns

Tuple of (balances_native, balances_usd) where each is a dict mapping chain_id to balance. balances_native is in native token units (e.g. ETH), balances_usd is the USD equivalent.

Return type

tuple[dict[int, decimal.Decimal], dict[int, decimal.Decimal]]

prepare_crosschain_swaps(wallet, source_web3, target_web3s, min_gas_usd=Decimal('5'), top_up_usd=Decimal('20'), source_token_address='0x0000000000000000000000000000000000000000', chain_configs=None, slippage=0.03, api_timeout=30, progress=True)

Check gas balances and prepare cross-chain bridge swaps for chains that need topping up.

Checks the native token balance on each target chain. If any chain has less than min_gas_usd worth of native token, prepares a LI.FI bridge quote to send tokens from the source chain.

The source token can be either the native gas token (default) or an ERC-20 token such as USDC. When using an ERC-20 source token, the amount to bridge is calculated using the token’s on-chain decimals via TokenDetails, and the USD price is fetched from the LI.FI token API. LI.FI handles the swap from the source token to the target chain’s native token.

Chains are identified by numeric EVM chain IDs (e.g. 1 for Ethereum, 42161 for Arbitrum). These are our internal chain IDs from eth_defi.chain.CHAIN_NAMES and are passed directly to the LI.FI API as fromChain/toChain parameters, which also uses numeric chain IDs. The corresponding RPC URLs are expected in JSON_RPC_{CHAIN_NAME} environment variables, resolved via eth_defi.provider.env.read_json_rpc_url().

Parameters
  • wallet (eth_defi.hotwallet.HotWallet) – Hot wallet that holds funds on the source chain

  • source_web3 (web3.main.Web3) – Web3 connection to the source chain. The chain ID is read from source_web3.eth.chain_id.

  • target_web3s (dict[int, web3.main.Web3]) – Dict mapping chain_id to Web3 connection for each target chain. Keys are numeric EVM chain IDs.

  • min_gas_usd (decimal.Decimal) – Default minimum gas balance in USD. Chains below this trigger a top-up.

  • top_up_usd (decimal.Decimal) – Default amount to bridge in USD when topping up.

  • source_token_address (str) – Address of the token to bridge from the source chain. Use LIFI_NATIVE_TOKEN_ADDRESS (default) for native gas token, or an ERC-20 address (e.g. USDC from USDC_NATIVE_TOKEN).

  • chain_configs (dict[int, eth_defi.lifi.crosschain.CrossChainGasConfig] | None) – Optional per-chain overrides for min_gas_usd and top_up_usd. Keys are chain IDs.

  • slippage (float) – Maximum allowed slippage as a decimal (0.03 = 3%)

  • api_timeout (float) – API request timeout in seconds

  • progress (bool) – Show a tqdm progress bar while fetching quotes (default True)

Returns

List of prepared swaps. Empty if all chains have sufficient gas.

Return type

list[eth_defi.lifi.crosschain.CrossChainSwap]

execute_crosschain_swaps(wallet, source_web3, swaps, progress=True, max_quote_age_seconds=120)

Execute prepared cross-chain gas top-up swaps sequentially.

Signs and broadcasts each swap transaction on the source chain. Waits for each transaction to confirm before proceeding to the next.

If a quote is older than max_quote_age_seconds (checked via is_valid()), it is automatically re-fetched before execution.

Parameters
Returns

List of results with transaction hashes

Raises

Reverted – If any transaction fails on-chain

Return type

list[eth_defi.lifi.crosschain.CrossChainSwapResult]

LIFI_TERMINAL_STATUSES = {'DONE', 'FAILED'}

LI.FI transfer statuses that indicate the transfer is complete (no more polling needed)

wait_crosschain_swaps(results, max_wait_seconds=None, poll_interval=10, progress=True)

Wait for cross-chain bridge transfers to complete on destination chains.

Polls the LI.FI GET /v1/status endpoint for each executed swap until all transfers reach a terminal status (DONE or FAILED) or the timeout is reached.

Parameters
Returns

Dict mapping tx_hash → final LI.FI status response dict. Each response contains a status field (DONE, FAILED, PENDING, etc.) and optionally a receiving dict with the destination transaction hash.

Return type

dict[hexbytes.main.HexBytes, dict]