0
# Security Patterns
1
2
OpenZeppelin Contracts provides essential security mechanisms to protect smart contracts from common vulnerabilities including reentrancy attacks, unauthorized access during emergency situations, and payment-related exploits.
3
4
## Core Imports
5
6
Import security contracts using Solidity import statements:
7
8
```solidity
9
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
10
import "@openzeppelin/contracts/security/Pausable.sol";
11
import "@openzeppelin/contracts/security/PullPayment.sol";
12
```
13
14
## Capabilities
15
16
### Reentrancy Protection
17
18
Protects against reentrancy attacks by preventing nested calls to functions marked with the `nonReentrant` modifier.
19
20
```solidity { .api }
21
abstract contract ReentrancyGuard {
22
modifier nonReentrant();
23
}
24
```
25
26
#### Usage Example
27
28
```solidity
29
pragma solidity ^0.8.0;
30
31
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
32
33
contract SecureWithdrawal is ReentrancyGuard {
34
mapping(address => uint256) private balances;
35
36
function withdraw() external nonReentrant {
37
uint256 balance = balances[msg.sender];
38
require(balance > 0, "No funds to withdraw");
39
40
balances[msg.sender] = 0;
41
42
(bool success, ) = msg.sender.call{value: balance}("");
43
require(success, "Transfer failed");
44
}
45
}
46
```
47
48
### Pausable Mechanism
49
50
Provides emergency pause functionality that can halt contract operations when security issues are detected.
51
52
```solidity { .api }
53
abstract contract Pausable is Context {
54
function paused() public view virtual returns (bool);
55
56
modifier whenNotPaused();
57
modifier whenPaused();
58
59
function _pause() internal virtual;
60
function _unpause() internal virtual;
61
}
62
```
63
64
#### Events
65
66
```solidity { .api }
67
event Paused(address account);
68
event Unpaused(address account);
69
```
70
71
#### Usage Example
72
73
```solidity
74
pragma solidity ^0.8.0;
75
76
import "@openzeppelin/contracts/security/Pausable.sol";
77
import "@openzeppelin/contracts/access/Ownable.sol";
78
79
contract EmergencyPausableToken is Pausable, Ownable {
80
mapping(address => uint256) private balances;
81
82
function transfer(address to, uint256 amount) public whenNotPaused {
83
require(balances[msg.sender] >= amount, "Insufficient balance");
84
balances[msg.sender] -= amount;
85
balances[to] += amount;
86
}
87
88
function emergencyPause() external onlyOwner {
89
_pause();
90
}
91
92
function emergencyUnpause() external onlyOwner {
93
_unpause();
94
}
95
}
96
```
97
98
### Pull Payment Pattern
99
100
Implements the pull payment pattern to avoid reentrancy risks and failed transfers by allowing payees to withdraw their funds themselves.
101
102
```solidity { .api }
103
abstract contract PullPayment {
104
function payments(address dest) public view returns (uint256);
105
function withdrawPayments(address payable payee) public virtual;
106
107
function _asyncTransfer(address dest, uint256 amount) internal;
108
}
109
```
110
111
#### Usage Example
112
113
```solidity
114
pragma solidity ^0.8.0;
115
116
import "@openzeppelin/contracts/security/PullPayment.sol";
117
118
contract Auction is PullPayment {
119
address public highestBidder;
120
uint256 public highestBid;
121
122
function bid() public payable {
123
require(msg.value > highestBid, "Bid not high enough");
124
125
if (highestBid != 0) {
126
// Previous highest bidder can withdraw their bid
127
_asyncTransfer(highestBidder, highestBid);
128
}
129
130
highestBidder = msg.sender;
131
highestBid = msg.value;
132
}
133
134
function withdrawPreviousBid() public {
135
withdrawPayments(payable(msg.sender));
136
}
137
}
138
```
139
140
## Security Best Practices
141
142
When using OpenZeppelin security patterns:
143
144
1. **Reentrancy**: Always use `nonReentrant` modifier for functions that make external calls or transfer funds
145
2. **Pausable**: Implement emergency pause mechanisms for critical functions that handle user funds
146
3. **Pull Payments**: Use pull payments instead of push payments to avoid failed transfers and gas limit issues
147
4. **Combined Patterns**: Security patterns can be combined - for example, using both `nonReentrant` and `whenNotPaused` modifiers
148
5. **Access Control**: Combine security patterns with proper access control mechanisms from the Access Control module
149
150
## Error Handling
151
152
Security contracts may revert with the following errors:
153
154
- **ReentrancyGuard**: `ReentrancyGuardReentrantCall()` - When reentrancy is detected
155
- **Pausable**: Functions fail when called in wrong pause state (no specific error, just reverts with modifiers)
156
- **PullPayment**: No specific errors, but underlying escrow operations may fail