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

调用swapExactTokensForTokens执行代币兑换时报invalid BigNumber value错误

问题修复方案

你代码中存在多处错误,对应修复如下:

核心错误点(直接触发BigNumber报错的原因)

  • 变量引用错误:const amountInHex = web3.utils.toHex('amountInWei') 这行你给amountInWei加了单引号,实际传入的是字符串"amountInWei"而非你定义的数值,转译后的结果无效,直接导致参数解析失败。
  • 方法调用错误:等待交易确认的接口是tx.wait(),你写成了不存在的tx.await()。
  • 收款地址错误:swapExactTokensForTokens的to参数不能填路由合约地址,要填你自己的收款钱包地址,否则兑换后的代币会直接打入路由合约无法找回。

遗漏的必要步骤

兑换ERC20代币之前,必须先调用对应代币的approve方法,给路由合约授权足够的转账额度,否则就算参数正确交易也会失败。

可选参数优化

Ubeswap路由要求deadline是秒级Unix时间戳,你用的Date.now()是毫秒级,要除以1000取整,避免参数超出合约限制。
ethers本身支持直接传入十进制字符串或者BigNumber类型作为数值参数,不需要手动转十六进制,也不需要额外引入web3做格式转换,可以减少出错概率。

修正后的关键代码示例

const init = async () => {
    //get data about tokens and pairs
    const token1 = await Fetcher.fetchTokenData(chainId, cusdAddressAlfa, customHttpProvider)
    const token2 = await Fetcher.fetchTokenData(chainId, celoAddressAlfa, customHttpProvider)
    const pair = await Fetcher.fetchPairData(token1, token2, customHttpProvider)
    const route = new Route([pair], token1)

    const amountInWei = '100000000000000000' // 1 cUSD
    const path = [token1.address, token2.address]
    const amountOut = await UniswapV2RouterContract.getAmountsOut(amountInWei, path)   
    // 滑点可以自己调整,这里留1%滑点避免交易因价格波动失败
    const amountOutMin = amountOut[1].mul(99).div(100)
    const to = account.address // 改为自己的钱包地址
    const deadline = Math.floor(Date.now() / 1000) + 60 * 10 // 转成秒级时间戳

    // 先给路由授权cUSD额度
    const cusdABI = ["function approve(address spender, uint256 amount) external returns (bool)"]
    const cusdContract = new ethers.Contract(cusdAddressAlfa, cusdABI, account)
    const approveTx = await cusdContract.approve(UniswapV2RouterAddress, amountInWei)
    await approveTx.wait()
    console.log("授权成功")

    // 执行兑换
    const tx = await UniswapV2RouterContract.swapExactTokensForTokens(
        amountInWei,
        amountOutMin,
        path,
        to,
        deadline    
    )

    const receipt = await tx.wait()

    console.log(`Transaction hash: ${tx.hash}`)
    console.log(`Transaction was mined in block ${receipt.blockNumber}`)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:06:04