Using OpenZeppelin
OpenZeppelin Contracts is a widely audited library of building blocks: tokens, access control, pausing, reentrancy protection and more. Reusing it is safer than writing these parts yourself, because the same code is already trusted by thousands of projects.
Install it with Foundry using forge install OpenZeppelin/openzeppelin-contracts, or with npm using npm install @openzeppelin/contracts. Then import the files you need and inherit from them with the is keyword.
Many contracts in the library work together. For example, you can build an ERC-20 that is also Ownable and Pausable by inheriting from all three. The order of inheritance and calls to super matter when functions are overridden, so read the docs for each one.
Pin the version you use and read the code you inherit, because you are responsible for how it behaves inside your contract. From version 5, Ownable requires you to pass the initial owner to its constructor.
The OpenZeppelin Contracts Wizard at wizard.openzeppelin.com generates a starting contract with the features you tick. It is a good way to see how the pieces fit together before you customize them.
import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; contract GameCoin is ERC20, Ownable, Pausable { constructor() ERC20("Game Coin", "GAME") Ownable(msg.sender) { _mint(msg.sender, 1_000_000 ether); } function mint(address to, uint256 amount) external onlyOwner { _mint(to, amount); } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } // OpenZeppelin v5 routes every transfer, mint and burn through _update function _update(address from, address to, uint256 value) internal override whenNotPaused { super._update(from, to, value); } }
Try it yourself
This example imports a library, so use the Open in Remix button: compile it, deploy it, then try transferring tokens after calling pause. Next, use the Contracts Wizard to generate a version with burning and permit.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.