6

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?

2 Answers 2

11

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.

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

if I have price in wei (too big number for JavaScript, like price = 20000000000000000), I use:

const tx = await contract2.mint(tokenID, { value: ethers.BigNumber.from(price) });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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