Solidity – Cannot Send Ether to a Payable Function in Truffle Unit Test

payablesoliditytestingtestrpctruffle

I am debugging a bug happened on my truffle solidity test. I can narrow down the problem to an exception happened in the payable modifier.

my contract code:

import "zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol";

contract MyToken is ERC721Token { 
  function MyToken() ERC721Token(NAME, SYMB) public payable {
  }
  function purchase(uint256 _tokenId) public payable {
    // all the code in this function is commented out when I do the test
  }
}

my test code:

MyToken myToken = MyToken(contractAddress);
myToken.purchase.value(1000000000000000000).gas(1000000000000000000)(0);

exception:

     Error: VM Exception while processing transaction: revert
  at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
  at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
  at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
  at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
  at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
  at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
  at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
  at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
  at endReadableNT (_stream_readable.js:1101:12)
  at process._tickCallback (internal/process/next_tick.js:114:19)

Best Answer

I'm adding the answer since its in the comments above and might be helpful for someone.

The transaction has been reverted because the testing contract has no balance. When you need to test the contact transactions via Solidity the sender is the testing contract. To allow the testing contract to make transactions you need to set the initial balance.

uint public initialBalance = 1 ether; // or any other value

this property must to be added to your testing contract. ref

Related Topic