1

this function :

  web3.eth.sendTransaction({from:myaddress,to:toaddress, value:web3.toWei(1, "ether")}, function(err, transactionHash) {
  if (!err)
    console.log(transactionHash); 
  });

completely work for send ETH from ethereum-acount-address to ethereum-acount-address BUT when i set an smartcontract address for toaddress meta mask return

Transaction Error. Exception thrown in contract code.

my solidity contract is

pragma solidity ^0.4.17;

contract mysmartContract{


        function whitdrawETH() payable public {

        }

        function getContactEthBalance() constant returns(uint) {

        return this.balance;
        }

    }
1

To make smart-contract acceptable for ether you need to implement fallback function:

function() public payable { }

Contracts that receive Ether directly (without a function call, i.e. using send or transfer) but do not define a fallback function throw an exception, sending back the Ether (this was different before Solidity v0.4.0). So if you want your contract to receive Ether, you have to implement a fallback function.

In case you want to send ether to your smart-contract mysmartContract with whitdrawETH() function you need to send methodSignature of this function to data field like this:

web3.eth.sendTransaction({
   from: myaddress,
   to: toaddress,
   data: web3.eth.abi.encodeFunctionSignature('whitdrawETH()')
   value: web3.toWei(1, "ether")
}
2
  • web3.eth.abi does no longer exists with MetaMask. It seems it moved elsewhere. – user2284570 Aug 15 '19 at 8:26
  • @user2284570 web3.eth.abi functions are a part of web3@1.x.x: web3js.readthedocs.io/en/v1.2.0/web3-eth-abi.html. Visibility of those functions relates to the version of the web3 library do you use in your Dapp. Metamask has nothing to do with it. – Victor Baranov Sep 8 '19 at 8:03
0

This is what worked for me:

receive() external payable { }

This is the function that is executed on plain Ether transfers (e.g. via .send() or .transfer()). If no such function exists, but a payable fallback function exists, the fallback function will be called on a plain Ether transfer. If neither a receive Ether nor a payable fallback function is present, the contract cannot receive Ether through regular transactions and throws an exception.

More information here: https://docs.soliditylang.org/en/v0.6.2/contracts.html#receive-ether-function

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.