Arbitrum网络Uniswap V3 Python兑换代币遇Gas资金不足错误
问题解决:Arbitrum网络WETH存币Gas费用过高/不足问题
错误原因分析
你遇到的insufficient funds错误核心不是gas数量问题,而是gas价格设置过高:
- 你把
maxFeePerGas设为100 * 10**9(100Gwei),但Arbitrum当前基础费通常仅0.1-1Gwei,这个价格是实际需求的几十倍甚至上百倍。 - 错误信息里的
want 20000000400000000是200000(gas)*100Gwei + 0.0000000004ETH的总和,远超过你账户里的0.004ETH(4014074730000000 wei)。 - 把gas降到200触发
intrinsic gas too low是必然的,哪怕最简单的合约调用(比如WETH deposit)也需要至少几万gas,200连基础交易门槛都达不到。
修复方案
要实现Arbitrum的最低手续费,核心是用合理的gas价格+自动估算gas用量,修改后的代码如下:
from web3 import Account, Web3 from abi import UNISWAP_V3_ROUTER2_ABI, WETH9_ABI, MIN_ERC20_ABI private_key = "你的私钥" chain_id = 42161 rpc_endpoint = "https://arb1.arbitrum.io/rpc" web3 = Web3(Web3.HTTPProvider(rpc_endpoint)) account = Account.from_key(private_key) amount_in = 0.0000000004 weth_address = web3.toChecksumAddress("0x35751007a407ca6feffe80b3cb397736d2cf4dbe") swap_router02_address = web3.toChecksumAddress("0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45") # 加载合约 weth_contract = web3.eth.contract(address=weth_address, abi=WETH9_ABI) # 1. 构建基础交易参数,暂不指定gas base_tx = { 'chainId': web3.eth.chain_id, "maxPriorityFeePerGas": web3.eth.max_priority_fee, # 采用网络当前优先级费 "maxFeePerGas": 2 * 10**9, # Arbitrum合理maxFee范围1-3Gwei,可按需微调 'nonce': web3.eth.get_transaction_count(account.address), 'value': int(web3.to_wei(amount_in, 'ether')) } # 2. 自动估算该交易所需gas用量 estimated_gas = weth_contract.functions.deposit().estimate_gas(base_tx) # 加10%缓冲避免网络波动导致gas不足,比例可调整5%-15% base_tx['gas'] = int(estimated_gas * 1.1) # 3. 签名并发送交易 signed_transaction = web3.eth.account.sign_transaction(base_tx, private_key) tx_hash = web3.eth.send_raw_transaction(signed_transaction.rawTransaction) tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash) print(f"tx hash: {Web3.to_hex(tx_hash)}")
关键优化点
- 合理设置gas价格:Arbitrum的
maxFeePerGas设为1-3Gwei完全足够,这是降低手续费的核心。 - 自动估算gas:用
estimate_gas获取合约调用实际需要的gas量,比硬编码更准确,避免浪费gas。 - gas缓冲机制:估算后加少量缓冲,防止网络波动导致交易失败。
额外验证建议
发送前可手动计算总费用:gas * maxFeePerGas + value,确保该值小于账户余额(可通过web3.eth.get_balance(account.address)查询)。
内容的提问来源于stack exchange,提问作者Zevs
相关产品推荐
相关产品推荐

