Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chubby-heads-film.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

Added ERC20 extension for configurable approval caps and expiry
181 changes: 107 additions & 74 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,122 +1,155 @@
# <img src="logo.svg" alt="OpenZeppelin" height="40px">
# ERC20SafeApproval — OpenZeppelin Extension

[![Github Release](https://img.shields.io/github/v/tag/OpenZeppelin/openzeppelin-contracts.svg?filter=v*&sort=semver&label=github)](https://github.com/OpenZeppelin/openzeppelin-contracts/releases/latest)
[![NPM Package](https://img.shields.io/npm/v/@openzeppelin/contracts.svg)](https://www.npmjs.org/package/@openzeppelin/contracts)
[![Coverage Status](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts/graph/badge.svg)](https://codecov.io/gh/OpenZeppelin/openzeppelin-contracts)
[![GitPOAPs](https://public-api.gitpoap.io/v1/repo/OpenZeppelin/openzeppelin-contracts/badge)](https://www.gitpoap.io/gh/OpenZeppelin/openzeppelin-contracts)
[![Docs](https://img.shields.io/badge/docs-%F0%9F%93%84-yellow)](https://docs.openzeppelin.com/contracts)
[![Forum](https://img.shields.io/badge/forum-%F0%9F%92%AC-yellow)](https://forum.openzeppelin.com/)
> A contribution-quality extension of OpenZeppelin's ERC20 contract that adds
> configurable approval caps and per-approval expiration timestamps.

**A library for secure smart contract development.** Build on a solid foundation of community-vetted code.
**Team:** Kenny Bartel & Brianna Patten

Check failure on line 6 in README.md

View workflow job for this annotation

GitHub Actions / codespell

Patten ==> Pattern, Patent
**Course:** CS5833
**Upstream Repo:** [OpenZeppelin/openzeppelin-contracts](https://github.com/OpenZeppelin/openzeppelin-contracts)
**Related Issue:** [openzeppelin-contracts#6500](https://github.com/OpenZeppelin/openzeppelin-contracts/issues/6500)

* Implementations of standards like [ERC20](https://docs.openzeppelin.com/contracts/erc20) and [ERC721](https://docs.openzeppelin.com/contracts/erc721).
* Flexible [role-based permissioning](https://docs.openzeppelin.com/contracts/access-control) scheme.
* Reusable [Solidity components](https://docs.openzeppelin.com/contracts/utilities) to build custom contracts and complex decentralized systems.
---

:mage: **Not sure how to get started?** Check out [Contracts Wizard](https://wizard.openzeppelin.com/) — an interactive smart contract generator.
## Overview

> [!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](https://docs.openzeppelin.com/contracts/backwards-compatibility).
The standard ERC-20 approval mechanism allows unlimited, non-expiring approvals.
This has been a known vector for token drains in DeFi, where users who previously
signed unlimited approvals to contracts that later turned malicious had their tokens
drained. While OpenZeppelin's `ERC20Permit` (ERC-2612) addresses expiry via
off-chain signatures, it requires EIP-712 infrastructure not available in simpler
applications and does not address approval caps.

## Overview
`ERC20SafeApproval` is an abstract Solidity extension that enforces both on-chain
through simple inheritance, requiring no off-chain signing infrastructure.

### Release tags
---

We use NPM tags to clearly distinguish between audited and non-audited versions of our package:
## Features

| Tag | Purpose | Description |
| :--------- | :----------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **latest** | ✅ Audited releases | Stable, audited versions of the package. This is the **default** version installed when users run `npm install @openzeppelin/contracts`. |
| **dev** | 🧪 Final but not audited | Versions that are finalized and feature-complete but have **not yet been audited**. This version is fully tested, can be used in production and is covered by the bug bounty. |
| **next** | 🚧 Release candidates | Pre-release versions that are **not final**. Used for testing and validation before the version becomes a final `dev` or `latest` release. |
- **Approval Cap** — a configurable maximum approval ceiling; no spender can ever
be approved above this limit regardless of what the user signs
- **Approval Expiry** — per-approval expiration timestamps; expired approvals
automatically revert in `transferFrom()`

### Installation
---

#### Hardhat (npm)
## Project Structure
contracts/
└── token/
└── ERC20/
└── extensions/
└── ERC20SafeApproval.sol # main extension
test/
└── token/
└── ERC20/
└── ERC20SafeApproval.t.sol # Foundry test suite
script/
└── DeployERC20SafeApproval.s.sol # Sepolia deployment script

```
$ npm install @openzeppelin/contracts
```
→ Installs the latest audited release (`latest`).
---

```
$ npm install @openzeppelin/contracts@dev
```
→ Installs the latest unaudited release (`dev`).
## Getting Started

#### Foundry (git)
### Prerequisites

> [!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.
- [Foundry](https://book.getfoundry.sh/getting-started/installation)
- Git

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

```bash
git clone https://github.com/kennyb66/CS5833-FinalProject
cd contracts
forge install
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix repository setup path in installation steps.

The cd contracts step is likely incorrect for project setup and can break forge install for users following the README. Use the repository root (or the actual directory containing foundry.toml) instead.

Suggested doc fix
 git clone https://github.com/kennyb66/CS5833-FinalProject
-cd contracts
+cd CS5833-FinalProject
 forge install
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
```bash
git clone https://github.com/kennyb66/CS5833-FinalProject
cd contracts
forge install
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@README.md` around lines 60 - 63, The README's setup steps change directory to
"contracts", which is incorrect; update the commands so users run them from the
repository root (or from the directory that contains foundry.toml) — e.g.,
remove or replace "cd contracts" and ensure the sequence is "git clone <repo> &&
cd <repo-root-or-foundry-dir> && forge install" so that forge install runs where
foundry.toml exists.

```
$ forge install OpenZeppelin/openzeppelin-contracts

### Build

```bash
forge build
```

Add `@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/` in `remappings.txt`.
### Run Tests

### Usage
```bash
forge test --match-path test/token/ERC20/ERC20SafeApproval.t.sol -v
```
Comment on lines +70 to +72
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align test instructions with the actual maintained test suite.

The README points to a Foundry test file path that appears to be placeholder-oriented, while this PR’s main coverage is described under the JavaScript suite. Update the “Project Structure” and “Run Tests” sections so contributors execute the real tests.

Suggested doc fix
-└── ERC20SafeApproval.t.sol     # Foundry test suite
+└── extensions/
+    └── ERC20SafeApproval.test.js  # Hardhat test suite
-### Run Tests
+### Run Tests (Hardhat)

 ```bash
-forge test --match-path test/token/ERC20/ERC20SafeApproval.t.sol -v
+npm test -- test/token/ERC20/extensions/ERC20SafeApproval.test.js
</details>


Also applies to: 37-45

<details>
<summary>🤖 Prompt for AI Agents</summary>

Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @README.md around lines 74 - 76, Update the README "Project Structure" and
"Run Tests" sections to point to the maintained JavaScript test suite instead of
the placeholder Foundry path: replace the forge command example with the npm
test invocation that runs the JS test file
(test/token/ERC20/extensions/ERC20SafeApproval.test.js) and update any
references to the old Solidity test path
(test/token/ERC20/ERC20SafeApproval.t.sol) to the new JS path so contributors
run the correct tests; ensure examples show "npm test --
test/token/ERC20/extensions/ERC20SafeApproval.test.js" and adjust nearby
explanatory text under the "Project Structure" and "Run Tests" headings
accordingly.


</details>

<!-- fingerprinting:phantom:triton:hawk -->

<!-- This is an auto-generated comment by CodeRabbit -->


Once installed, you can use the contracts in the library by importing them:
### Run Gas Benchmarks

```solidity
pragma solidity ^0.8.20;
```bash
forge test --match-path test/token/ERC20/ERC20SafeApproval.t.sol --gas-report
```

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
### Deploy to Sepolia

contract MyCollectible is ERC721 {
constructor() ERC721("MyCollectible", "MCO") {
}
}
```bash
forge script script/DeployERC20SafeApproval.s.sol \
--rpc-url $SEPOLIA_RPC_URL \
--private-key $PRIVATE_KEY \
--broadcast
```

_If you're new to smart contract development, head to [Developing Smart Contracts](https://docs.openzeppelin.com/learn/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.
## Testnet Deployment

## Learn More
| Contract | Network | Address |
|----------|---------|---------|
| ERC20SafeApproval | Sepolia | `0x...` |

The guides in the [documentation site](https://docs.openzeppelin.com/contracts) will teach about different concepts, and how to use the related contracts that OpenZeppelin Contracts provides:
Verified on [Sepolia Etherscan](https://sepolia.etherscan.io/address/0x...)

* [Access Control](https://docs.openzeppelin.com/contracts/access-control): decide who can perform each of the actions on your system.
* [Tokens](https://docs.openzeppelin.com/contracts/tokens): create tradeable assets or collectibles for popular ERC standards like ERC-20, ERC-721, ERC-1155, and ERC-6909.
* [Utilities](https://docs.openzeppelin.com/contracts/utilities): generic useful tools including non-overflowing math, signature verification, and trustless paying systems.
---

The [full API](https://docs.openzeppelin.com/contracts/api/token/ERC20) 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' development in the [community forum](https://forum.openzeppelin.com).
## Gas Benchmarks

Finally, you may want to take a look at the [guides on our blog](https://blog.openzeppelin.com/), 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.
| Function | Base ERC20 | ERC20SafeApproval | Delta |
|----------|-----------|-------------------|-------|
| `approve()` | - | - | - |
| `transferFrom()` | - | - | - |

* [The Hitchhiker’s Guide to Smart Contracts in Ethereum](https://blog.openzeppelin.com/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05) will help you get an overview of the various tools available for smart contract development, and help you set up your environment.
* [A Gentle Introduction to Ethereum Programming, Part 1](https://blog.openzeppelin.com/a-gentle-introduction-to-ethereum-programming-part-1-783cc7796094) provides very useful information on an introductory level, including many basic concepts from the Ethereum platform.
* For a more in-depth dive, you may read the guide [Designing the Architecture for Your Ethereum Application](https://blog.openzeppelin.com/designing-the-architecture-for-your-ethereum-application-9cec086f8317), which discusses how to better structure your application and its relationship to the real world.
*To be filled in during Week 3*

## Security
---

This project is maintained by [OpenZeppelin](https://openzeppelin.com) 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.
## Usage Example

The [OpenZeppelin Contracts Security Center](https://contracts.openzeppelin.com/security) contains more details about the secure development process.
```solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import "./extensions/ERC20SafeApproval.sol";

The security policy is detailed in [`SECURITY.md`](./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](https://immunefi.com/bounty/openzeppelin) to reward the responsible disclosure of vulnerabilities.
contract MyToken is ERC20SafeApproval {
constructor() ERC20("MyToken", "MTK") {
// set approval cap to 1000 tokens
// set default expiry to 30 days
}
}
```

The engineering guidelines we follow to promote project quality can be found in [`GUIDELINES.md`](./GUIDELINES.md).
---

Past audits can be found in [`audits/`](./audits).
## Team Contributions

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.
| Member | Contributions |
|--------|--------------|
| Kenny Bartel | |
| Brianna Patten | |

Check failure on line 139 in README.md

View workflow job for this annotation

GitHub Actions / codespell

Patten ==> Pattern, Patent

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.
*To be filled in as work progresses*

## 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](CONTRIBUTING.md)!
## Demo Video

## License
*Link to be added in Week 3*

OpenZeppelin Contracts is released under the [MIT License](LICENSE).
---

## Legal
## References

Your use of this Project is governed by the terms found at www.openzeppelin.com/tos (the "Terms").
- [OpenZeppelin ERC20 source](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC20)
- [ERC-2612 / ERC20Permit](https://eips.ethereum.org/EIPS/eip-2612)
- [OpenZeppelin contribution guidelines](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/CONTRIBUTING.md)
21 changes: 21 additions & 0 deletions contracts/mocks/token/ERC20SafeApprovalMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: UNLICENSED

pragma solidity ^0.8.20;

import {ERC20SafeApproval} from "../../token/ERC20/extensions/ERC20SafeApproval.sol";
import {ERC20} from "../../token/ERC20/ERC20.sol";

contract ERC20SafeApprovalMock is ERC20SafeApproval {
constructor(string memory name, string memory symbol, uint256 cap)
ERC20(name, symbol)
ERC20SafeApproval(cap)
{}

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

function setApprovalCap(uint256 newCap) external {
_setApprovalCap(newCap);
}
}
92 changes: 92 additions & 0 deletions contracts/token/ERC20/extensions/ERC20SafeApproval.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {ERC20} from "../ERC20.sol";

/**
* @dev Extension of ERC20 that adds a configurable approval cap
* and per-approval expiration timestamps.
*/
abstract contract ERC20SafeApproval is ERC20 {

/**
* @dev The approval amount exceeds the configured cap
*/
error ERC20ApprovalCapExceeded(uint256 attempted, uint256 cap);

/**
* @dev A transferFrom was attempted with an expired approval
*/
error ERC20ApprovalExpired(address owner, address spender, uint256 expiryTime);

/**
* @dev An approval was attempted with an expiration time in the past
*/
error ERC20InvalidExpiration(uint256 expiryTime);

// TODO: approval cap storage
uint256 private _approvalCap;
// TODO: expiry storage

// TODO: override transferFrom()
mapping(address owner => mapping(address spender => uint256 expiry)) private _approvalExpiry;
Comment on lines +27 to +32
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Stale TODOs interleaved with implemented storage declarations.

Lines 27, 29, and 31 are leftover scaffolding TODOs (approval cap storage, expiry storage, override transferFrom()) for work that has since been completed in this file. The misplaced // TODO: override transferFrom() between the expiry comment and the mapping is especially confusing for readers. Please remove these before merging.

🧹 Proposed cleanup
-    // TODO: approval cap storage
     uint256 private _approvalCap;
-    // TODO: expiry storage
-    
-    // TODO: override transferFrom()
     mapping(address owner => mapping(address spender => uint256 expiry)) private _approvalExpiry;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// TODO: approval cap storage
uint256 private _approvalCap;
// TODO: expiry storage
// TODO: override transferFrom()
mapping(address owner => mapping(address spender => uint256 expiry)) private _approvalExpiry;
uint256 private _approvalCap;
mapping(address owner => mapping(address spender => uint256 expiry)) private _approvalExpiry;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@contracts/token/ERC20/extensions/ERC20SafeApproval.sol` around lines 27 - 32,
Remove the stale TODO comments left alongside the implemented storage
declarations: delete the comments "// TODO: approval cap storage", "// TODO:
expiry storage", and the misplaced "// TODO: override transferFrom()" so only
the actual storage members remain (_approvalCap and mapping _approvalExpiry) and
the existing transferFrom implementation is not obscured by comments; keep the
declarations for uint256 private _approvalCap and mapping(address =>
mapping(address => uint256)) private _approvalExpiry as-is.


event ApprovalCapUpdated(uint256 oldCap, uint256 newCap);
event ApprovalWithExpiration(address indexed owner, address indexed spender, uint256 value, uint256 expiryTime);

constructor(uint256 cap) {
_setApprovalCap(cap);
}

function getApprovalCap() public view virtual returns (uint256) {
return _approvalCap;
}

function getApprovalExpiry(address owner, address spender) public view virtual returns (uint256) {
return _approvalExpiry[owner][spender];
}

function isApprovalExpired(address owner, address spender) public view virtual returns (bool) {
uint256 expiry = _approvalExpiry[owner][spender];
return expiry != 0 && block.timestamp > expiry;
}

// TODO: override approve()
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_checkCap(amount);
delete _approvalExpiry[msg.sender][spender];
return super.approve(spender, amount);
}
Comment on lines +54 to +59
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove stale // TODO: override approve() — already implemented below.

Same scaffolding cleanup as above; the override is right under the TODO. Drop the comment so it doesn't mislead future readers into thinking work is pending.

🧹 Proposed cleanup
-    // TODO: override approve()
     function approve(address spender, uint256 amount) public virtual override returns (bool) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// TODO: override approve()
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_checkCap(amount);
delete _approvalExpiry[msg.sender][spender];
return super.approve(spender, amount);
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_checkCap(amount);
delete _approvalExpiry[msg.sender][spender];
return super.approve(spender, amount);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@contracts/token/ERC20/extensions/ERC20SafeApproval.sol` around lines 54 - 59,
Remove the stale comment "// TODO: override approve()" that sits immediately
above the implemented approve(address spender, uint256 amount) function; the
override is already implemented in the approve function (which calls _checkCap,
clears _approvalExpiry, and returns super.approve), so delete that misleading
TODO comment to avoid confusing future readers.


function approveWithExpiration(address spender, uint256 amount, uint256 expiryTime) public virtual returns (bool) {
if (expiryTime <= block.timestamp) {
revert ERC20InvalidExpiration(expiryTime);
}
_checkCap(amount);
_approvalExpiry[msg.sender][spender] = expiryTime;
emit ApprovalWithExpiration(msg.sender, spender, amount, expiryTime);
return super.approve(spender, amount);
}
Comment on lines +55 to +69
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm OZ v5 ERC20 still exposes the 4-arg internal _approve and how _spendAllowance calls it
ast-grep --pattern 'function _approve(address $_, address $_, uint256 $_, bool $_) internal virtual { $$$ }'
rg -nP --type=sol -C3 '_approve\([^)]*\b(true|false)\b\s*\)' -g 'contracts/token/ERC20/**'

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 994


🏁 Script executed:

#!/bin/bash
# Find and read ERC20SafeApproval.sol
find . -name "ERC20SafeApproval.sol" -type f

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 136


🏁 Script executed:

#!/bin/bash
# Check the full ERC20SafeApproval.sol implementation
cat -n contracts/token/ERC20/extensions/ERC20SafeApproval.sol

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 3900


🏁 Script executed:

#!/bin/bash
# Check ERC20Permit.permit() to see how it invokes _approve
rg -n "permit" contracts/token/ERC20/extensions/ERC20Permit.sol -A 20 | head -50

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 1730


🏁 Script executed:

#!/bin/bash
# Check _spendAllowance implementation and how it calls _approve
rg -n "_spendAllowance" contracts/token/ERC20/ERC20.sol -A 15

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 2054


🏁 Script executed:

#!/bin/bash
# Get the complete permit() function including the _approve call
rg -n "function permit" contracts/token/ERC20/extensions/ERC20Permit.sol -A 30

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 1065


🏁 Script executed:

#!/bin/bash
# Also verify if ERC20SafeApproval might be used with ERC20Permit in tests
find . -name "*.sol" -type f -exec grep -l "ERC20SafeApproval" {} \; | head -10

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 291


🏁 Script executed:

#!/bin/bash
# Check if there's a 3-arg _approve method or how it resolves
rg -n "function _approve" contracts/token/ERC20/ERC20.sol

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 381


🏁 Script executed:

#!/bin/bash
# Check the test file to see if ERC20SafeApproval is tested with permit
cat -n test/token/ERC20/ERC20SafeApproval.t.sol | head -100

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 1113


🏁 Script executed:

#!/bin/bash
# Check the implementation of the 3-arg _approve
sed -n '251,265p' contracts/token/ERC20/ERC20.sol

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 813


🏁 Script executed:

#!/bin/bash
# Verify the relationship between 3-arg and 4-arg _approve and how permit uses them
rg -n "function _approve" contracts/token/ERC20/ERC20.sol -A 5

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 928


Cap bypass via ERC20Permit.permit() and other internal _approve callers—override the virtual 4-arg _approve to enforce cap.

_checkCap is invoked only on the public approve / approveWithExpiration entry points. The cap is bypassed by any caller that writes allowance through the inherited _approve(owner, spender, value) method—most notably ERC20Permit.permit() (line 64 of ERC20Permit.sol), which sets allowances directly via signature. The 3-arg _approve delegates to the virtual 4-arg variant with emitEvent=true.

Since the PR aims to provide an approval-cap alternative that complements ERC-2612, this gap should be closed in the extension itself.

Override the internal virtual 4-arg _approve(owner, spender, value, emitEvent) and enforce the cap only when emitEvent == true. This captures user-initiated approvals (including permit() and public approve()) while avoiding interference with _spendAllowance, which calls the 4-arg variant with emitEvent=false when decrementing allowance after a transfer.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@contracts/token/ERC20/extensions/ERC20SafeApproval.sol` around lines 55 - 69,
Override the internal 4-arg _approve(owner, spender, value, emitEvent) in
ERC20SafeApproval and enforce the cap only when emitEvent == true by calling
_checkCap(value) in that branch; also ensure user-initiated allowance clears
approvals expiry when value == 0 by deleting _approvalExpiry[owner][spender]
when emitEvent == true and value == 0, then delegate to super._approve(owner,
spender, value, emitEvent); keep the method signature as internal virtual
override to match the base contract.


function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
uint256 expiry = _approvalExpiry[from][msg.sender];
if (expiry != 0 && block.timestamp > expiry) {
revert ERC20ApprovalExpired(from, msg.sender, expiry);
}
return super.transferFrom(from, to, amount);
}
Comment on lines +55 to +77
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check which sender API is used by other ERC20 extensions in OpenZeppelin contracts
rg -nP --type=sol -C2 '\b(msg\.sender|_msgSender\(\))' -g 'contracts/token/ERC20/**'

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 107


🏁 Script executed:

#!/bin/bash
# Find ERC20 extension files first
find contracts/token/ERC20/extensions -name "*.sol" -type f | head -20

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 914


🏁 Script executed:

#!/bin/bash
# Check which sender API is used in ERC20 extensions
rg -n --glob='contracts/token/ERC20/**/*.sol' '(msg\.sender|_msgSender\(\))' -C 1

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 8849


🏁 Script executed:

#!/bin/bash
# Check the base ERC20 contract's implementation
rg -n --glob='contracts/token/ERC20/ERC20.sol' '(msg\.sender|_msgSender\(\))' -B 1 -A 1

Repository: OpenZeppelin/openzeppelin-contracts

Length of output: 914


Use _msgSender() instead of msg.sender for ERC-2771 (meta-transaction) compatibility.

OpenZeppelin's ERC20 uses _msgSender() in approve() (line 121), transferFrom() (line 143), and other public methods. This extension hardcodes msg.sender, creating a divergence with ERC2771Context (trusted forwarder):

  • In approve() (line 57), the expiry is deleted under msg.sender, but super.approve() records the allowance under _msgSender(). With a forwarder, these are different addresses—the wrong expiry entry is cleared and a stale expiring approval survives.
  • In approveWithExpiration() (lines 66–67), the expiry and event use msg.sender while super.approve() uses _msgSender(), causing off-chain indexers and on-chain checks to diverge for meta-tx users.
  • In transferFrom() (lines 72, 74), the spender lookup uses msg.sender, but super.transferFrom() consumes the allowance keyed by _msgSender().

All other ERC20 extensions (ERC20Wrapper, ERC4626, ERC20Burnable, ERC1363, etc.) consistently use _msgSender(). Mirror the pattern and use _msgSender() (already available via Context).

Proposed fix
     function approve(address spender, uint256 amount) public virtual override returns (bool) {
         _checkCap(amount);
-        delete _approvalExpiry[msg.sender][spender];
+        address owner = _msgSender();
+        delete _approvalExpiry[owner][spender];
         return super.approve(spender, amount);
     }

     function approveWithExpiration(address spender, uint256 amount, uint256 expiryTime) public virtual returns (bool) {
         if (expiryTime <= block.timestamp) {
             revert ERC20InvalidExpiration(expiryTime);
         }
         _checkCap(amount);
-        _approvalExpiry[msg.sender][spender] = expiryTime;
-        emit ApprovalWithExpiration(msg.sender, spender, amount, expiryTime);
+        address owner = _msgSender();
+        _approvalExpiry[owner][spender] = expiryTime;
+        emit ApprovalWithExpiration(owner, spender, amount, expiryTime);
         return super.approve(spender, amount);
     }

     function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
-        uint256 expiry = _approvalExpiry[from][msg.sender];
+        address spender = _msgSender();
+        uint256 expiry = _approvalExpiry[from][spender];
         if (expiry != 0 && block.timestamp > expiry) {
-            revert ERC20ApprovalExpired(from, msg.sender, expiry);
+            revert ERC20ApprovalExpired(from, spender, expiry);
         }
         return super.transferFrom(from, to, amount);
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@contracts/token/ERC20/extensions/ERC20SafeApproval.sol` around lines 55 - 77,
The extension incorrectly uses msg.sender instead of _msgSender(), causing
mismatches with ERC20's use of _msgSender() (breaks meta-transactions/trusted
forwarder). Update approve(), approveWithExpiration(), and transferFrom() to use
_msgSender() when accessing/deleting/setting
_approvalExpiry[msg.sender][spender] (and when emitting ApprovalWithExpiration)
and when reading expiry in transferFrom() (replace
_approvalExpiry[from][msg.sender] with _approvalExpiry[from][_msgSender()]) so
that the expiry mapping, emitted event and allowance consumption use the same
effective sender as super.approve()/super.transferFrom().


function _checkCap(uint256 value) internal view virtual {
uint256 cap = _approvalCap;
if (cap != type(uint256).max && value > cap) {
revert ERC20ApprovalCapExceeded(value, cap);
}
}

function _setApprovalCap(uint256 newCap) internal virtual {
uint256 oldCap = _approvalCap;
_approvalCap = newCap;
emit ApprovalCapUpdated(oldCap, newCap);
}

}
24 changes: 24 additions & 0 deletions contracts/token/ERC20/extensions/ERC20SafeApprovalToken.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {ERC20SafeApproval} from "./ERC20SafeApproval.sol";
import {ERC20} from "../ERC20.sol";

/**
* @dev Concrete ERC20 token using ERC20SafeApproval extension.
* Used for testing and demonstration purposes.
*/
contract ERC20SafeApprovalToken is ERC20SafeApproval {
constructor(string memory name, string memory symbol, uint256 cap, uint256 initialSupply)
ERC20(name, symbol)
ERC20SafeApproval(cap)
{
_mint(msg.sender, initialSupply);
}

// TODO: add owner storage and onlyOwner modifier

// TODO: add constructor

// TODO: expose setApprovalCap for owner
Comment on lines +19 to +23
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Reconcile/clean up the trailing TODOs.

  • // TODO: add constructor (line 21) is already done on lines 12–17 — drop it.
  • // TODO: add owner storage and onlyOwner modifier (line 19) and // TODO: expose setApprovalCap for owner (line 23) describe meaningful follow-ups that block delivering on the PR objective of "Allow on-chain configurable caps (updatable internally)" — as shipped, _setApprovalCap is unreachable after deployment, so the concrete token effectively has a fixed cap. Please either (a) wire Ownable + a setApprovalCap(uint256) onlyOwner entry point into this concrete reference token, or (b) explicitly note in the contract NatSpec and the changeset that this concrete token is a minimal demo and that ownership/admin control is intentionally out of scope.

Either resolution is fine, but the current "TODO list as a comment" leaves the concrete token in an in-between state.

Want me to draft the Ownable + setApprovalCap wiring (option a) so this concrete token actually satisfies the "configurable cap" objective?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@contracts/token/ERC20/extensions/ERC20SafeApprovalToken.sol` around lines 19
- 23, Remove the stale "// TODO: add constructor" comment and either wire
ownership or document intent; to satisfy the PR goal, inherit OpenZeppelin
Ownable in ERC20SafeApprovalToken, add an external onlyOwner function
setApprovalCap(uint256 newCap) that calls the internal _setApprovalCap(newCap),
and remove the "// TODO: add owner storage and onlyOwner modifier" and "// TODO:
expose setApprovalCap for owner" comments; ensure the contract
import/constructor changes reflect Ownable inheritance and that setApprovalCap
is the single owner-controlled entry point to update the cap.

}
Loading
Loading