Search code examples
ethereumsoliditysmartcontractsweb3js

How to add ETH as parameter when calling solidity contract function on web3


I have created smart contract with function:

function putOrder() external payable {
  require(msg.value == itemPrice);
  (bool sent, bytes memory data) = shopManager.call{value: msg.value}("");
  require(sent, "Failed to purchase");
}

This just checks if eth/bnb value is properly passed to the function and then sends it to manager address.

This is how my function on web3 with react looks like:

const putOrder() = async () => {
    ...
  window.contract.methods.orderStuff().send({from: accounts[0]}).on(
    'receipt', function(){
      processOrder();
    }
  );
    ...
}

Obviously I get an error that itemPrice is not met. So how do I pass eth/bnb value to send trough web3 to contract function call?


Solution

  • You can pass it to the send() function argument as a property named value. Its value is the amount of wei (not the amount of ETH) to be sent.

    It's just an override of the transaction params (the transaction that executes the contract function). So you could also use it to override gas value, nonce and other params if you need.

    .send({
        from: accounts[0],
        value: 1  // 1 wei
    })
    
    .send({
        from: accounts[0],
        value: web3.utils.toWei(1, 'ether')  // 1 ETH == 10^18 wei
    })