[英]Uniswap JS SDK and Ethers js trying to swap eth for tokens
我正在尝试使用可用于将以太坊交换为任何令牌的 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,所以任何见解都将不胜感激。
您必须在 uniswap 上为该令牌创建一个池。 在 Goerli 网络上,Eth to usdc sawap 我也面临同样的问题。首先,将令牌添加到池中,然后用以太创建池。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.