Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 47 ยท Tokens and Standards

Using OpenZeppelin

Learn why to reuse audited code and how to use OpenZeppelin's Ownable, AccessControl, ReentrancyGuard, Pausable and SafeERC20, with runnable pattern stand-ins.

In the last few lessons you wrote token logic by hand, and you saw how many small details there are: zero-address checks, allowance rules, receiver hooks, rounding. Smart contracts hold real money and cannot be patched quietly, so the safest code is code that thousands of people have already read, tested and attacked. OpenZeppelin Contracts is the most widely used library of such code: tokens, access control, pausing, security helpers and upgrade tools, all written in Solidity and audited.

The rule of thumb is simple. Do not write your own ERC-20, ownership or reentrancy guard. Import the standard one, and spend your time on what makes your contract different. This lesson shows the building blocks you will use most, and runs stand-ins so you can see exactly what each one does.

Why reuse audited code?

Many eyes Widely reviewed and attacked in public.
Well tested Edge cases are already covered.
Standard behavior Wallets and tools expect it.
Saves time You write only your own logic.
1 / 2

Installing and importing

You add the library to a project with a package manager (npm for Hardhat, or forge install for Foundry) and import files by path. The commands and imports below are read-only: they need a project on your own computer.

Terminal
# Read-only: Hardhat project
npm install @openzeppelin/contracts

# Read-only: Foundry project
forge install OpenZeppelin/openzeppelin-contracts
SOLIDITY
// Read-only: typical imports (OpenZeppelin Contracts 5.x paths)
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {SafeERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

Two warnings. First, pin the version and read the release notes when you upgrade: file locations, constructor arguments and function names have changed between major versions (for example, Ownable takes an initialOwner argument in version 5, and ReentrancyGuard and Pausable live under utils). Second, a library is only as good as your use of it: you are still responsible for how the pieces are combined.

A token in a few lines

Everything from Building an ERC-20 Token collapses into inheritance:

SOLIDITY
// Read-only
contract GameCoin is ERC20, Ownable {
    constructor(address initialOwner)
        ERC20("Game Coin", "GAME")
        Ownable(initialOwner)
    {
        _mint(initialOwner, 1_000_000 * 10 ** decimals());
    }

    function mint(address to, uint256 amount) external onlyOwner {
        _mint(to, amount);
    }
}

Inheritance and the constructor chain are exactly what you learned in Inheritance and Overriding. The base contracts provide the tables, events and checks. Your contract adds one rule: only the owner can mint.

Ownable and AccessControl

Ownable gives a contract a single owner. The onlyOwner modifier protects functions, transferOwnership(newOwner) hands over control and renounceOwnership() gives it up for good (use that with great care). An Ownable2Step variant requires the new owner to accept, which prevents transferring ownership to a wrong address by accident; compare Modifiers and Access Control.

AccessControl is for contracts with more than one kind of privileged user. Roles are bytes32 labels, usually keccak256("MINTER_ROLE"). Each role has an admin role that can grant and revoke it (by default DEFAULT_ADMIN_ROLE). You protect functions with onlyRole(MINTER_ROLE).

SOLIDITY
// Read-only
contract Rewards is AccessControl {
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    constructor(address admin) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
    }

    function reward(address to, uint256 amount) external onlyRole(MINTER_ROLE) {
        // ...
    }
}

Prefer roles when different people or contracts need different powers, because compromising one key then does not give away everything.

JS Owner and roles as guards

Press Run (or Ctrl + Enter) to see the console output here.

No output.

ReentrancyGuard and Pausable

ReentrancyGuard gives you a modifier, nonReentrant. It sets a flag when a function starts and clears it when the function ends; if the same contract is entered again while the flag is set, the second call reverts. Put it on functions that make external calls and change balances. It is a safety net, not an excuse to skip the checks-effects-interactions order, which Reentrancy Step by Step teaches in detail.

Pausable adds an emergency switch: _pause() and _unpause() (which you protect with your own access control), a paused() getter, and modifiers whenNotPaused and whenPaused. It lets the team stop deposits or transfers quickly if a problem is discovered. It also means someone can freeze users, so it is part of what users must trust.

SOLIDITY
// Read-only
contract Bank is ReentrancyGuard, Pausable, Ownable {
    mapping(address => uint256) public balance;

    constructor() Ownable(msg.sender) {}

    function pause() external onlyOwner { _pause(); }
    function unpause() external onlyOwner { _unpause(); }

    function deposit() external payable whenNotPaused {
        balance[msg.sender] += msg.value;
    }

    function withdraw() external nonReentrant {
        uint256 amount = balance[msg.sender];
        balance[msg.sender] = 0;                       // effects first
        (bool ok, ) = msg.sender.call{value: amount}(""); // interaction last
        require(ok, "send failed");
    }
}

The stand-in below wraps functions in guards, which is how modifiers work conceptually. A greedy vault calls back into a user-supplied function before it clears the balance, so you can watch the guard stop a re-entry.

JS nonReentrant and whenNotPaused

Press Run (or Ctrl + Enter) to see the console output here.

No output.

SafeERC20

Not every token follows ERC-20 to the letter. The standard says transfer returns a bool, but some well-known tokens return nothing at all, and some return false instead of reverting. A plain token.transfer(to, amount) call against a no-return token reverts when Solidity tries to decode a missing return value, and against a returns-false token it silently continues if you do not check the value.

SafeERC20 wraps the calls so all three behaviors are handled: it uses a low-level call, reverts if the call failed, accepts "no return data", and reverts if the token returned false. You use it with using SafeERC20 for IERC20; and then call safeTransfer, safeTransferFrom and forceApprove (the last one handles tokens that require resetting an allowance to zero first).

SOLIDITY
// Read-only
using SafeERC20 for IERC20;

function pay(IERC20 token, address to, uint256 amount) external {
    token.safeTransfer(to, amount);               // never ignore the return value yourself
    token.safeTransferFrom(msg.sender, address(this), amount);
}
JS Three kinds of token, one safe wrapper

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The naive column shows the two problems: no-return tokens break a strict caller, and a token that returns false is silently treated as paid. The safe wrapper stops the second one and tolerates the first.

Using libraries wisely

  • Inherit, do not copy. Copy-pasted code does not receive security fixes.
  • Pin versions and read changelogs on upgrade; run your tests again.
  • Override with care. When you change a hook such as _update in ERC-20, you can break guarantees the base contract made. Always call super unless you know why not.
  • Know what you import. Read the contracts you inherit from. They are short and they are the best documentation.
  • Upgradeable variants (@openzeppelin/contracts-upgradeable) exist for proxies and use initializers instead of constructors, as in Proxies and Upgradeable Contracts.

What is real: the roles, owner, guard, pause and safe-call ideas, and the import paths and function names of OpenZeppelin Contracts 5.x as of this writing. What is the stand-in: each pattern is plain JavaScript (closures and Sets) rather than Solidity modifiers and storage, errors are plain text, and the greedy vault is a toy. The library itself is not run on this site.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer an imported OpenZeppelin contract over your own copy of the same logic?

    Audited, widely used code has fewer hidden bugs than a fresh rewrite. It does not remove your responsibility to test how you combine and configure it.
  2. 2. When would you choose AccessControl over Ownable?

    Ownable has one owner with all special rights. AccessControl splits rights into named roles that can be granted and revoked separately.
  3. 3. What does the nonReentrant modifier do?

    It sets a flag at the start and clears it at the end. A callback that re-enters while the flag is set reverts. Still follow checks-effects-interactions.
  4. 4. Why use SafeERC20 instead of calling token.transfer directly?

    Some tokens return no value and some return false instead of reverting. SafeERC20 accepts empty return data, reverts on false and checks that the call succeeded.

Summary

  • Reuse audited libraries such as OpenZeppelin Contracts instead of rewriting tokens and security helpers.
  • Pin the version and read the notes: paths, constructors and names change between major versions.
  • Ownable is a single owner (use the two-step variant when you can); AccessControl gives named, separately granted roles.
  • ReentrancyGuard blocks re-entry and Pausable adds an emergency stop; both are part of what users must trust and are no replacement for good ordering of effects and interactions.
  • SafeERC20 makes token transfers robust against tokens that return nothing or false.
  • Override base hooks carefully, and keep calling super.

Next: Common Vulnerabilities.