Reputation: 3
I am using web3.js library and I am trying to buy a token by calling swapExactETHForTokens method from UniswapV2Router02 smart contract, but I don't know why my transaction fails. I approved WETH for this transaction, but still get an error with the following status:
Fail with error 'UniswapV2: TRANSFER_FAILED'
My code:
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();
Transaction details on etherscan: https://etherscan.io/tx/0x4c6f507ed95b2889bdb929a34dbbe0114db168c2462ce21778eeed9dc4a894eb
Smart contract of token which I am trying to buy: https://etherscan.io/address/0x0913dDAE242839f8995c0375493f9a1A3Bddc977#code
Upvotes: 0
Views: 1600