Convert Figma logo to code with AI

OpenZeppelin logoopenzeppelin-contracts

OpenZeppelin Contracts is a library for secure smart contract development.

24,847
11,779
24,847
288

Top Related Projects

A guide to smart contract security best practices

5,296

Static Analyzer for Solidity and Vyper

23,191

Solidity, the Smart Contract Programming Language

7,238

Hardhat is a development environment to compile, deploy, test, and debug your Ethereum software.

Quick Overview

OpenZeppelin Contracts is a library of secure, reusable smart contracts for Ethereum and other EVM-compatible blockchains. It provides a set of thoroughly tested and community-reviewed contracts that developers can use as building blocks for their decentralized applications (dApps) and blockchain projects.

Pros

  • Highly secure and audited contracts, reducing the risk of vulnerabilities
  • Extensive documentation and community support
  • Regularly updated to incorporate best practices and new features
  • Modular design allows for easy integration and customization

Cons

  • Learning curve for developers new to smart contract development
  • Some contracts may be overly complex for simple use cases
  • Gas costs can be higher due to additional security features
  • Dependency on external library may introduce potential risks if not properly managed

Code Examples

  1. ERC20 Token Creation:
pragma solidity ^0.8.0;

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

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}

This example creates a basic ERC20 token with a specified initial supply.

  1. Access Control:
pragma solidity ^0.8.0;

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

contract MyContract is Ownable {
    function restrictedFunction() public onlyOwner {
        // Only the owner can call this function
    }
}

This example demonstrates how to use the Ownable contract to restrict access to certain functions.

  1. Pausable Contract:
pragma solidity ^0.8.0;

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

contract MyPausableContract is Pausable, Ownable {
    function pause() public onlyOwner {
        _pause();
    }

    function unpause() public onlyOwner {
        _unpause();
    }

    function sensitiveFunction() public whenNotPaused {
        // This function can only be called when the contract is not paused
    }
}

This example shows how to create a contract that can be paused and unpaused by the owner, with functions that respect the paused state.

Getting Started

To use OpenZeppelin Contracts in your project:

  1. Install the package using npm:

    npm install @openzeppelin/contracts
    
  2. Import the desired contracts in your Solidity file:

    import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
    
  3. Inherit from the imported contracts or use them directly in your smart contract:

    contract MyContract is ERC20 {
        constructor() ERC20("MyToken", "MTK") {
            // Contract initialization
        }
    }
    

Competitor Comparisons

A guide to smart contract security best practices

Pros of smart-contract-best-practices

  • Comprehensive guide covering various aspects of smart contract security
  • Regularly updated with community contributions and latest best practices
  • Provides explanations and rationale behind recommendations

Cons of smart-contract-best-practices

  • Primarily text-based, lacking ready-to-use code implementations
  • May require more effort to implement recommendations in actual projects
  • Less structured compared to a library of pre-built contracts

Code Comparison

smart-contract-best-practices (example recommendation):

function transfer(address to, uint256 amount) public returns (bool) {
    require(balances[msg.sender] >= amount, "Insufficient balance");
    balances[msg.sender] -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount);
    return true;
}

openzeppelin-contracts (implemented ERC20 transfer):

function transfer(address to, uint256 amount) public virtual override returns (bool) {
    address owner = _msgSender();
    _transfer(owner, to, amount);
    return true;
}

The smart-contract-best-practices example shows a basic implementation, while openzeppelin-contracts provides a more robust, tested, and gas-optimized version with additional security features built-in.

5,296

Static Analyzer for Solidity and Vyper

Pros of Slither

  • Static analysis tool for finding vulnerabilities and code smells in Solidity
  • Supports multiple output formats for easy integration into development workflows
  • Regularly updated with new detectors for emerging smart contract vulnerabilities

Cons of Slither

  • Requires additional setup and integration into the development process
  • May produce false positives that need manual review
  • Limited to static analysis, cannot catch all runtime issues

Code Comparison

Slither (analysis output):

INFO:Detectors:
Reentrancy in Vault.withdraw(uint256) (contracts/Vault.sol#15-22):
	External calls:
	- (success) = msg.sender.call{value: amount}() (contracts/Vault.sol#19)
	State variables written after the call(s):
	- balances[msg.sender] -= amount (contracts/Vault.sol#21)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities

OpenZeppelin Contracts (ReentrancyGuard implementation):

modifier nonReentrant() {
    require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
    _status = _ENTERED;
    _;
    _status = _NOT_ENTERED;
}
23,191

Solidity, the Smart Contract Programming Language

Pros of solidity

  • Core language repository, providing the foundation for Ethereum smart contract development
  • Extensive documentation and language specifications
  • Regular updates and improvements to the Solidity language itself

Cons of solidity

  • Focuses solely on the language, not providing ready-to-use contract implementations
  • Steeper learning curve for beginners compared to using pre-built contracts
  • Requires more in-depth knowledge of smart contract security best practices

Code comparison

solidity:

pragma solidity ^0.8.0;

contract SimpleStorage {
    uint256 private storedData;

    function set(uint256 x) public {
        storedData = x;
    }
}

openzeppelin-contracts:

pragma solidity ^0.8.0;

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

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}

The solidity repository provides the core language features, while openzeppelin-contracts offers pre-built, secure contract implementations like ERC20 tokens. Solidity requires developers to implement functionality from scratch, whereas openzeppelin-contracts provides battle-tested contracts that can be easily extended and customized.

7,238

Hardhat is a development environment to compile, deploy, test, and debug your Ethereum software.

Pros of Hardhat

  • Comprehensive development environment with built-in testing, debugging, and deployment tools
  • Extensible plugin system for customizing functionality
  • TypeScript support out of the box

Cons of Hardhat

  • Steeper learning curve for beginners compared to OpenZeppelin Contracts
  • Focused on development workflow rather than providing reusable smart contract components
  • Requires more setup and configuration for complex projects

Code Comparison

Hardhat (configuration example):

module.exports = {
  solidity: "0.8.4",
  networks: {
    hardhat: {},
    rinkeby: {
      url: process.env.RINKEBY_URL,
      accounts: [process.env.PRIVATE_KEY]
    }
  }
};

OpenZeppelin Contracts (contract example):

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

contract MyToken is ERC20 {
    constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
        _mint(msg.sender, initialSupply);
    }
}

While Hardhat focuses on providing a development environment and tooling for Ethereum projects, OpenZeppelin Contracts offers a library of secure, reusable smart contract components. Hardhat is more suitable for managing the entire development lifecycle, while OpenZeppelin Contracts excels in providing battle-tested contract implementations for common use cases.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

OpenZeppelin

NPM Package Coverage Status GitPOAPs Docs Forum

A library for secure smart contract development. Build on a solid foundation of community-vetted code.

:mage: Not sure how to get started? Check out Contracts Wizard — an interactive smart contract generator.

:building_construction: Want to scale your decentralized application? Check out OpenZeppelin Defender — a mission-critical developer security platform to code, audit, deploy, monitor, and operate with confidence.

[!IMPORTANT] OpenZeppelin Contracts uses semantic versioning to communicate backwards compatibility of its API and storage layout. For upgradeable contracts, the storage layout of different major versions should be assumed incompatible, for example, it is unsafe to upgrade from 4.9.3 to 5.0.0. Learn more at Backwards Compatibility.

Overview

Installation

Hardhat (npm)

$ npm install @openzeppelin/contracts

Foundry (git)

[!WARNING] When installing via git, it is a common error to use the master branch. This is a development branch that should be avoided in favor of tagged releases. The release process involves security measures that the master branch does not guarantee.

[!WARNING] Foundry installs the latest version initially, but subsequent forge update commands will use the master branch.

$ forge install OpenZeppelin/openzeppelin-contracts

Add @openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/ in remappings.txt.

Usage

Once installed, you can use the contracts in the library by importing them:

pragma solidity ^0.8.20;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract MyCollectible is ERC721 {
    constructor() ERC721("MyCollectible", "MCO") {
    }
}

If you're new to smart contract development, head to Developing Smart Contracts to learn about creating a new project and compiling your contracts.

To keep your system secure, you should always use the installed code as-is, and neither copy-paste it from online sources nor modify it yourself. The library is designed so that only the contracts and functions you use are deployed, so you don't need to worry about it needlessly increasing gas costs.

Learn More

The guides in the documentation site will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides:

  • Access Control: decide who can perform each of the actions on your system.
  • Tokens: create tradeable assets or collectives, and distribute them via Crowdsales.
  • Utilities: generic useful tools including non-overflowing math, signature verification, and trustless paying systems.

The full API is also thoroughly documented, and serves as a great reference when developing your smart contract application. You can also ask for help or follow Contracts's development in the community forum.

Finally, you may want to take a look at the guides on our blog, which cover several common use cases and good practices. The following articles provide great background reading, though please note that some of the referenced tools have changed, as the tooling in the ecosystem continues to rapidly evolve.

Security

This project is maintained by OpenZeppelin with the goal of providing a secure and reliable library of smart contract components for the ecosystem. We address security through risk management in various areas such as engineering and open source best practices, scoping and API design, multi-layered review processes, and incident response preparedness.

The OpenZeppelin Contracts Security Center contains more details about the secure development process.

The security policy is detailed in SECURITY.md as well, and specifies how you can report security vulnerabilities, which versions will receive security patches, and how to stay informed about them. We run a bug bounty program on Immunefi to reward the responsible disclosure of vulnerabilities.

The engineering guidelines we follow to promote project quality can be found in GUIDELINES.md.

Past audits can be found in audits/.

Smart contracts are a nascent technology and carry a high level of technical risk and uncertainty. Although OpenZeppelin is well known for its security audits, using OpenZeppelin Contracts is not a substitute for a security audit.

OpenZeppelin Contracts is made available under the MIT License, which disclaims all warranties in relation to the project and which limits the liability of those that contribute and maintain the project, including OpenZeppelin. As set out further in the Terms, you acknowledge that you are solely responsible for any use of OpenZeppelin Contracts and you assume all risks associated with any such use.

Contribute

OpenZeppelin Contracts exists thanks to its contributors. There are many ways you can participate and help build high quality software. Check out the contribution guide!

License

OpenZeppelin Contracts is released under the MIT License.

Legal

Your use of this Project is governed by the terms found at www.openzeppelin.com/tos (the "Terms").

NPM DownloadsLast 30 Days