How to use swapExactETHForTokens methods with ethers.js properly?

Viewed 1271

I want to use swapExactETHForTokens() method inside node.js app with ethers.js library, but transaction always fails because of not including variable msg.value (from docs: 'The amount of ETH to send.' It's present in docs but I don't know how can I incude it inside code) But in method declaration this var is not present, only var amountOutMin. So how is it possible to use this var and make the swap success? My code:


const WBNBHERORouterContract = new ethers.Contract(
    router,
    [
        `function getAmountsOut(uint amountIn, address[] memory path) internal view returns (uint[] memory amounts)`,
        `function swapExactETHForTokens(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts)`
    ],
    signer
);
const tx = await WBNBHERORouterContract.swapExactETHForTokens(
            wbnbAmount,
            minAmountToBuy,
            [WBNB, HERO],
            wallet.address,
            Date.now() + 1000 * 60,
            {gasLimit: 251234}
        )

receipt = await tx.wait();
1 Answers

I think it would be necessary to specify the address that the WBNB sends and how much it sends

  const tx = await WBNBHERORouterContract.swapExactETHForTokens(
            wbnbAmount,
            minAmountToBuy,
            [WBNB, HERO],
            wallet.address,
            Date.now() + 1000 * 60,
            {from : ..... , value: ... , gasLimit: 251234}
        ) 
    
receipt = await tx.wait();
Related