Using OpenZeppelin Libraries

Using OpenZeppelin Libraries


OpenZeppelin Contracts is the industry-standard library for secure smart contract development. It provides tested, audited implementations of common patterns.


Why Use OpenZeppelin?


1. **Battle-tested**: Used in thousands of projects

2. **Professionally audited**: Regular security audits

3. **Community maintained**: Active development and updates

4. **Gas optimized**: Efficient implementations

5. **Well documented**: Comprehensive guides and examples


Installation


npm install @openzeppelin/contracts

Common Use Cases


1. ERC20 Token


import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
    constructor() ERC20("MyToken", "MTK") {
        _mint(msg.sender, 1000000 * 10 ** decimals());
    }
}

2. Access Control


import "@openzeppelin/contracts/access/Ownable.sol";

contract MyContract is Ownable {
    function sensitiveFunction() public onlyOwner {
        // Only owner can execute
    }
}

3. Pausable Functionality


import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract MyContract is Pausable, Ownable {
    function pause() public onlyOwner {
        _pause();
    }
    
    function unpause() public onlyOwner {
        _unpause();
    }
    
    function criticalFunction() public whenNotPaused {
        // Can only execute when not paused
    }
}

4. ReentrancyGuard


import "@openzeppelin/contracts/security/ReentrancyGuard.sol";

contract MyContract is ReentrancyGuard {
    function withdraw() public nonReentrant {
        // Protected from reentrancy
        uint amount = balances[msg.sender];
        balances[msg.sender] = 0;
        payable(msg.sender).transfer(amount);
    }
}

5. Role-Based Access Control


import "@openzeppelin/contracts/access/AccessControl.sol";

contract MyContract is AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
    
    constructor() {
        _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
    }
    
    function mint(address to, uint amount) public onlyRole(MINTER_ROLE) {
        _mint(to, amount);
    }
}

Advanced Features


Upgradeable Contracts


import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract MyUpgradeableContract is Initializable, OwnableUpgradeable {
    function initialize() public initializer {
        __Ownable_init();
        // Initialize state
    }
}

ERC20 Extensions


import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol";

contract GovernanceToken is ERC20, ERC20Burnable, ERC20Snapshot, ERC20Votes {
    // Advanced token with burning, snapshots, and voting power
}

Best Practices


1. **Use Latest Stable Version**: Keep dependencies updated

2. **Don't Modify Library Code**: Extend instead of modifying

3. **Understand What You Import**: Read the documentation

4. **Check for Updates**: Security patches are released regularly

5. **Use Specific Versions**: Lock to specific versions in production


Common Patterns


Safe Token Transfers


import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

using SafeERC20 for IERC20;

function safeTransfer(IERC20 token, address to, uint amount) internal {
    token.safeTransfer(to, amount); // Handles all edge cases
}

Counters


import "@openzeppelin/contracts/utils/Counters.sol";

using Counters for Counters.Counter;
Counters.Counter private _tokenIds;

function mintNFT() public {
    uint newTokenId = _tokenIds.current();
    _tokenIds.increment();
    _mint(msg.sender, newTokenId);
}

Gotchas to Avoid


1. **Don't inherit from deprecated contracts**

2. **Be careful with upgradeable vs non-upgradeable versions**

3. **Initialize properly for upgradeable contracts**

4. **Watch for storage layout in upgrades**

5. **Test all inherited functionality**


Version Management


{
  "dependencies": {
    "@openzeppelin/contracts": "^5.0.0"
  }
}

Always check the [OpenZeppelin Contracts documentation](https://docs.openzeppelin.com/contracts/) for the latest version and migration guides.


Resources


- [OpenZeppelin Contracts](https://github.com/OpenZeppelin/openzeppelin-contracts)

- [Documentation](https://docs.openzeppelin.com/contracts/)

- [Contract Wizard](https://wizard.openzeppelin.com/)

Need Professional Security Audit?

Our experts can help secure your smart contracts

Get Audit Quote