
Building a Safe ERC20 Allowance Reset Pattern in Solidity
ERC20 allowances are one of the most common sources of user confusion and integration bugs in Ethereum applications. A wallet or dApp approves a spender for a token amount, and later that spender can transfer tokens up to the approved limit. If the allowance is changed carelessly, especially from one nonzero value to another, the contract can become vulnerable to race conditions and unexpected token movement.
This tutorial shows how to implement a safe allowance reset pattern in Solidity. You will build a small helper contract that reduces approval risk by forcing a two-step allowance update: first reset to zero, then set the new value. The pattern is useful for token managers, treasury tools, and admin-controlled workflows that need predictable ERC20 approvals.
Why allowance updates need care
The ERC20 approve model is simple, but it has a known edge case: if a spender sees a pending transaction that increases an allowance, it may be able to use both the old and new allowance depending on transaction ordering. This is especially relevant when a user changes an existing approval from one nonzero value to another nonzero value.
A safe pattern avoids that ambiguity by requiring:
- The current allowance to be cleared to zero.
- The new allowance to be set only after the reset is confirmed.
This does not eliminate every approval risk, but it removes the most common race condition around allowance replacement.
When this pattern is useful
Use a safe allowance reset flow when:
- Your contract manages approvals for an external protocol.
- You want to expose a controlled admin function for token spending limits.
- You need to update allowances in a predictable way across multiple tokens.
- You want to avoid relying on users to manually handle zero-reset behavior correctly.
It is less useful if your architecture can avoid allowances entirely, such as by using permit, direct transfers, or pull-based token flows.
Design goals
A robust allowance reset helper should:
- Work with standard ERC20 tokens.
- Prevent nonzero-to-nonzero allowance changes.
- Fail clearly if the token does not behave as expected.
- Emit events for off-chain monitoring.
- Restrict who can change allowances if the contract is privileged.
For this example, we will build a contract that can manage allowances for a set of approved tokens and spenders. The contract owner can reset and reassign allowances safely.
Contract overview
The contract will expose two functions:
resetAllowance(token, spender)sets the allowance to zero.setAllowance(token, spender, amount)sets a new allowance, but only if the current allowance is already zero.
This separation makes the workflow explicit and easy to audit.
| Function | Purpose | Safety rule |
|---|---|---|
resetAllowance | Clear an existing approval | Always sets allowance to 0 |
setAllowance | Assign a new approval | Requires current allowance to be 0 |
safeUpdateAllowance | Optional convenience flow | Performs reset then set in one transaction |
The convenience function is useful for tokens that allow same-transaction zero-reset and reapproval. However, some integrations prefer the two-step process to be explicit.
Implementation
Below is a complete example using OpenZeppelin-style interfaces and ownership control.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IERC20 {
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
}
abstract contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0), "Zero address");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract AllowanceResetManager is Ownable {
event AllowanceReset(address indexed token, address indexed spender);
event AllowanceSet(address indexed token, address indexed spender, uint256 amount);
error NonZeroAllowance(uint256 currentAllowance);
error ApproveFailed();
function resetAllowance(address token, address spender) external onlyOwner {
_approve(token, spender, 0);
emit AllowanceReset(token, spender);
}
function setAllowance(address token, address spender, uint256 amount) external onlyOwner {
uint256 current = IERC20(token).allowance(address(this), spender);
if (current != 0) {
revert NonZeroAllowance(current);
}
_approve(token, spender, amount);
emit AllowanceSet(token, spender, amount);
}
function safeUpdateAllowance(
address token,
address spender,
uint256 amount
) external onlyOwner {
_approve(token, spender, 0);
emit AllowanceReset(token, spender);
if (amount != 0) {
_approve(token, spender, amount);
emit AllowanceSet(token, spender, amount);
}
}
function _approve(address token, address spender, uint256 value) internal {
bool ok = IERC20(token).approve(spender, value);
if (!ok) revert ApproveFailed();
}
}
How the contract works
The contract uses the allowance held by itself as the token owner. That means it is suitable for treasury-style contracts, vaults, or protocol adapters that hold tokens and grant spending rights to external contracts.
resetAllowance
This function unconditionally sets the allowance to zero. It is the safest first step when changing a spender’s permissions.
setAllowance
Before assigning a new allowance, the function checks the current allowance. If it is nonzero, the call reverts. This prevents accidental overwrites of an active approval.
safeUpdateAllowance
This helper combines both steps. It is convenient when you want to update an allowance in one transaction, but still preserve the zero-reset rule internally.
Practical usage example
Imagine your treasury contract needs to interact with a DEX router. The router should only be allowed to spend a specific token amount for a single operation. A common pattern is:
- Reset router allowance to zero.
- Set allowance to the exact amount needed.
- Execute the swap or liquidity action.
- Reset allowance again after the operation.
This limits the router’s spending window and reduces leftover approval risk.
A typical flow might look like this:
function executeWithTemporaryApproval(
address token,
address router,
uint256 amount
) external onlyOwner {
_approve(token, router, 0);
_approve(token, router, amount);
// Call the external protocol here.
// Example: IRouter(router).swapExactTokensForTokens(...);
_approve(token, router, 0);
}
This pattern is especially valuable when interacting with third-party contracts that only need temporary access.
Best practices for safe allowance management
1. Prefer exact approvals over unlimited approvals
Unlimited approvals are convenient, but they expand the blast radius if a spender contract is compromised. Approve only what is needed for the current operation.
2. Reset after use
If the spender only needs temporary access, clear the allowance immediately after the external call completes.
3. Restrict who can manage approvals
If the contract is not meant to be permissionless, guard allowance changes with access control. In the example above, only the owner can update approvals.
4. Check token compatibility
Not all tokens behave perfectly. Some tokens return false instead of reverting, while others may not fully follow the ERC20 standard. Always test against the exact token contracts you plan to support.
5. Emit events
Events make it easier to audit approval changes from off-chain systems and monitoring tools.
Handling nonstandard ERC20 behavior
ERC20 tokens in the wild are not always consistent. Some tokens:
- return no boolean value,
- revert on zero approvals,
- require allowance to be set to zero before any new value,
- apply transfer fees or other custom logic.
If you need broader compatibility, consider using OpenZeppelin’s SafeERC20 library in production. It wraps token calls and handles many nonstandard return behaviors more gracefully than a raw interface call.
A safer production-grade version would use safeApprove-style logic or a helper that performs low-level calls and validates the result. The main architectural rule remains the same: do not overwrite a nonzero allowance directly.
Common mistakes to avoid
Overwriting an active allowance
This is the core mistake the pattern prevents. Never assume that setting a new allowance automatically cancels the old one in a safe way.
Forgetting to clear temporary approvals
If a contract approves a router for a swap and leaves the approval in place, that router can continue spending later if it is compromised or misused.
Using approve from the wrong address
The allowance owner must be the address that holds the tokens. In a contract-based treasury, the contract itself is the owner. In a user wallet flow, the user’s externally owned account is the owner.
Ignoring transaction ordering
Even if your UI submits a reset and reapprove flow, miners or validators can reorder transactions in ways that matter. That is why the zero-reset rule is important.
Extending the pattern
You can adapt the same design to support more advanced workflows:
- Per-token policies: enforce maximum allowance caps for specific assets.
- Spender whitelists: allow only known protocol contracts.
- Allowance schedules: update approvals only during predefined operational windows.
- Audit logging: record who requested the change and why.
For example, a treasury contract could maintain a mapping of approved spenders and maximum limits, then require every allowance update to stay within policy.
mapping(address => uint256) public maxAllowance;
function setPolicy(address spender, uint256 limit) external onlyOwner {
maxAllowance[spender] = limit;
}
function setPolicyAllowance(address token, address spender, uint256 amount) external onlyOwner {
require(amount <= maxAllowance[spender], "Exceeds policy");
_approve(token, spender, 0);
_approve(token, spender, amount);
}
This adds a governance layer on top of the safe reset pattern.
Testing recommendations
A good test suite should verify:
- setting allowance from zero succeeds,
- setting allowance from nonzero reverts,
- resetting to zero always succeeds,
- temporary approvals are cleared after use,
- events are emitted correctly,
- unsupported token behavior is handled as expected.
You should also test against at least one real token implementation and one mock token that simulates nonstandard behavior. That helps catch integration issues before deployment.
Summary
A safe ERC20 allowance reset pattern is a simple but important defensive technique. By forcing approvals to pass through zero before a new value is assigned, you reduce the risk of allowance race conditions and make token spending permissions easier to reason about.
Use this pattern whenever a contract manages approvals for external protocols, especially in treasury, vault, or automation contexts. Keep approvals small, temporary, and explicit, and prefer well-audited token helper libraries for production deployments.