Requirements

No muffin is created equal. Especially our SpaceMuffin. And I believe you want to protect it.

I want to help you Amiral. Let's make an authorisation system to eat the SpaceMuffin.

Require

What is it?

require is a keyword in Solidity. It is a built-in function allowing you to assert something. If the assertion succeed, then the code is executed normally. If the assertion fail, the execution stops and the state of the contract is restored

function division(uint dividend, uint divisor) pure public returns (uint) {
  require(divisor > 0);
  return dividend / divisor;
}

Formal Syntax

In a general case, require syntax is the following

require(<boolean expression>);

An expression can be:

  • A literal, either true or false
  • A function call, for a function that returns a boolean
  • A logical expression, a == 2

SpaceMuffin - Protection 1

Exercise
Correct!
False!

Loading...

Before one can eat, you check that the password is Super Super Muffin
pragma solidity ^0.4.24; contract SpaceMuffin { uint public bite = 0; function eat(bytes32 _password) public { // It should require the correct password // Then the hungry user is allow to take a bite bite = bite + 1; } }

Modifiers

Imagine that you know have to allow people to touch the SpaceMuffin. You would have to implement the same function again! It would be very impractical. Therefore, you can wrap the check of the password into a modifier.

What is it?

A modifier is a pretreatment applied to function code.

modifier securityCheck(bytes32 _password) {
  require(_password == "Super Super Muffin");
  _;
}

function eat(bytes32 _password) public securityCheck(_password) {
  bite = bite + 1;
}

Formal Syntax

modifier <name>([arg1, arg2, ...]) {
  [require(<e>);]* // all the requirements

  _; // means that the function code will be inserted here

  // I didn't write anything here, but in the future you might see some useful applications
}

There can even be complex requirements, such as prefunctions.

Function signature has

function <name> ([arg1, arg2, ...]) <visibility> [mutability] [modifier1, modifier2, ...] [returns ([ret1, ret2, ...])] ;

Amiral tip If the modifier your calling as no argument, you can simply write its name without parenthesis

Exercise
Correct!
False!

Loading...

Implement touch, a pure function that returns true if the user has touched the muffin
pragma solidity ^0.4.24; contract SpaceMuffin { uint public bite = 0; // Write securityCheck modifier // You will have to update this function according to the code above function eat(bytes32 _password) public { require(); bite = bite + 1; } // You should implement touch here }