Photo by GuerrillaBuzz Crypto PR on Unsplash
How to pause functions in solidity
Solidity function pausing mechanism
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;
}
}
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.