Pausability
Add an emergency stop mechanism to your smart contracts.
We'll cover the following
The Pausable design pattern
The Pausable design pattern adds an emergency stop mechanism to our contracts, defined in the OpenZeppelin abstract contract Pausable.sol, which can be imported with import "@openzeppelin/contracts/security/Pausable.sol";
command.
Description
This abstract contract is built around an internal boolean variable, _paused
, whose value can be set by two virtual, internal functions _pause()
and _unpause()
, and read by a getter function paused()
.
Importantly, ownable.sol
gives us access to two modifiers, whenPaused()
and whenNotPaused()
, that can be used to restrict the use of some functions to a given state of our contract.
Usage
For instance, in case of a security exploit, we may want to pause the contract and stop all deposits and withdrawals. These functions need to be declared with the modifier whenNotPaused()
.
Since we likely do not want anyone but the contract owner to have the ability to pause it, the Pausable design pattern implicitly requires an owner role in the contract and is typically inherited along with the Ownable design pattern.
Moreover, since the _pause()
and _unpause()
functions have internal
visibility, they can only be called by the contract. Therefore, we need to write an external function that calls them and can toggle the _pause
boolean to true
/false
. Let's call this function togglePause()
.
Example
In the source file below, we augment our basicBank.sol
contract with the ability to pause deposits and withdrawals.
We import the code of the ownable.sol
and pausable.sol
abstract contracts in line 2 and line 3, and inherit from them in line 5 by declaring that our contract is Ownable, Pausable
.
We define a togglePause()
function in lines 6–10, which simply calls _pause()
/_unpause()
depending on the current value of the _paused
boolean.
Finally, we add the whenNotPaused()
modifier to functions deposit()
and withdraw()
in line 20 and line 25, respectively.
Again, it's recommended to run this example with a compiler version above 0.8.0
as Pausable.sol
requires this version.
Get hands-on with 1400+ tech skills courses.