0

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! :)

1

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.

  • Thank you, seems that this will help! How will the code need to be, if the contract needs a parameter, for example an address? Like "function deposit(address _address) ..."? – dkb Apr 12 '18 at 9:44
  • 1
    Just pass the parameter first and then the transaction deatils, like this: MyContract.deposit(_address, {from: web3.eth.accounts[0], gas: gasValue, value: weiValue}, function(err, res){ }). If I had answered you question please acceptit by clicking the check mark. good luck. – Jaime Apr 12 '18 at 12:46
  • Thanks for the answer, that's exactly what I tried. But I got: "Invalid number of arguments to Solidity function" – dkb Apr 12 '18 at 15:13
  • Did you change the function to accept the address parameter? function deposit(address _address) public payable you must do this for it to work. On the other side if you are requesting the address of the person making the deposit you can use msg.sender inside the payable. – Jaime Apr 12 '18 at 15:25
  • Yes the function needs already an address parameter. I know that I can use msg.sender but I would like to make it possible to deposit to others addresses. – dkb Apr 12 '18 at 16:20

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.