require in solidity

require will check if a condition is true and allow code to flow only if condition is true. If the condition is false, require will throw an error, the rest of the code will not be executed and the transaction will revert.

The first param of require call is the condition you are checking, and the second param is an optional error message that will be returned by EVM when error is thrown.

The require Solidity function guarantees validity of conditions that cannot be detected before execution. It checks inputs, contract state variables and return values from calls to external contracts.

In the following cases, Solidity triggers a require-type of exception:

  • When you call require with arguments that result in false.
  • When a function called through a message does not end properly.
  • When you create a contract with new keyword and the process does not end properly.
  • When you target a codeless contract with an external function.
  • When your contract gets Ether through a public getter function.
  • When .transfer() ends in failure.

In this code sample, only the owner of the contract can call addBalance() successfully. Otherwise, require will throw an error and the transaction will revert.
The transfer() method also uses require to check that the sender has the amount they are trying to send.
Also, sender cannot send transaction to themselves.

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;

contract Bank {
    mapping(address => uint) balance;
    address owner;
    
    constructor() {
        owner = msg.sender; // address that deploys contract will be the owner
    }
    
    function addBalance(uint _toAdd) public returns(uint) {
        require(msg.sender == owner);
        balance[msg.sender] += _toAdd;
        return balance[msg.sender];
    }
    
    function getBalance() public view returns(uint) {
        return balance[msg.sender];
    }
    
    function transfer(address recipient, uint amount) public {
        require(balance[msg.sender]>=amount, "Insufficient Balance");
        require(msg.sender != recipient, "You can't send money to yourself!");
        _transfer(msg.sender, recipient, amount);
    }
    
    function _transfer(address from, address to, uint amount) private {
        balance[from] -= amount;
        balance[to] += amount;
    }
}
Show Comments