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

使用SunSwap调用swapExactETHForTokens遇UniswapV2Library错误求助

SunSwap交易报错UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT解决方案

问题代码

const { trx_amount, private_key } = request.body;
var tronWeb = new TronWeb({
  fullHost: "https://api.trongrid.io",
  headers: { "TRON-PRO-API-KEY": "xxxxxxxxxxxxxxxxxxxxxxxxx" },
  privateKey: private_key,
});
let contract = await tronWeb.contract().at("TKzxdSv2FZKQrEqkKVgp5DcwEXBEKMg2Ax");
const currentTime = Math.floor(Date.now() / 1000);
const deadline = currentTime + (20 * 60); // 20 minutes in seconds
try {
  const swap = await contract.methods.swapExactETHForTokens(
    trx_amount,
    [
      "TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR",
      "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    ],
    "TRpZ1F9xxxxxxxxxxxxxxxxxxxxxxxx",
    deadline
  ).send();
 response.status(200).send({
   hash: swap,
   message: "You swap is under process",
 });
} catch (e) {
  response.status(400).send({
    message: "There was an error",
    error: e,
  });
}

报错核心原因

这个错误是因为交易中实际投入的TRX数量为0,根源是两个关键参数传递错误:

  • swapExactETHForTokens的第一个参数是amountOutMin(你期望得到的最小代币数量),不是要投入的TRX数量
  • 没有在交易中指定要转入合约的TRX金额,导致合约未收到任何输入资产,触发输入不足的校验报错

修正后的代码

const { trx_amount, private_key } = request.body;
var tronWeb = new TronWeb({
  fullHost: "https://api.trongrid.io",
  headers: { "TRON-PRO-API-KEY": "xxxxxxxxxxxxxxxxxxxxxxxxx" },
  privateKey: private_key,
});
let contract = await tronWeb.contract().at("TKzxdSv2FZKQrEqkKVgp5DcwEXBEKMg2Ax");
const currentTime = Math.floor(Date.now() / 1000);
const deadline = currentTime + (20 * 60); // 20分钟有效期
try {
  // 建议根据滑点设置合理的最小输出代币数量,示例用0仅作演示,实际需按行情计算(比如允许1%滑点则设为理论输出的99%)
  const amountOutMin = 0; 
  // 将TRX数量转换为Sun单位(1TRX = 1000000 Sun)
  const trxAmountInSun = tronWeb.toSun(trx_amount);
  const swap = await contract.methods.swapExactETHForTokens(
    amountOutMin, // 第一个参数为最小输出代币数量
    [
      "TNUC9Qb1rRpS5CbWLmNMxXBjyFoydXjWFR",
      "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
    ],
    "TRpZ1F9xxxxxxxxxxxxxxxxxxxxxxxx",
    deadline
  ).send({
    callValue: trxAmountInSun // 这里指定要转入合约的TRX金额(Sun单位)
  });
 response.status(200).send({
   hash: swap,
   message: "交易处理中"
 });
} catch (e) {
  response.status(400).send({
    message: "交易出错",
    error: e,
  });
}

额外注意事项

  • amountOutMin不要直接设为0,建议通过查询SunSwap池子的代币比例计算理论输出后,乘以滑点系数(比如0.99对应1%滑点),避免因价格波动导致交易失败
  • 确认trx_amount的单位:如果前端传入的是TRX数量(如1.5),必须用tronWeb.toSun()转换为Sun;如果已经是Sun单位则跳过转换
  • 确保发起交易的钱包地址有足够的TRX余额(需包含交易手续费)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 00:06:10