Cointime

Download App
iOS & Android

Formally Verifying OpenZeppelin’s ERC-20 Implementation

Validated Project

Open Zeppelin’s ERC-20 reference implementation is widely used in Web3. A bug in it would be devastating for the many contracts that derive from it. But how do we know that it is correct? And how do we know contracts that derive from it do so correctly and do not introduce bugs?

In Part One of this series on formal verification, we explained how CertiK uses formal verification to mathematically prove the correctness of ERC-20 contracts that we audit. Let’s dive in and see what happens when we apply it to OpenZeppelin’s code.In Part One of this series on formal verification, we explained how CertiK uses formal verification to mathematically prove the correctness of ERC-20 contracts that we audit. Let’s dive in and see what happens when we apply it to OpenZeppelin’s code.

ERC-20 Standard Properties

At CertiK, we have written property templates that precisely describe the expected behaviors of ERC-20 token contracts. These templates are generic: our tools analyze the implementation details of each smart contract and adapt the templates accordingly. We have 38 property templates.

Let's look at some of the properties that we regularly verify on incoming ERC-20 token contracts. For the sake of readability, the formulas that follow are slightly simplified and omit some technical details that do not contribute to the overall understanding of the approach. CertiK's audit reports contain an appendix that reproduces the formulas that have been used during model checking. A list with all the formulas used in our ERC-20 verification approach is publicly available here.

The transferFrom() function in ERC-20 contracts requires special attention, as it needs to distinguish between the initiator of the transaction (the address is msg.sender), the accounts that spend and receive tokens, and because it needs to observe the limits imposed by the entries in _balances and _allowances.

Specifying Correct Allowance Updates

When transferFrom() succeeds, it must deduct the amount of tokens that have been transferred from the allowance that the sender has over the spender's account. However, many ERC-20 token contracts also allow the token owner to grant infinite allowance to another account. This is reflected by setting that account's allowance to the maximum value, i.e. to ((2^256)-1). Taking that exception into account, a correct allowance update can be specified by the following LTL formula 𝜑:

It states that when transferFrom() is invoked and terminates (without reverting) with a return value of true, we expect that the sender's allowance is either reduced by the amount of tokens in amt (the red subformula) or that the sender either is the owner of the transferred tokens or has unlimited allowance over the spender's tokens. In those cases, the allowance must remain unchanged (the blue subformula).

Specifying Dismissal of Transfers That Exceed the Allowance

Attempts to use transferFrom() to transfer an amount of tokens that exceeds one´s allowance should fail. This is formalized by 𝜓:

If the invocation of transferFrom() requests to transfer tokens from somebody other than their owner and if that transfer exceeds the sender's allowance, we expect the transaction to either revert, or to fail and signal its failure by returning false.

These are only two examples of the formalizations CertiK uses to capture the expected behaviors of ERC-20 token contracts. For more information about our properties and all technical details, refer to our property list.

OpenZeppelin's Reference Implementation for ERC-20 Contracts

The OpenZeppelin library provides reference implementations for many popular smart contracts. Its ERC-20 base contracts are popular and often used as building blocks for DeFi projects.

As many of the projects we audit contain contracts that derive from OpenZeppelin, we formally verified a set of 38 security properties on their ERC-20 reference implementation as of version 4.7.3. As can be seen the image below, all properties of the base contract are proven correct.

This result, however, tells us little about the security of actual ERC-20 token implementations, even when they derive from the OpenZeppelin contract! In actual blockchain projects, the reference implementation is modified by overriding its virtual functions and by introducing additional public APIs. What if someone makes a mistake?

The correctness of a base contract is generally not sufficient to ensure security in derived tokens! It is possible to introduce errors not only when overriding parts of the base implementation, but also by making changes to the contract’s state variables that were unforeseen in the base implementation.

OpenZeppelin implements their ERC-20 base contracts by making important state variables private. This ensures that contracts derived from them cannot simply destroy invariants that hold for those private variables. This encapsulation provides a certain level of protection from errors introduced within derived contracts.

Example: PancakeSwap's CAKE Token

PancakeSwap is one of the most popular decentralized exchanges. It is powered by the CAKE token, which implements the BEP20 standard (an extension of the ERC-20 standard). In general, CAKE tokens can be earned by staking and by providing liquidity to the exchange. Running our model checker on the CAKE token implementation successfully proves the basic ERC-20 behavior. The token implementation satisfies all of the properties that CertiK verifies on basic ERC-20 token contracts.

Conclusion

We’ve used formal verification to mathematically prove that OpenZeppelin’s reference ERC-20 implementation v4.8 meets basic ERC-20 properties. While it is not surprising that it does, this is good to know! We explained why just verifying OpenZeppelin’s implementation is not enough. You need to formally verify contracts that derive from it. Be sure to watch for our next blog post, where we discuss handling extensions to ERC-20 and other real-world challenges in verifying.

Read more: https://www.certik.com/resources/blog/7EELzmUpEOE7yhow8LpA3A-formally-verifying-openzeppelins-erc-20-implementation

Get the latest news here: Cointime channel — https://t.me/cointime_en

Comments

All Comments

Recommended for you

  • Michael Saylor Releases New Bitcoin Tracker Information

    On July 5, Strategy founder Michael Saylor released new information regarding the Bitcoin Tracker. He stated, 'Bitcoin is digital energy.' Following previous patterns, Strategy typically discloses information about increasing Bitcoin holdings the day after related announcements.

  • BTC Falls Below $63,000

    Market data shows that BTC has fallen below $63,000, currently priced at $62,978.8, with a 24-hour increase of 0.24%. The market is experiencing significant volatility, so please ensure proper risk management.

  • Vitalik: Ethereum to Complete Major Third Iteration in Next 5 Years, Quantum Resistance and Privacy as Primary Goals

    On July 5, Vitalik Buterin announced that Ethereum researchers finalized the 'Streamlined Ethereum' roadmap during a conference in Berlin. This is not a one-time upgrade but a series of forks over the next 3 to 4 years (starting from 'I-star'), which will mark the third major era of Ethereum, almost replacing all core components. Core changes include: verification shifting from direct execution to recursive STARK; consensus introducing 1-2 rounds of finality for faster and safer transactions; multi-dimensional Gas pricing; and a complete replacement of existing solutions with quantum-resistant cryptography. The most disruptive change is the state model—current dynamic states only expand to about 2TB, while introducing new scalable states like UTXO and circular buffers, with a total scale reaching up to 100TB, suitable for ERC20/NFT/DeFi, potentially reducing transaction fees by over 10 times after the rewrite; complex applications (like Uniswap pools) will retain the old state without mandatory migration. However, the issue of who will store the 100TB state and the associated incentives has become a new focus of research. Privacy upgrades are now a primary design goal, with all new components needing to support quantum-resistant, intermediary-free privacy transactions. Formal verification will be fully implemented, and there is exploration into introducing RISC-V or leanISA as the underlying VM for the protocol, with EVM potentially becoming a feature at the compilation layer in the future. In terms of scalability metrics, Gas limits, Blob capacity, and block times will be increased multiple times over the next 5 years, with the Glasterdam fork set to significantly raise Gas limits first. In the order of forks, H-star (Hegota) will be the last 'pre-streamlined' fork, after which Ethereum will fully enter the streamlined era. Through this complex yet smooth transition, Ethereum is moving towards a quantum-resistant, massively scalable, privacy-first new network while maximizing the protection of existing applications. This cautious disruption over the next five years has officially begun.

  • ETH Surpasses $1800

    Market data shows that ETH has surpassed $1800, currently priced at $1803.65, with a 24-hour increase of 3.76%. The market is experiencing significant fluctuations, so please ensure proper risk management.

  • BTC Surpasses $63,000

    Market data shows that BTC has surpassed $63,000, currently priced at $63,057.24, with a 24-hour increase of 1.18%. The market is experiencing significant volatility, so please ensure proper risk management.

  • Bank of England Governor Bailey to Speak on Fiscal and Monetary Policy Coordination in Ten Minutes

    Bank of England Governor Bailey will deliver a speech on the issue of coordination between fiscal and monetary policy in ten minutes.

  • Solana Achieves $4.84 Billion in Spot Trading Volume for Tokenized Stocks This Quarter

    On July 3, it was reported that Solana broke multiple records in trading, revenue, and trading volume in the second quarter of 2026. In the tokenized stock sector, Solana's spot trading volume reached $4.84 billion this quarter, capturing over 96% market share. This volume far exceeded that of all other blockchains combined, marking the fourth consecutive quarter that Solana has led this sector, solidifying its dominant position. In terms of decentralized application revenue, the total dApp revenue for this quarter was $257 million, maintaining its lead over all Layer 1 and Layer 2 blockchains for the ninth consecutive quarter. Despite competitive pressure from peers, the enthusiasm of ecosystem developers and actual user demand remains strong. On-chain trading activity has surged, with daily, weekly, and monthly trading volumes all hitting new highs. The total number of non-voting transactions for the quarter approached 9.8 billion, with the overall network transaction volume rising to 59%, reaching an eleven-month high. The perpetual futures trading scale has seen a significant surge, with nominal trading volume for the quarter reaching $183 billion. GMTrade, Pacifica, and Jupiter were the main sources of trading volume, with GMTrade showing impressive growth in asset locking, cumulative trading volume, and protocol fees. The Phoenix platform also gained market recognition with its new features. Meanwhile, the Solana Foundation has proactively reduced its staking holdings, with the staking scale dropping to 4.92% of the total network staking, aiming to weaken its control over network validation and promote the decentralized and mature development of the validator ecosystem. Overall, even though the market is generally perceived to be at the bottom of a bear cycle, Solana's various innovative businesses and fundamental on-chain data are rising against the trend. If this quarter indeed marks the low point of the current market cycle, the existing performance will lay a solid foundation for long-term growth. The article also briefly mentions developments related to Solana's on-chain governance, the Grass rewards controversy, and future plans of the foundation's executives.

  • Venezuela's Largest Oil Refinery Resumes Operations

    On July 3, three sources reported that Venezuela's largest refinery, the Amuay refinery with a processing capacity of 645,000 barrels per day, has resumed operations after a power outage on Friday. It is currently processing approximately 140,000 barrels per day of crude oil, and the fluid catalytic cracking unit (FCC) has also restarted. Following two earthquakes last week that caused significant casualties, several refineries in Venezuela were affected by power outages. Additionally, sources indicated that the El Palito refinery, with a processing capacity of 146,000 barrels per day, has regained power, but staff have not yet been able to restart the production units.

  • US Bitcoin ETF Sees Net Outflow of 588 BTC Today, Ethereum ETF Records Net Inflow of 6,105 ETH

    According to monitoring by Lookonchain, today the US Bitcoin ETF experienced a net outflow of 588 BTC, with a total net outflow of 22,189 BTC over the past seven days. Meanwhile, the Ethereum ETF recorded a net inflow of 6,105 ETH, with a net outflow of 1,915 ETH over the past seven days.

  • US Stock Market Closed on July 3rd (Friday)

    On July 3rd, the US stock market will be closed for one day in observance of the Independence Day holiday.