How to pause functions in solidity

Michael FawoleMichael Fawole
2 min read

Hello readers. To understand this article, you must have read my previous article on boolean in solidity. If you have not, click this link.

Let start from where we stopped in previous article.

pragma solidity ^0.5.0;

contract Michael{

bool public paused;
uint public count;

function Pause(bool x)public {
    paused = x;
}

}

Do not forget that uint public count was added.

Next step is to add the increment and decrement function.

function increase() public {

count += 1;

    }

This function will increase the count variable by 1 every time it is called.

function decrease() public {

count -= 1;
    }

The decrease function above will reduce the state variable count by 1 every time it is called.

The full code will look like this

pragma solidity ^0.5.0;
contract tech4dev{
bool public paused;
uint public count;

function setPause(bool x) public {
paused = x;
}


    function increase() public {

count += 1;

    }
    function decrease() public {

count -= 1;
    }

    }

Let add require statement so that if the contract is paused, the function increase and decrease will not work.

function increase() public {
       require(!paused);
count += 1;

    }
    function decrease() public {
           require(!paused);
count -= 1;
    }

The require code is saying : if the contract is not paused, execute the code below.

Here is the full code, let compile and deploy the code.

pragma solidity ^0.5.0;
contract tech4dev{
bool public paused;
uint public count;

function setPause(bool x) public {
paused = x;
}

    function increase() public {
        require(!paused);
count += 1;

    }
    function decrease() public {
          require(!paused);
count -= 1;
    }

    }

image.png

So to set paused to true, type true in the input field when you deploy.

Congratulations, by now, you can pause functions in solidity anyhow you like.

3
Subscribe to my newsletter

Read articles from Michael Fawole directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Michael Fawole
Michael Fawole

Michael Fawole is a Blockchain and web application developer with 7+ years of experience and 3+ years plus of experience in blockchain dapp development. He is also delivering training on blockchain ( Solidity, web3 and react js ) and php language. He also helps start-ups and companies to setup blockchain practice and incorporating blockchain into existing project. Techstack (Blockchain): Solidity, web3 js and react js. Techstack (Webapp): Php and Mysql.