【问题标题】:Uniswap JS SDK and Ethers js trying to swap eth for tokensUniswap JS SDK 和 Ethers js 试图将 eth 换成代币
【发布时间】:2021-08-23 00:54:08
【问题描述】:

我正在尝试使用 js 脚本交换代币,该脚本可用于将以太坊换成任何代币。问题是我尝试交换的一些令牌将提供错误“UnhandledPromiseRejectionWarning: InsufficientInputAmountError”。但是,如果我尝试换成不同的令牌,它应该可以正常工作。我知道引发错误的令牌与 uniswap 兼容,因为我通过他们的网站购买了一些并且没有收到错误。

const {ChainId, Fetcher, WETH, Route, Trade, TokenAmount, TradeType, Percent, Token} = require('@uniswap/sdk');
const {ethers} = require("ethers");

let Web3 = require('web3');
let web3 = new Web3(new Web3.providers.HttpProvider("INFURA_KEY"));

function toHex(Amount) {
   return `0x${Amount.raw.toString(16)}`;
}

const chainId = ChainId.MAINNET; 
const tokenAddress = '0x094F00Cb5e31Ab6164E3CAcb654e8D6c2b3b471C';

const provider = new ethers.providers.EtherscanProvider('homestead', 'ETHERSCAN_KEYY');

const init = async () => {
   const gas = await web3.eth.getGasPrice();
   const token = await Fetcher.fetchTokenData(chainId, tokenAddress, provider);

   const weth = WETH[token.chainId];
   const pair = await Fetcher.fetchPairData(token, weth, provider);
   const amountIn = '10000000000000000';
   const route = new Route([pair], weth);

   const trade = new Trade(route, new TokenAmount(weth, amountIn), TradeType.EXACT_INPUT);
  
   const slippageTolerance = new Percent('1', '100');
   const amountOutMin = toHex(trade.minimumAmountOut(slippageTolerance));
   const path = [weth.address, token.address];
   const to = 'MY_KEY';
   const deadline = Math.floor(Date.now()/1000) + 60*20;
   const value = toHex(trade.inputAmount);

   const signer = new ethers.Wallet('MY_PRIVATE_KEY');
   const account = signer.connect(provider);
   const uniswap = new ethers.Contract(
       '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D',
       ['function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts)'],
       account
   );

   const tx = await uniswap.swapExactETHForTokens(
       amountOutMin,
       path,
       to,
       deadline,
       {value, gasPrice: gas}
   );     
   console.log(tx);
}

init();

功能令牌地址:0x6b175474e89094c44da98b954eedeac495271d0f 无效地址:0x094F00Cb5e31Ab6164E3CAcb654e8D6c2b3b471C

问题似乎出在定义 const trade 时,因为脚本不会超出此范围。我已经看过并且不知道大多数代币似乎可以工作但有一些不能工作的任何原因(即使它们在 uniswap 网站上工作)。我对 JS 很陌生,并且正在使用 ethers/uniswap,因此我将不胜感激。

【问题讨论】:

    标签: javascript ethereum web3js ethers.js


    【解决方案1】:

    您必须在 uniswap 上为该令牌创建一个池。 Goerli 网络上的 Eth 到 usdc 交换我也面临同样的问题。首先,将代币添加到池中,然后用以太币创建一个池。

    【讨论】:

      猜你喜欢
      • 2022-12-23
      • 2022-07-29
      • 2022-11-04
      • 2022-07-12
      • 2022-10-13
      • 2022-08-04
      • 1970-01-01
      • 2021-02-08
      • 2018-09-16
      相关资源
      最近更新 更多