You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ropsten网调用Uniswap的swapExactETHForTokens报EXPIRED错误如何解决?

问题根因与解决方案

1. 多余的WETH授权操作

swapExactETHForTokens是原生ETH兑换代币的方法,全程使用原生ETH交互,不需要提前给路由合约授权WETH额度,你写的approve步骤完全冗余,既浪费gas也和当前兑换逻辑无关。只有调用swapExactTokensForTokens这类ERC20代币兑换的方法时,才需要提前授权对应代币的使用额度。

2. EXPIRED错误直接诱因

你设置的1.5gwei的gasPrice远低于Ropsten测试网的最低打包阈值,交易长期滞留在内存池未被打包,等到最终上链时,区块时间已经超过了你传入的20分钟deadline参数,Uniswap路由合约就会抛出UniswapV2Router: EXPIRED错误直接回滚交易。

3. 兑换金额参数错误

你的需求是用0.01 ETH兑换,代码开头也定义了value变量对应0.01 ETH的数值,但实际调用兑换方法时传入的value是对应0.1 ETH的ETHAmount变量,和你的预期不符。

4. 测试网兼容性问题

Ropsten测试网已于2022年被以太坊基金会正式弃用,链上Uniswap V2的流动性池已经几乎没有可用流动性,即使交易成功打包也大概率无法完成兑换,建议改用Sepolia或Goerli测试网进行相关测试。


修正后核心代码示例

const ethers = require('ethers')
const to = '0xD5768aa815D590494277f558Ee5cbeC5FAF1501C'; // 接收地址
const swapValue = ethers.utils.parseUnits('0.01', 'ether') // 实际兑换用的0.01 ETH
// 建议更换为Sepolia测试网
let provider = new ethers.providers.InfuraProvider('sepolia', '你的Infura Key');
const signer = new ethers.Wallet('你的私钥');
const account = signer.connect(provider);
const config = {
    // Sepolia测试网WETH地址: 0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14
    weth: '0xc778417E063141139Fce010982780140Aa0cD5Ab', 
    // Sepolia测试网USDC地址: 0x94a9D9AC8a465CEA79aF72a4Fd3C7d52920B5602
    usdc: '0x07865c6E87B9F70255377e024ace6630C1Eaa37F', 
    // Uniswap V2路由在各EVM兼容测试网地址普遍为0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
    router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
    slippage: 12,
}

const uniswapRouter = new ethers.Contract(
    config.router,
    [
        'function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)',
        'function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)',
    ],
    account
)

const buyToken = async () => {
    try {
        // 动态获取当前网络建议gas价格,避免设置过低导致打包超时
        const gasPrice = await provider.getGasPrice()
        const gas = {
            gasPrice: gasPrice,
            gasLimit: 300000 // 兑换不需要600万这么高的gas limit,30万足够,节省gas
        }
        const tx = await uniswapRouter.swapExactETHForTokens(
            0,
            [config.weth, config.usdc],
            to,
            Math.floor(Date.now() / 1000) + 60 * 30, // 把deadline拉长到30分钟,给打包留足够时间
            {
                ...gas,
                value: swapValue // 用正确的0.01 ETH参数
            }
        );
        console.log(`交易已发送,哈希: ${tx.hash}`);
        const receipt = await tx.wait();
        console.log(`交易已打包,区块号: ${receipt.blockNumber}`);
    } catch (error) {
        console.log('交易出错', error)
    }
}

// 直接调用兑换,不需要approve步骤
buyToken()

内容的提问来源于stack exchange,提问作者ofirthedev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:45:04