
Building a Safe ERC20 Permit-Based Deposit Vault in Solidity
Why a permit-based vault is useful
Traditional ERC20 deposits require two on-chain steps:
- The user approves the vault to spend tokens.
- The user calls the vault’s deposit function.
That extra approval transaction adds latency, gas cost, and complexity. A permit-based vault removes the need for a separate approval by using the token’s signed permit mechanism.
Common use cases
- One-click token deposits in DeFi apps
- Gas-efficient onboarding for vaults and savings products
- Deposit flows in marketplaces or escrow systems
- Batch deposit UX where each user signs a permit once
Important caveat
This pattern only works with ERC20 tokens that implement permit in the EIP-2612 style. Not all tokens support it, so production systems often need a fallback path for standard approvals.
Design goals for a safe vault
A robust permit-based vault should:
- Verify the token supports
permit - Use
SafeERC20for token transfers - Prevent reentrancy during deposit logic
- Track deposits per user
- Avoid assuming the permit succeeded unless the token call does not revert
- Support deadline checks and signature replay protection through the token’s nonce system
The vault itself does not implement signature validation. The ERC20 token does that. The vault only forwards the signed permit data to the token contract and then performs the transfer.
How the flow works
A typical deposit flow looks like this:
- The user signs a permit message off-chain.
- The user submits
depositWithPermit(...)to the vault. - The vault calls
permit(...)on the token. - The vault pulls tokens from the user using
transferFrom(...). - The vault records the deposit.
This is atomic: if any step fails, the whole transaction reverts.
Example implementation
The following contract demonstrates a practical permit-based deposit vault for a single ERC20 token.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract PermitDepositVault is ReentrancyGuard {
using SafeERC20 for IERC20;
IERC20 public immutable asset;
IERC20Permit public immutable permitToken;
mapping(address => uint256) public deposited;
event Deposited(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
constructor(address token) {
require(token != address(0), "token is zero");
asset = IERC20(token);
permitToken = IERC20Permit(token);
}
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external nonReentrant {
require(amount > 0, "amount is zero");
// Approve this vault to spend exactly `amount` via signature.
permitToken.permit(msg.sender, address(this), amount, deadline, v, r, s);
// Pull the tokens after permit succeeds.
asset.safeTransferFrom(msg.sender, address(this), amount);
deposited[msg.sender] += amount;
emit Deposited(msg.sender, amount);
}
function deposit(uint256 amount) external nonReentrant {
require(amount > 0, "amount is zero");
asset.safeTransferFrom(msg.sender, address(this), amount);
deposited[msg.sender] += amount;
emit Deposited(msg.sender, amount);
}
function withdraw(uint256 amount) external nonReentrant {
require(amount > 0, "amount is zero");
uint256 balance = deposited[msg.sender];
require(balance >= amount, "insufficient deposited");
deposited[msg.sender] = balance - amount;
asset.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
}
Key implementation details
1. Use SafeERC20
Not all ERC20 tokens return a boolean consistently. OpenZeppelin’s SafeERC20 handles non-standard return behavior and reverts when transfers fail.
2. Use ReentrancyGuard
Even though ERC20 transfers are usually straightforward, a vault should still guard deposit and withdrawal functions with nonReentrant. This is especially important if the token has hooks, unusual behavior, or is upgraded later to a more complex asset.
3. Separate deposit and withdrawal accounting
The contract tracks deposited[user] independently from the token balance held by the vault. This is a common pattern for internal accounting and makes withdrawals explicit.
4. Let the token enforce permit validity
The vault does not inspect the permit signature itself. The token contract checks:
- signer authenticity
- nonce correctness
- deadline validity
- domain separator consistency
That keeps the vault simpler and less error-prone.
Comparing deposit approaches
| Approach | User transactions | UX | Security notes |
|---|---|---|---|
approve() then deposit() | 2 | Slower, more friction | Standard and widely supported |
permit() then depositWithPermit() | 1 | Better UX | Requires EIP-2612 support |
approve() with unlimited allowance | 2 initially, then 1 | Convenient but risky | Larger approval surface area |
For most modern dApps, permit-based deposits are the best choice when token support exists. For unsupported tokens, keep a standard deposit function as a fallback.
Handling deadlines and replay protection
The deadline parameter is critical. It limits how long the signed permit remains valid. If a user signs a permit but never submits the transaction, the signature should eventually expire.
Replay protection comes from the token’s nonce system. Each successful permit increments the nonce, so the same signature cannot be reused.
Best practices
- Use short deadlines for time-sensitive deposits
- Surface the deadline clearly in the frontend
- Never reuse a permit signature across multiple vault calls
- Treat permit signatures as single-use authorizations
Supporting both permit and non-permit users
A production vault should not force every user into the permit flow. Some tokens do not support permit, and some wallets or signing flows may not be available in every environment.
The example contract includes both:
depositWithPermit(...)for signature-based depositsdeposit(...)for standard allowance-based deposits
This dual-path design makes the vault more flexible without sacrificing usability.
When to prefer each path
- Use
depositWithPermit(...)for supported tokens and first-time users - Use
deposit(...)for tokens without permit support - Use
deposit(...)in scripts or integrations that already manage approvals
Frontend integration tips
A permit flow is only as good as the client-side implementation. The frontend must build the correct typed data and submit the signature parameters accurately.
Typical frontend steps
- Read the user’s current nonce from the token.
- Build the EIP-712 typed data for the permit.
- Ask the wallet to sign the typed data.
- Submit
depositWithPermit(...)with the signature values.
Data you must match exactly
- token address
- owner address
- spender address, which is the vault
- value, which should match the intended deposit amount
- nonce
- deadline
- chain ID
- token name and version, if required by the token’s domain separator
A mismatch in any of these fields will cause the permit call to revert.
Security considerations
Avoid overbroad approvals
A permit can authorize a specific amount, which is safer than granting an unlimited allowance. Prefer exact-amount permits whenever possible.
Validate zero-address inputs in constructors
The vault constructor rejects a zero token address. This prevents deployment mistakes that would otherwise create a broken contract.
Keep accounting changes before external transfers on withdrawal
In withdraw, the balance is reduced before the token transfer occurs. This follows the checks-effects-interactions pattern and reduces reentrancy risk.
Do not assume all tokens are standard
Some tokens have unusual transfer behavior, fee mechanics, or broken permit implementations. If you plan to support arbitrary assets, test each token carefully and consider allowlisting.
Extending the vault safely
A simple vault is often enough, but real systems may need additional features.
Per-user caps
You can add a maximum deposit limit per address to prevent concentration risk or enforce product rules.
Total vault cap
A global cap can stop deposits once the vault reaches a target size.
Emergency pause
A pause mechanism can be useful if the token contract is upgraded, compromised, or behaves unexpectedly.
Multi-asset support
If you want to support multiple tokens, store separate accounting per asset address. Be careful not to mix balances across assets.
A multi-asset design usually looks like:
mapping(address token => mapping(address user => uint256))- separate deposit and withdraw functions per token
- explicit allowlisting for supported assets
Testing scenarios to cover
A permit-based vault should be tested beyond the happy path.
Recommended tests
- Successful deposit with valid permit
- Deposit fails with expired deadline
- Deposit fails with invalid signature
- Deposit fails if the token does not support permit
- Withdraw succeeds after deposit
- Withdraw fails when balance is insufficient
- Repeated permit reuse fails due to nonce mismatch
- Deposit with zero amount reverts
Edge cases worth checking
- User signs permit for one amount but submits a different amount
- Token returns unusual revert data
- Frontend uses the wrong chain ID
- Permit is signed for a different spender address
Practical deployment notes
Before deploying, confirm the token’s permit interface matches the expected EIP-2612 shape. Some tokens implement variations or non-standard extensions.
Also verify that your chosen OpenZeppelin version matches your Solidity compiler version. The example above targets Solidity ^0.8.24, which is a solid baseline for modern projects.
If you are integrating with a popular token like USDC or DAI, do not assume the permit format is identical across assets. Always inspect the token documentation and test on a fork or testnet first.
Summary
A permit-based deposit vault is a clean way to streamline ERC20 deposits without sacrificing safety. It reduces user friction, keeps approvals scoped to a single action, and fits well into modern dApp UX.
The safest implementation pattern is straightforward:
- use
permitfor authorization - use
SafeERC20for transfers - guard state-changing functions with
nonReentrant - keep fallback deposit support for non-permit tokens
- test signature, deadline, and nonce behavior thoroughly
When implemented carefully, this pattern provides a strong balance of usability and security for token deposit workflows.