DEV Community

Cover image for Day 16 - Require Statement
Vedant Chainani
Vedant Chainani

Posted on • Edited on

Day 16 - Require Statement

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 16 of 30 in Solidity Series
Today I Learned About Require Statement in Solidity.

The require statements declare prerequisites for running the function i.e. it declares the constraints which should be satisfied before executing the code. It accepts a single argument and returns a boolean value after evaluation, it also has a custom string message option. If false then exception is raised and execution is terminated. The unused gas is returned back to the caller and the state is reversed to its original state.

Following are some cases when require type of exception is triggered :

  • When require() is called with the arguments which result as false.
  • When a function called by a message does not end properly.
  • When a contract is created using the new keyword and the process does not end properly.
  • When a codeless contract is targeted to an external function.
  • When ethers are sent to the contract using the public getter method.
  • When .transfer() method fails.
    • When an assert is called with a condition that results in false.
    • When a zero-initialized variable of a function is called.
    • When a large or a negative value is converted to an enum.
    • When a value is divided or modulo by zero.
    • When accessing an array in an index which is too big or negative.

Syntax:

require(condition,"Error Message");
Enter fullscreen mode Exit fullscreen mode

Example:

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract RequireStatement {
    function requireStatement(uint _input) public view returns(string memory){
        require(_input >= 0, "invalid uint8");
        require(_input <= 255, "invalid uint8");
        return "Input is Uint8";
}
Enter fullscreen mode Exit fullscreen mode

Output:
when we pass input as 78 we get

"0 : Input is Uint8"
Enter fullscreen mode Exit fullscreen mode

when we pass input as 748 we get

"0 : invalid uint8"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)