【发布时间】:2022-11-07 19:18:10
【问题描述】:
我正在使用 web3.js 库,我试图通过调用 swapExactETHForTokens 方法来购买令牌 UniswapV2Router02 smart contract,但我不知道为什么我的交易失败。我批准了此交易的 WETH,但仍然收到以下状态的错误:
失败并出现错误“UniswapV2:TRANSFER_FAILED”
我的代码:
const swapTokens = async () => { const PRIVATE_KEY = 'my private key goes here'; web3.eth.accounts.wallet.add(PRIVATE_KEY); const myAccount = web3.eth.accounts.wallet[0].address; const WETHAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'; const swapRouterAddress = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D'; const routerContract = new web3.eth.Contract( UNISWAP_V2_ROUTER_ABI, swapRouterAddress, ); const tokenToBuyAddress = '0x0913dDAE242839f8995c0375493f9a1A3Bddc977'; const deadline = Math.floor(Date.now() / 1000) + 60 * 20; const block = await web3.eth.getBlock('latest'); const gasLimit = Math.round(block.gasLimit / block.transactions.length); const amountToBuy = 0.01; const result = await routerContract.methods .swapExactETHForTokens( web3.utils.toHex(0), [WETHAddress, tokenToBuyAddress], myAccount, deadline, ) .send({ from: myAccount, gasLimit, value: web3.utils.toWei(`${amountToBuy}`, 'ether'), }); console.log('result: ', result); } swapTokens();etherscan 上的交易详情:https://etherscan.io/tx/0x4c6f507ed95b2889bdb929a34dbbe0114db168c2462ce21778eeed9dc4a894eb
我要购买的代币智能合约:https://etherscan.io/address/0x0913dDAE242839f8995c0375493f9a1A3Bddc977#code
【问题讨论】:
标签: node.js ethereum web3js uniswap