MetaMask – How to Call a Payable Function and Send Ether Using MetaMask

metamasksolidityweb3js

I am using web3 and MetaMask for my dApp
I have a deposit function in a contract. Now I know, that I could simply tell the user that he should send ether to a contract and the fallback function would do the rest.

But how can I do a manual deposit function where the user enters an amount on the website in an input field, clicks on a "Make deposit"-button and then needs to accept the MetaMask request where he sends the ethereum he entered together with the request to call deposit()?

Thanks! 🙂

Best Answer

Assume you have a function in your contract like this:

function deposit() public payable{
    // do something here
}

Now, you want to call deposit() and send some ether from your website.

On your website you have the form to input the Ether amount and a button to submit. First you get an instance of your contract:

 var thecontract = web3.eth.contract(contractABI);
 var MyContract = thecontract.at('contract_address');

Then "onclick" of the button you execute a function that contains this:

function makeDeposit(){
   var etherAmount = web3.toBigNumber($("#id_of_field_with_ether_value").val());
   var weiValue = web3.toWei(etherAmount,'ether');
   MyContract.deposit({from: web3.eth.accounts[0], gas: gasValue, value: weiValue}, function(err, res){ })
   }    

Thats it.

Hope it helps.

Related Topic