Solidity – How to Set msg.value in Function Call Using Ethers.js

ethers.jsfrontendjavascriptsolidity

I've got a function in my smart contract and i want it to take an argument that sets the msg.value and then pays it into the contract:

function deposit(uint256 amount) public payable {
    msg.value = amount
}

I'm trying to make a button on a website that sends a fixed amount into the contract like this:

async function sendTransaction() {
   if (typeof window.ethereum !== 'undefined') {
      await requestAccount()
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const contract = new ethers.Contract(contractAddress, contract.abi, signer);
      const transaction = await contract.deposit()
      await transaction.await()
   }

my question is, is there a way to set the msg.value from within the function its self, so i can call contract.deposit(value), or is there an easier way to set the value using ether.js?

Best Answer

You cannot change msg.value in the contract, it represents the amount of ether sent.

On frontend:

const transaction = await contract.deposit({ value: ethers.utils.parseEther("0.1") })
//sends 0.1 eth
await transaction.wait()

Change the 0.1 to the amount of ether you would like to send.

Related Topic