0
# OpenZeppelin Contracts
1
2
OpenZeppelin Contracts is a comprehensive library of secure, reusable Solidity smart contract components for Ethereum development. It provides battle-tested implementations of token standards (ERC20, ERC721, ERC1155), access control mechanisms, governance tools, proxy patterns for upgradeability, and essential utilities for building decentralized applications. The library follows security best practices with extensive auditing, formal verification, and community review.
3
4
## Package Information
5
6
- **Package Name**: @openzeppelin/contracts
7
- **Package Type**: npm
8
- **Language**: Solidity
9
- **Installation**: `npm install @openzeppelin/contracts`
10
11
## Core Imports
12
13
```solidity
14
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
15
import "@openzeppelin/contracts/access/Ownable.sol";
16
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
17
```
18
19
## Basic Usage
20
21
```solidity
22
// SPDX-License-Identifier: MIT
23
pragma solidity ^0.8.20;
24
25
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
26
import "@openzeppelin/contracts/access/Ownable.sol";
27
28
contract MyToken is ERC20, Ownable {
29
constructor(address initialOwner)
30
ERC20("MyToken", "MTK")
31
Ownable(initialOwner)
32
{}
33
34
function mint(address to, uint256 amount) public onlyOwner {
35
_mint(to, amount);
36
}
37
}
38
```
39
40
## Architecture
41
42
OpenZeppelin Contracts is built around several key architectural patterns:
43
44
- **Modular Design**: Contracts are designed to be composed together through inheritance and interfaces
45
- **Security-First**: All contracts follow security best practices and are extensively audited
46
- **Standard Compliance**: Implements all major Ethereum standards (ERC20, ERC721, ERC1155, etc.)
47
- **Upgradeability**: Proxy patterns enable contract upgrades while preserving state
48
- **Gas Optimization**: Efficient implementations that minimize gas costs
49
- **Extension System**: Base contracts with optional extensions and utilities
50
51
## Capabilities
52
53
### Token Standards
54
55
Complete implementations of Ethereum token standards with extensions and utilities for custom functionality.
56
57
```solidity { .api }
58
// ERC20 Token Standard
59
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
60
constructor(string memory name_, string memory symbol_);
61
function transfer(address to, uint256 value) public virtual returns (bool);
62
function transferFrom(address from, address to, uint256 value) public virtual returns (bool);
63
function approve(address spender, uint256 value) public virtual returns (bool);
64
function balanceOf(address account) public view virtual returns (uint256);
65
function totalSupply() public view virtual returns (uint256);
66
function allowance(address owner, address spender) public view virtual returns (uint256);
67
}
68
69
// ERC721 NFT Standard
70
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
71
constructor(string memory name_, string memory symbol_);
72
function approve(address to, uint256 tokenId) public virtual;
73
function transferFrom(address from, address to, uint256 tokenId) public virtual;
74
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual;
75
function ownerOf(uint256 tokenId) public view virtual returns (address);
76
function balanceOf(address owner) public view virtual returns (uint256);
77
}
78
79
// ERC1155 Multi-Token Standard
80
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
81
constructor(string memory uri_);
82
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual;
83
function safeBatchTransferFrom(address from, address to, uint256[] memory ids, uint256[] memory values, bytes memory data) public virtual;
84
function balanceOf(address account, uint256 id) public view virtual returns (uint256);
85
function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual returns (uint256[] memory);
86
}
87
```
88
89
[Token Standards](./token-standards.md)
90
91
### Access Control
92
93
Role-based and ownership-based access control mechanisms for secure contract administration.
94
95
```solidity { .api }
96
// Single Owner Pattern
97
abstract contract Ownable is Context {
98
constructor(address initialOwner);
99
function owner() public view virtual returns (address);
100
function transferOwnership(address newOwner) public virtual onlyOwner;
101
function renounceOwnership() public virtual onlyOwner;
102
modifier onlyOwner();
103
}
104
105
// Role-Based Access Control
106
abstract contract AccessControl is Context, IAccessControl, ERC165 {
107
function hasRole(bytes32 role, address account) public view virtual returns (bool);
108
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role));
109
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role));
110
function renounceRole(bytes32 role, address callerConfirmation) public virtual;
111
modifier onlyRole(bytes32 role);
112
}
113
```
114
115
[Access Control](./access-control.md)
116
117
### Security Utilities
118
119
Essential security patterns and utilities for protecting against common vulnerabilities.
120
121
```solidity { .api }
122
// Reentrancy Protection
123
abstract contract ReentrancyGuard {
124
modifier nonReentrant();
125
}
126
127
// Emergency Pause Functionality
128
abstract contract Pausable is Context {
129
function paused() public view virtual returns (bool);
130
function _pause() internal virtual whenNotPaused;
131
function _unpause() internal virtual whenPaused;
132
modifier whenNotPaused();
133
modifier whenPaused();
134
}
135
```
136
137
[Security Utilities](./security-utilities.md)
138
139
### Governance
140
141
On-chain governance systems with voting, proposal management, and timelock controls.
142
143
```solidity { .api }
144
// Governor Contract
145
abstract contract Governor is Context, ERC165, EIP712, Nonces, IGovernor {
146
function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) public virtual returns (uint256);
147
function execute(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) public virtual returns (uint256);
148
function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256);
149
function castVoteWithReason(uint256 proposalId, uint8 support, string calldata reason) public virtual returns (uint256);
150
}
151
152
// Timelock Controller
153
contract TimelockController is AccessControl {
154
function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE);
155
function execute(address target, uint256 value, bytes calldata payload, bytes32 predecessor, bytes32 salt) public virtual onlyRoleOrOpenRole(EXECUTOR_ROLE);
156
function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE);
157
}
158
```
159
160
[Governance](./governance.md)
161
162
### Proxy Patterns
163
164
Upgradeability patterns enabling contract logic updates while preserving state and addresses.
165
166
```solidity { .api }
167
// ERC1967 Proxy
168
contract ERC1967Proxy is Proxy {
169
constructor(address implementation, bytes memory _data);
170
}
171
172
// Transparent Upgradeable Proxy
173
contract TransparentUpgradeableProxy is ERC1967Proxy {
174
constructor(address _logic, address initialOwner, bytes memory _data);
175
}
176
177
// UUPS Upgradeable
178
abstract contract UUPSUpgradeable is IERC1822Proxiable, ERC1967Utils {
179
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy;
180
function proxiableUUID() external view virtual notDelegated returns (bytes32);
181
}
182
```
183
184
[Proxy Patterns](./proxy-patterns.md)
185
186
### Mathematical Utilities
187
188
Safe mathematical operations and data structures for common smart contract patterns.
189
190
```solidity { .api }
191
// Math Library
192
library Math {
193
function max(uint256 a, uint256 b) internal pure returns (uint256);
194
function min(uint256 a, uint256 b) internal pure returns (uint256);
195
function average(uint256 a, uint256 b) internal pure returns (uint256);
196
function sqrt(uint256 a) internal pure returns (uint256);
197
}
198
199
// Safe Casting
200
library SafeCast {
201
function toUint248(uint256 value) internal pure returns (uint248);
202
function toUint240(uint256 value) internal pure returns (uint240);
203
function toInt256(uint256 value) internal pure returns (int256);
204
}
205
206
// Address Utilities
207
library Address {
208
function isContract(address account) internal view returns (bool);
209
function sendValue(address payable recipient, uint256 amount) internal;
210
function functionCall(address target, bytes memory data) internal returns (bytes memory);
211
}
212
```
213
214
[Mathematical Utilities](./mathematical-utilities.md)
215
216
### Account Abstraction
217
218
ERC-4337 compliant smart contract wallets with modular authentication and gasless transactions.
219
220
```solidity { .api }
221
// ERC-4337 Account Contract
222
contract Account is Context, IERC165, IERC1271, IAccount, Ownable, UUPSUpgradeable {
223
constructor(IEntryPoint anEntryPoint);
224
function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds) external virtual returns (uint256 validationData);
225
function executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external virtual;
226
function execute(address target, uint256 value, bytes calldata data) external virtual requireFromEntryPointOrOwner;
227
function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata data) external virtual requireFromEntryPointOrOwner;
228
}
229
```
230
231
[Account Abstraction](./account-abstraction.md)
232
233
### Finance
234
235
Token vesting and financial management contracts for controlled distribution over time.
236
237
```solidity { .api }
238
// Vesting Wallet
239
contract VestingWallet is Context, Ownable {
240
constructor(address beneficiary, uint64 startTimestamp, uint64 durationSeconds);
241
function release() public virtual;
242
function release(address token) public virtual;
243
function releasable() public view virtual returns (uint256);
244
function releasable(address token) public view virtual returns (uint256);
245
function vestedAmount(uint64 timestamp) public view virtual returns (uint256);
246
}
247
248
// Vesting with Cliff
249
contract VestingWalletCliff is VestingWallet {
250
constructor(address beneficiary, uint64 startTimestamp, uint64 durationSeconds, uint64 cliffSeconds);
251
function cliff() public view virtual returns (uint256);
252
}
253
```
254
255
[Finance](./finance.md)
256
257
### Meta-transactions
258
259
ERC-2771 gasless transactions enabling users to interact without paying gas fees directly.
260
261
```solidity { .api }
262
// ERC-2771 Context
263
abstract contract ERC2771Context is Context {
264
constructor(address trustedForwarder);
265
function isTrustedForwarder(address forwarder) public view virtual returns (bool);
266
function _msgSender() internal view virtual override returns (address);
267
function _msgData() internal view virtual override returns (bytes calldata);
268
}
269
270
// ERC-2771 Forwarder
271
contract ERC2771Forwarder is ERC165, EIP712, Nonces, IERC2771Forwarder {
272
constructor(string memory name);
273
function verify(ForwardRequestData calldata request) public view virtual returns (bool);
274
function execute(ForwardRequestData calldata request) public payable virtual returns (bool success, bytes memory returndata);
275
function executeBatch(ForwardRequestData[] calldata requests, address payable refundReceiver) public payable virtual;
276
}
277
```
278
279
[Meta-transactions](./meta-transactions.md)
280
281
## Common Types
282
283
```solidity { .api }
284
// Standard Interfaces
285
interface IERC20 {
286
function transfer(address to, uint256 value) external returns (bool);
287
function transferFrom(address from, address to, uint256 value) external returns (bool);
288
function approve(address spender, uint256 value) external returns (bool);
289
function balanceOf(address account) external view returns (uint256);
290
function totalSupply() external view returns (uint256);
291
function allowance(address owner, address spender) external view returns (uint256);
292
}
293
294
interface IERC721 {
295
function approve(address to, uint256 tokenId) external;
296
function transferFrom(address from, address to, uint256 tokenId) external;
297
function safeTransferFrom(address from, address to, uint256 tokenId) external;
298
function ownerOf(uint256 tokenId) external view returns (address);
299
function balanceOf(address owner) external view returns (uint256);
300
}
301
302
interface IERC1155 {
303
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
304
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata values, bytes calldata data) external;
305
function balanceOf(address account, uint256 id) external view returns (uint256);
306
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
307
}
308
309
// Access Control
310
interface IAccessControl {
311
function hasRole(bytes32 role, address account) external view returns (bool);
312
function grantRole(bytes32 role, address account) external;
313
function revokeRole(bytes32 role, address account) external;
314
function renounceRole(bytes32 role, address callerConfirmation) external;
315
}
316
317
// Governance
318
interface IGovernor {
319
function propose(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description) external returns (uint256);
320
function execute(address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash) external returns (uint256);
321
function castVote(uint256 proposalId, uint8 support) external returns (uint256);
322
}
323
```