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
LI.FI transfer statuses that indicate the transfer is complete (no more polling needed) |
Functions
|
Execute prepared cross-chain gas top-up swaps sequentially. |
|
Fetch native token balances and their USD values across chains. |
|
Check gas balances and prepare cross-chain bridge swaps for chains that need topping up. |
|
Wait for cross-chain bridge transfers to complete on destination chains. |
Classes
Per-chain gas configuration for cross-chain feeding. |
|
A prepared cross-chain gas top-up swap. |
|
Result of an executed cross-chain gas top-up. |
- class CrossChainGasConfig
Bases:
objectPer-chain gas configuration for cross-chain feeding.
Allows overriding the default minimum gas threshold and top-up amount on a per-chain basis.
- 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
chain_id (int) –
min_gas_usd (decimal.Decimal) –
top_up_usd (decimal.Decimal) –
- Return type
None
- class CrossChainSwap
Bases:
objectA prepared cross-chain gas top-up swap.
Contains all information needed to execute a bridge transaction from the source chain to a target chain.
- 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().
- __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
source_chain_id (int) –
target_chain_id (int) –
from_amount_raw (int) –
from_amount_usd (decimal.Decimal) –
target_balance_usd (decimal.Decimal) –
min_gas_usd (decimal.Decimal) –
top_up_usd (decimal.Decimal) –
transaction_request (dict) –
quote (eth_defi.lifi.quote.LifiQuote) –
- Return type
None
- class CrossChainSwapResult
Bases:
objectResult 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
tx_hash (hexbytes.main.HexBytes) –
- 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
- Returns
Tuple of (balances_native, balances_usd) where each is a dict mapping chain_id to balance.
balances_nativeis in native token units (e.g. ETH),balances_usdis 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_usdworth 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_NAMESand are passed directly to the LI.FI API asfromChain/toChainparameters, which also uses numeric chain IDs. The corresponding RPC URLs are expected inJSON_RPC_{CHAIN_NAME}environment variables, resolved viaeth_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 fromUSDC_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
tqdmprogress bar while fetching quotes (defaultTrue)
- Returns
List of prepared swaps. Empty if all chains have sufficient gas.
- Return type
- 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 viais_valid()), it is automatically re-fetched before execution.- Parameters
wallet (eth_defi.hotwallet.HotWallet) – Hot wallet to sign transactions with
source_web3 (web3.main.Web3) – Web3 connection to the source chain
swaps (list[eth_defi.lifi.crosschain.CrossChainSwap]) – List of prepared swaps from
prepare_crosschain_swaps()progress (bool) – Show a
tqdmprogress bar during execution (defaultTrue)max_quote_age_seconds (float) – Maximum acceptable quote age in seconds before re-fetching (default 120s)
- Returns
List of results with transaction hashes
- Raises
Reverted – If any transaction fails on-chain
- Return type
- 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/statusendpoint for each executed swap until all transfers reach a terminal status (DONEorFAILED) or the timeout is reached.- Parameters
results (list[eth_defi.lifi.crosschain.CrossChainSwapResult]) – List of executed swap results from
execute_crosschain_swaps()max_wait_seconds (float | None) – Maximum time to wait in seconds. If None, uses 1.5x the maximum
execution_durationacross all swaps, with a minimum of 300s.poll_interval (float) – Seconds between status polls (default 10s)
progress (bool) – Show a
tqdmprogress bar during waiting (defaultTrue)
- Returns
Dict mapping tx_hash → final LI.FI status response dict. Each response contains a
statusfield (DONE,FAILED,PENDING, etc.) and optionally areceivingdict with the destination transaction hash.- Return type