Truffle – How to Send Ether to a Contract in Truffle Test

truffle

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!

Best Answer

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 ] } }
Related Topic