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

  • Trump Threatens to Destroy Iranian Power Plants if Strait of Hormuz Not Opened

    March 20 - Trump stated that if Iran does not fully open the Strait of Hormuz within 48 hours, the United States will strike and destroy multiple Iranian power plants, starting with the largest one. (Jins10)

  • ETH Drops Below $2100

    Market data shows that ETH has fallen below $2100, currently trading at $2095.44. It has experienced a 24-hour decline of 2.47%. The market is experiencing significant volatility, so please manage your risk accordingly.

  • BTC Drops Below $69,000

    Market data shows that BTC has fallen below $69,000, currently trading at $68,955. The cryptocurrency has seen a 2.31% decrease in the past 24 hours. The market is experiencing significant volatility, and investors are advised to implement risk control measures.

  • BTC Drops Below $70,000

    Market data shows that BTC has fallen below $70,000, currently trading at $69,988.17. It has experienced a 0.74% decrease in the past 24 hours. The market is experiencing significant volatility, so please manage your risk accordingly.

  • Golden Morning News | Key Overnight Developments on March 22

    9:00 PM - 7:00 AM Keywords: Iran, US Dollar, Strait of Hormuz 1. BofA: Maintains a medium-term bearish view on the US Dollar. 2. Israeli Defense Minister states that strikes against Iran will intensify in the coming week. 3. Iranian Armed Forces announce significant actions being taken in the Strait of Hormuz. 4. US media reports that Trump's team is developing strategies for potential peace talks with Iran. 5. Analysts: US SEC's cryptocurrency guidance marks the "end of an era" for Gensler. 6. British media: Over 20 countries declare readiness to contribute to ensuring safe passage through the Strait of Hormuz. 7. Cryptocurrency companies lay off hundreds of employees within weeks, attributing it to a weak market and powerful AI.

  • US Media: Trump Team Strategizing for Potential Iran Peace Talks

    According to the website AXIOS, a US official and an informed source revealed that after three weeks of war, the Trump administration has begun preliminary discussions on the next phase and the possible form of peace negotiations with Iran. US President Trump stated on Friday that he is considering a "phased end" to the war, but US officials indicated that the fighting is expected to continue for another two to three weeks. Meanwhile, Trump's advisors hope to begin preparing for diplomatic mediation. Sources revealed that Trump's envoys Kushner and Wittcoff are participating in discussions regarding potential diplomatic avenues. Any agreement to end the war must include the reopening of the Strait of Hormuz, addressing Iran's enriched uranium stockpile, and reaching a long-term agreement on Iran's nuclear program, ballistic missiles, and support for regional proxies. Other sources also revealed that although Egypt, Qatar, and the UK have all conveyed messages between the US and Iran, there have been no direct contacts between the US and Iran in recent days. Egypt and Qatar have informed the US and Israel that Iran is interested in negotiations, but the conditions are very tough, with Iran's demands including a ceasefire, guarantees against future wars, and reparations.

  • BTC Surges Past $71,000

    Market data shows that BTC has broken through $71,000, currently trading at $71,007.92. It has seen a 1.93% increase in the last 24 hours. The market is experiencing significant volatility, so please manage your risk accordingly.

  • Golden Evening News | Key Developments on March 21st

    12:00-21:00 Keywords: Coinbase, Iran, OpenAI, James Wynn 1. Citigroup: Bitcoin could reach $165,000 this year. 2. Iranian Foreign Minister states the pursuit of a complete end to the war, not a temporary ceasefire. 3. OpenAI plans to nearly double its workforce to 8,000 employees by the end of the year. 4. James Wynn returns to HyperLiquid, shorting Bitcoin with 40x leverage. 5. Tim Cook responds to OpenClaw driving Mac Mini sales: Neural Engine added ten years ago. 6. Coinbase's asset management arm launches tokenized shares of a Bitcoin fund, accelerating its asset tokenization strategy.

  • Polymarket to Announce Major News Next Monday, Potentially Related to Token Launch or Funding

    March 21st news: A member of the official Polymarket team, Mustafa, posted on X stating that major news will be announced next Monday. Due to the inclusion of a coin emoji in the tweet, the community speculates that the significant news may be related to funding or a token launch. Previously, it was reported that prediction market platforms Kalshi and Polymarket were in discussions with potential investors for a new round of financing, with both targeting valuations of approximately $20 billion. Kalshi has recently completed a new round of financing exceeding $1 billion, reaching a valuation of $22 billion, doubling its valuation from the previous round in December last year, which was $11 billion. Sources familiar with the matter revealed that this round of financing was led by Coatue Management, and Kalshi's current annualized revenue is $1.5 billion.

  • Midday Briefing | Key Updates for March 21

    7:00 AM - 12:00 PM Keywords: Zedxion, Gold, Galaxy Digital, US SEC 1. UK Proposes Revoking License for Crypto Exchange Zedxion for Allegedly Facilitating Funding for Iran. 2. Gold Records Largest Weekly Drop in 43 Years. 3. Sources: Trump Administration Developing Plan to Seize Iranian Nuclear Material Reserves. 4. CryptoQuant Analyst: Galaxy Digital Suspected of Selling Approximately 700 BTC. 5. Galaxy Head of Research: New SEC Rules Reshape Digital Asset Regulation, Providing Clear Secondary Market Channels. 6. Claude Code Launches Cloud-Based Scheduled Tasks: Automates PR reviews, dependency upgrades, no local execution needed. 7. World Team Suspected of Conducting OTC Trade with an Entity, Sending 117 Million WLD.