0

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?

1

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.await()

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

1
  • Thank you so much! i literally did this without the curly braces, feel like such a fool!
    – PopFendi
    Jun 27 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.