4

SOLUTION BELOW

How do I go about testing the following fallback function:

function () public payable {
  revert();
}

being that the function does not have a function name, what do I need to do to test it? I tried using a function name that does not exist like this:

it("should not accept ETH deposits", async function() {
  let xferAmt = web3.toWei(0.5, "ether");
  await contract.dummyfunction({value: xferAmt}).should.be.rejectedWith(EVMThrow);
})

But truffle complains about the dummyfunction not being a function.

Thanks. A.

SOLUTION

function () public {}

test:

it("should not accept ETH deposits", async function() {
  let xferAmt = 1;
  await contract.sendTransaction({value: xferAmt}).should.be.rejectedWith(EVMThrow);
});
4
  • you should use contract.send
    – mirg
    Jun 15 '18 at 11:56
  • What version of web3js are you using? 0.2 or 1.0? Jun 15 '18 at 11:56
  • @mirg - I tried contract.send and then got a strange error: new BigNumber() not a number: [object Object] which is odd. as there is a only a revert
    – adam
    Jun 15 '18 at 12:02
  • @Andromelus - whatever comes with truffle.. looks like "0.18.4"
    – adam
    Jun 15 '18 at 12:04
4

Make the fallback function:

function () public {
  // dont receive ether via fallback method (by not having 'payable' modifier on this function). 
}

See OpenZeppelin examples: https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/HasNoEther.sol

And test it with sendTransaction:

it("...should reject sending ether directly to the contract.", async () => {
  instance = await Contract.deployed();
  await assertRevert(
    instance.sendTransaction(
      { from: myAddress, value: 1 }
    )
  );
});
0

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.