4

For some reason I cant figure out how to send ether to a contract when testing in truffle. This is my attempt:

 await myContract.send(10, {from: accounts[0]});

the error message is:

 Error: VM Exception while processing transaction: revert

I get the same error message if I try:

 let txHash = await web3.eth.sendTransaction({from: accounts[0], to: myContract.address, value: 10 });

Any idea how to get this to work?

Thanks!

2

Fallback functions

To create a contract which can receive eth via the .send() method, you need to declare a fallback function in your contract.

It's pretty easy to do this by simply creating a payable function with no name in your contract like this:

// @notice Will receive any eth sent to the contract
function () external payable {
}

If you want to do anything with the funds inside a payable function you can use the msg.sender and msg.value variables to work out who and how much was sent.

Full example:

pragma solidity ^0.4.19;

/// @title An example contract that demonstrates making a payment via the send function
contract Test {
  /// @notice Logs the address of the sender and amounts paid to the contract
  event Paid(address indexed _from, uint _value);

  /// @notice Any funds sent to this function will be unrecoverable
  /// @dev This function receives funds, there is currently no way to send funds back
  function () external payable {
    Paid(msg.sender, msg.value);
  }
}

Output:

When the above contract is compiled, created and send funds, you get the following output:

truffle(develop)> Test.new().then(c => c.send(10, {from: '0x627306090abab3a6e1400e9345bc60c78a8bef57'}).then(tx => {console.log(tx.tx); tx.logs.length && console.log(tx.logs[0].event, tx.logs[0].args)}))
0x911ceb59724001b3cb99a035281745b4af5b02a10a1c79906b4c527f8c462db8
Paid { _from: '0x627306090abab3a6e1400e9345bc60c78a8bef57',
  _value: BigNumber { s: 1, e: 1, c: [ 10 ] } }
1

You can use web3 method 'sendTransaction'. things to be note that web3 methods always handle ethereum in wei format, so when you transfer ether you should use wei format

first Deploy your contract as follows (assume your contract name is 'myContract')

myContract.deployed().then(function(instance){myContract=instance})

now use sendTransaction to transfer ether to this contract as follows

myContract.sendTransaction({from:web3.eth.coinbase,value:10000000000000000000})

youcan use 'toWei' method to find out ether in wei as follows

 web3.toWei(10,"ether")

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.