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:
If you want to do anything with the funds inside a payable function you can use the
msg.sender
andmsg.value
variables to work out who and how much was sent.Full example:
Output:
When the above contract is compiled, created and send funds, you get the following output: