0
# Utilities
1
2
OpenZeppelin Contracts provides a comprehensive set of utility functions including mathematical operations, cryptographic utilities, data structures, and helper functions essential for smart contract development.
3
4
## Core Imports
5
6
Import utility contracts using Solidity import statements:
7
8
```solidity
9
import "@openzeppelin/contracts/utils/Address.sol";
10
import "@openzeppelin/contracts/utils/Strings.sol";
11
import "@openzeppelin/contracts/utils/math/Math.sol";
12
import "@openzeppelin/contracts/utils/math/SignedMath.sol";
13
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
14
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
15
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
16
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
17
import "@openzeppelin/contracts/utils/Counters.sol";
18
import "@openzeppelin/contracts/utils/Create2.sol";
19
```
20
21
## Capabilities
22
23
### Mathematical Operations
24
25
Comprehensive math utilities for safe arithmetic operations with various rounding modes and overflow protection.
26
27
```solidity { .api }
28
library Math {
29
function max(uint256 a, uint256 b) internal pure returns (uint256);
30
function min(uint256 a, uint256 b) internal pure returns (uint256);
31
function average(uint256 a, uint256 b) internal pure returns (uint256);
32
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256);
33
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256);
34
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256);
35
function sqrt(uint256 a) internal pure returns (uint256);
36
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256);
37
function log2(uint256 value) internal pure returns (uint256);
38
function log2(uint256 value, Rounding rounding) internal pure returns (uint256);
39
function log10(uint256 value) internal pure returns (uint256);
40
function log10(uint256 value, Rounding rounding) internal pure returns (uint256);
41
function log256(uint256 value) internal pure returns (uint256);
42
function log256(uint256 value, Rounding rounding) internal pure returns (uint256);
43
}
44
45
enum Rounding {
46
Down,
47
Up,
48
Zero
49
}
50
51
library SignedMath {
52
function max(int256 a, int256 b) internal pure returns (int256);
53
function min(int256 a, int256 b) internal pure returns (int256);
54
function average(int256 a, int256 b) internal pure returns (int256);
55
function abs(int256 n) internal pure returns (uint256);
56
}
57
```
58
59
#### Usage Example
60
61
```solidity
62
pragma solidity ^0.8.0;
63
64
import "@openzeppelin/contracts/utils/math/Math.sol";
65
66
contract MathExample {
67
function calculateReward(uint256 totalRewards, uint256 userStake, uint256 totalStake)
68
public pure returns (uint256) {
69
// Safe multiplication and division to avoid overflow
70
return Math.mulDiv(totalRewards, userStake, totalStake);
71
}
72
73
function calculateSqrt(uint256 value) public pure returns (uint256) {
74
return Math.sqrt(value, Math.Rounding.Up);
75
}
76
}
77
```
78
79
### Address Utilities
80
81
Collection of functions for working with addresses, including contract detection and safe function calls.
82
83
```solidity { .api }
84
library Address {
85
function isContract(address account) internal view returns (bool);
86
function sendValue(address payable recipient, uint256 amount) internal;
87
function functionCall(address target, bytes memory data) internal returns (bytes memory);
88
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory);
89
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory);
90
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory);
91
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory);
92
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory);
93
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory);
94
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory);
95
}
96
```
97
98
#### Usage Example
99
100
```solidity
101
pragma solidity ^0.8.0;
102
103
import "@openzeppelin/contracts/utils/Address.sol";
104
105
contract AddressExample {
106
using Address for address;
107
108
function safeCall(address target, bytes calldata data) external {
109
require(target.isContract(), "Target is not a contract");
110
target.functionCall(data, "Call failed");
111
}
112
113
function sendEther(address payable recipient, uint256 amount) external {
114
Address.sendValue(recipient, amount);
115
}
116
}
117
```
118
119
### String Utilities
120
121
String manipulation functions for converting between data types and string representations.
122
123
```solidity { .api }
124
library Strings {
125
function toString(uint256 value) internal pure returns (string memory);
126
function toHexString(uint256 value) internal pure returns (string memory);
127
function toHexString(uint256 value, uint256 length) internal pure returns (string memory);
128
function toHexString(address addr) internal pure returns (string memory);
129
}
130
```
131
132
#### Usage Example
133
134
```solidity
135
pragma solidity ^0.8.0;
136
137
import "@openzeppelin/contracts/utils/Strings.sol";
138
139
contract StringExample {
140
function generateTokenURI(uint256 tokenId) external view returns (string memory) {
141
return string(abi.encodePacked(
142
"https://api.example.com/tokens/",
143
Strings.toString(tokenId),
144
".json"
145
));
146
}
147
}
148
```
149
150
### Cryptographic Utilities
151
152
Essential cryptographic functions for signature verification, merkle proof validation, and hash operations.
153
154
```solidity { .api }
155
library ECDSA {
156
function recover(bytes32 hash, bytes memory signature) internal pure returns (address);
157
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address);
158
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address);
159
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32);
160
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32);
161
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32);
162
}
163
164
library MerkleProof {
165
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool);
166
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool);
167
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32);
168
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32);
169
function multiProofVerify(bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves) internal pure returns (bool);
170
function multiProofVerifyCalldata(bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves) internal pure returns (bool);
171
}
172
```
173
174
#### Usage Example
175
176
```solidity
177
pragma solidity ^0.8.0;
178
179
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
180
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
181
182
contract CryptoExample {
183
using ECDSA for bytes32;
184
185
bytes32 public merkleRoot;
186
mapping(address => bool) public hasClaimed;
187
188
function verifySignature(bytes32 hash, bytes memory signature, address signer)
189
public pure returns (bool) {
190
return hash.recover(signature) == signer;
191
}
192
193
function claim(bytes32[] calldata proof, uint256 amount) external {
194
require(!hasClaimed[msg.sender], "Already claimed");
195
196
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount));
197
require(MerkleProof.verify(proof, merkleRoot, leaf), "Invalid proof");
198
199
hasClaimed[msg.sender] = true;
200
// Transfer tokens or execute claim logic
201
}
202
}
203
```
204
205
### Data Structures
206
207
Enumerable sets and maps providing gas-efficient storage and iteration capabilities.
208
209
```solidity { .api }
210
library EnumerableSet {
211
struct Bytes32Set { /* private */ }
212
struct AddressSet { /* private */ }
213
struct UintSet { /* private */ }
214
215
function add(Bytes32Set storage set, bytes32 value) internal returns (bool);
216
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool);
217
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool);
218
function length(Bytes32Set storage set) internal view returns (uint256);
219
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32);
220
function values(Bytes32Set storage set) internal view returns (bytes32[] memory);
221
}
222
223
library EnumerableMap {
224
struct Bytes32ToBytes32Map { /* private */ }
225
struct UintToAddressMap { /* private */ }
226
struct UintToUintMap { /* private */ }
227
struct AddressToUintMap { /* private */ }
228
struct Bytes32ToUintMap { /* private */ }
229
230
function set(Bytes32ToBytes32Map storage map, bytes32 key, bytes32 value) internal returns (bool);
231
function remove(Bytes32ToBytes32Map storage map, bytes32 key) internal returns (bool);
232
function contains(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool);
233
function length(Bytes32ToBytes32Map storage map) internal view returns (uint256);
234
function at(Bytes32ToBytes32Map storage map, uint256 index) internal view returns (bytes32, bytes32);
235
function tryGet(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bool, bytes32);
236
function get(Bytes32ToBytes32Map storage map, bytes32 key) internal view returns (bytes32);
237
}
238
```
239
240
#### Usage Example
241
242
```solidity
243
pragma solidity ^0.8.0;
244
245
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
246
247
contract SetExample {
248
using EnumerableSet for EnumerableSet.AddressSet;
249
250
EnumerableSet.AddressSet private admins;
251
252
function addAdmin(address admin) external {
253
admins.add(admin);
254
}
255
256
function removeAdmin(address admin) external {
257
admins.remove(admin);
258
}
259
260
function isAdmin(address account) external view returns (bool) {
261
return admins.contains(account);
262
}
263
264
function getAdminCount() external view returns (uint256) {
265
return admins.length();
266
}
267
268
function getAllAdmins() external view returns (address[] memory) {
269
return admins.values();
270
}
271
}
272
```
273
274
### Counters
275
276
Simple counter implementation that can only be incremented, decremented, or reset.
277
278
```solidity { .api }
279
library Counters {
280
struct Counter { /* private */ }
281
282
function current(Counter storage counter) internal view returns (uint256);
283
function increment(Counter storage counter) internal;
284
function decrement(Counter storage counter) internal;
285
function reset(Counter storage counter) internal;
286
}
287
```
288
289
### CREATE2 Deployment
290
291
Helper functions for deterministic contract deployment using CREATE2 opcode.
292
293
```solidity { .api }
294
library Create2 {
295
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address);
296
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address);
297
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address);
298
}
299
```
300
301
### Context and Introspection
302
303
Base context information and interface detection utilities.
304
305
```solidity { .api }
306
abstract contract Context {
307
function _msgSender() internal view virtual returns (address);
308
function _msgData() internal view virtual returns (bytes calldata);
309
}
310
311
library ERC165Checker {
312
function supportsERC165(address account) internal view returns (bool);
313
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool);
314
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory);
315
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool);
316
}
317
```
318
319
### Base64 Encoding
320
321
Base64 encoding utilities for data URI generation and off-chain compatibility.
322
323
```solidity { .api }
324
library Base64 {
325
function encode(bytes memory data) internal pure returns (string memory);
326
}
327
```
328
329
### Multicall
330
331
Batch multiple function calls into a single transaction.
332
333
```solidity { .api }
334
abstract contract Multicall {
335
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results);
336
}
337
```
338
339
### Type Casting Utilities
340
341
Safe type casting utilities preventing overflow/underflow issues when downcasting between different integer sizes.
342
343
```solidity { .api }
344
library SafeCast {
345
function toUint248(uint256 value) internal pure returns (uint248);
346
function toUint240(uint256 value) internal pure returns (uint240);
347
function toUint232(uint256 value) internal pure returns (uint232);
348
function toUint224(uint256 value) internal pure returns (uint224);
349
function toUint216(uint256 value) internal pure returns (uint216);
350
function toUint208(uint256 value) internal pure returns (uint208);
351
function toUint200(uint256 value) internal pure returns (uint200);
352
function toUint192(uint256 value) internal pure returns (uint192);
353
function toUint184(uint256 value) internal pure returns (uint184);
354
function toUint176(uint256 value) internal pure returns (uint176);
355
function toUint168(uint256 value) internal pure returns (uint168);
356
function toUint160(uint256 value) internal pure returns (uint160);
357
function toUint152(uint256 value) internal pure returns (uint152);
358
function toUint144(uint256 value) internal pure returns (uint144);
359
function toUint136(uint256 value) internal pure returns (uint136);
360
function toUint128(uint256 value) internal pure returns (uint128);
361
function toUint120(uint256 value) internal pure returns (uint120);
362
function toUint112(uint256 value) internal pure returns (uint112);
363
function toUint104(uint256 value) internal pure returns (uint104);
364
function toUint96(uint256 value) internal pure returns (uint96);
365
function toUint88(uint256 value) internal pure returns (uint88);
366
function toUint80(uint256 value) internal pure returns (uint80);
367
function toUint72(uint256 value) internal pure returns (uint72);
368
function toUint64(uint256 value) internal pure returns (uint64);
369
function toUint56(uint256 value) internal pure returns (uint56);
370
function toUint48(uint256 value) internal pure returns (uint48);
371
function toUint40(uint256 value) internal pure returns (uint40);
372
function toUint32(uint256 value) internal pure returns (uint32);
373
function toUint24(uint256 value) internal pure returns (uint24);
374
function toUint16(uint256 value) internal pure returns (uint16);
375
function toUint8(uint256 value) internal pure returns (uint8);
376
function toInt248(int256 value) internal pure returns (int248);
377
function toInt240(int256 value) internal pure returns (int240);
378
function toInt232(int256 value) internal pure returns (int232);
379
function toInt224(int256 value) internal pure returns (int224);
380
function toInt216(int256 value) internal pure returns (int216);
381
function toInt208(int256 value) internal pure returns (int208);
382
function toInt200(int256 value) internal pure returns (int200);
383
function toInt192(int256 value) internal pure returns (int192);
384
function toInt184(int256 value) internal pure returns (int184);
385
function toInt176(int256 value) internal pure returns (int176);
386
function toInt168(int256 value) internal pure returns (int168);
387
function toInt160(int256 value) internal pure returns (int160);
388
function toInt152(int256 value) internal pure returns (int152);
389
function toInt144(int256 value) internal pure returns (int144);
390
function toInt136(int256 value) internal pure returns (int136);
391
function toInt128(int256 value) internal pure returns (int128);
392
function toInt120(int256 value) internal pure returns (int120);
393
function toInt112(int256 value) internal pure returns (int112);
394
function toInt104(int256 value) internal pure returns (int104);
395
function toInt96(int256 value) internal pure returns (int96);
396
function toInt88(int256 value) internal pure returns (int88);
397
function toInt80(int256 value) internal pure returns (int80);
398
function toInt72(int256 value) internal pure returns (int72);
399
function toInt64(int256 value) internal pure returns (int64);
400
function toInt56(int256 value) internal pure returns (int56);
401
function toInt48(int256 value) internal pure returns (int48);
402
function toInt40(int256 value) internal pure returns (int40);
403
function toInt32(int256 value) internal pure returns (int32);
404
function toInt24(int256 value) internal pure returns (int24);
405
function toInt16(int256 value) internal pure returns (int16);
406
function toInt8(int256 value) internal pure returns (int8);
407
function toUint256(int256 value) internal pure returns (uint256);
408
}
409
```
410
411
### Advanced Cryptographic Utilities
412
413
Extended cryptographic operations for structured data signing and signature validation.
414
415
```solidity { .api }
416
library EIP712 {
417
function _domainSeparatorV4() internal view returns (bytes32);
418
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32);
419
function _buildDomainSeparator(bytes32 typeHash, bytes32 nameHash, bytes32 versionHash) private view returns (bytes32);
420
}
421
422
library SignatureChecker {
423
function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool);
424
}
425
```
426
427
### Advanced Data Structures
428
429
Efficient data structures for specialized use cases requiring high performance and low gas usage.
430
431
```solidity { .api }
432
library BitMaps {
433
struct BitMap {
434
mapping(uint256 => uint256) _data;
435
}
436
437
function get(BitMap storage bitmap, uint256 index) internal view returns (bool);
438
function setTo(BitMap storage bitmap, uint256 index, bool value) internal;
439
function set(BitMap storage bitmap, uint256 index) internal;
440
function unset(BitMap storage bitmap, uint256 index) internal;
441
}
442
443
library DoubleEndedQueue {
444
struct Bytes32Deque {
445
int128 _begin;
446
int128 _end;
447
mapping(int128 => bytes32) _data;
448
}
449
450
function pushBack(Bytes32Deque storage deque, bytes32 value) internal;
451
function popBack(Bytes32Deque storage deque) internal returns (bytes32 value);
452
function pushFront(Bytes32Deque storage deque, bytes32 value) internal;
453
function popFront(Bytes32Deque storage deque) internal returns (bytes32 value);
454
function front(Bytes32Deque storage deque) internal view returns (bytes32 value);
455
function back(Bytes32Deque storage deque) internal view returns (bytes32 value);
456
function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value);
457
function clear(Bytes32Deque storage deque) internal;
458
function length(Bytes32Deque storage deque) internal view returns (uint256);
459
function empty(Bytes32Deque storage deque) internal view returns (bool);
460
}
461
```
462
463
### Historical Data Management
464
465
Checkpoint system for tracking historical values with efficient querying for governance and voting systems.
466
467
```solidity { .api }
468
library Checkpoints {
469
struct History {
470
Checkpoint[] _checkpoints;
471
}
472
473
struct Checkpoint {
474
uint32 _blockNumber;
475
uint224 _value;
476
}
477
478
function push(History storage self, uint256 value) internal returns (uint256, uint256);
479
function getAtBlock(History storage self, uint256 blockNumber) internal view returns (uint256);
480
function latest(History storage self) internal view returns (uint256);
481
function length(History storage self) internal view returns (uint256);
482
}
483
```
484
485
### Array Utilities
486
487
Efficient array operations including searching, sorting, and manipulation functions.
488
489
```solidity { .api }
490
library Arrays {
491
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256);
492
}
493
```
494
495
### Storage Management
496
497
Low-level storage slot management utilities for upgradeable contracts and proxy patterns.
498
499
```solidity { .api }
500
library StorageSlot {
501
struct AddressSlot {
502
address value;
503
}
504
505
struct BooleanSlot {
506
bool value;
507
}
508
509
struct Bytes32Slot {
510
bytes32 value;
511
}
512
513
struct Uint256Slot {
514
uint256 value;
515
}
516
517
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r);
518
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r);
519
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r);
520
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r);
521
}
522
```
523
524
## Utility Best Practices
525
526
1. **Gas Efficiency**: Use appropriate data structures based on your access patterns
527
2. **Safe Math**: Always use OpenZeppelin's math utilities for overflow protection
528
3. **Address Validation**: Check if addresses are contracts before making calls
529
4. **Signature Verification**: Validate signatures properly using ECDSA utilities
530
5. **Merkle Proofs**: Use merkle trees for efficient batch operations and airdrops
531
6. **Data Structures**: Choose between sets and maps based on whether you need key-value storage
532
533
## Error Handling
534
535
Utility libraries may revert with various errors:
536
537
- **ECDSA**: `ECDSAInvalidSignature()`, `ECDSAInvalidSignatureLength(uint256 length)`, `ECDSAInvalidSignatureS(bytes32 s)`, `ECDSAInvalidSignatureV(uint8 v)`
538
- **Address**: Various call-related errors depending on the target contract
539
- **Math**: Overflow/underflow errors in older Solidity versions (handled automatically in 0.8+)