0

I am trying to compile a contract on remix and have run into the following warning :

Use assert(x) if you never ever want x to be false, not in any circumstance (apart from a bug in your code). Use require(x) if x can be false, due to e.g. invalid input or a failing external component.

The parts of my code that use assert are :

assert(checkPlayerExists(msg.sender) == false);
assert(number >= 1 && number <= 10);
assert(msg.value >= minimumBet);

Would love someone to explain this as it seems a bit cryptic.

  • assert(checkPlayerExists(msg.sender)) will return false and abort execution. Try to cut ‘== false’ and run code again. – Roman Frolov Dec 18 '17 at 16:39
  • Thanks for your help. In my case, I want the call to be terminated if the player already exists . Would taking it out not do the opposite? would it be safer using require? – Samuel Dare Dec 18 '17 at 16:52
  • 1
    Rob Hitchens already answered this question before me. As it is stated in docs, assert is meant to be true. – Roman Frolov Dec 18 '17 at 16:58
2

This is a misuse of assert because, depending on input, the expressions may evaluate to false. Use require() instead.

assert() is meant to check for logical errors in the contract itself. Asserts state facts that must always be true under any circumstances, so any possibility of false would be a logic issue.

Consider:

uint balanceAlice = 10;
uint balanceBob = 5;
uint conserveFunds = balanceAlice + balanceBob;

// do stuff
uint conservedFunds = balanceAlice + balanceBob;

// whatever we did, we should always end up with the same funds accounted for.
// ANY departure from this principal means the contract contains a logic error. 
assert(conserveFunds == conservedFunds)

Hope it helps.

  • Thanks for this. I have replace the asserts with require but the warning is still there...is this expected behaviour? – Samuel Dare Dec 18 '17 at 17:03
  • Maybe post the whole works so we can replicate it. I wouldn't expect require to behave the same way. Maybe it's a different complaint. – Rob Hitchens - B9lab Dec 18 '17 at 17:57

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.