Ethers.js – How to Send Parameters and Ethers Simultaneously Using Ethers.js

ethers.js

I have a function with takes amount of token. And at the same time I want to send ethers. So how to write code using Ethers.js which will send ethers and give to transaction _amount value?

  function buy(uint256 _amount)
        public
        payable
    {
        token.transfer(msg.sender, _amount);
    }

Best Answer

You would do so as follows:

await contract.buy(inputAmount, { value: ethersValue });

Where both inputAmount and ethersValue are of type BigNumber.

You still need to add checks on the contract side to assert that user sent the correct msg.value (correct amount of Ethers) to the contract that are needed to buy the provided inputAmount.

Related Topic