
Building a Safe ERC20 Token Vesting Wallet in Solidity
What a vesting wallet should do
A vesting wallet typically has three responsibilities:
- Accept ERC20 tokens intended for future release.
- Track a vesting schedule based on timestamps.
- Allow the beneficiary to claim unlocked tokens as time passes.
A robust implementation should also:
- prevent reentrancy during token release,
- handle partial claims correctly,
- support multiple token deposits over time,
- avoid assumptions about token decimals,
- expose readable state for off-chain monitoring.
The contract below focuses on a single beneficiary and a single schedule, which keeps the design easy to reason about and suitable for many real-world use cases.
Vesting model
We will use a linear vesting model with an optional cliff:
- Start time: vesting begins.
- Cliff duration: no tokens can be claimed before this point.
- Duration: total time over which tokens vest.
- Beneficiary: the address that can claim vested tokens.
The amount vested at any timestamp is:
0before the cliff,totalAllocationafter the end,- proportional in between.
This model is predictable and easy to verify.
| Parameter | Meaning | Example |
|---|---|---|
start | Vesting start timestamp | 1700000000 |
cliffDuration | Lockup before first claim | 90 days |
duration | Total vesting period | 365 days |
beneficiary | Recipient of vested tokens | 0x1234... |
Contract implementation
The contract below uses OpenZeppelin’s IERC20, SafeERC20, and ReentrancyGuard. It also includes a small amount of bookkeeping so the beneficiary can claim only what has vested, not the entire balance.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
contract ERC20VestingWallet is ReentrancyGuard {
using SafeERC20 for IERC20;
address public immutable beneficiary;
uint64 public immutable start;
uint64 public immutable cliff;
uint64 public immutable duration;
// Tracks how many tokens have already been released.
mapping(address => uint256) public released;
event TokensReleased(address indexed token, uint256 amount);
event TokensDeposited(address indexed token, uint256 amount);
error InvalidSchedule();
error NotBeneficiary();
error NothingToRelease();
constructor(
address _beneficiary,
uint64 _start,
uint64 _cliffDuration,
uint64 _duration
) {
if (_beneficiary == address(0)) revert InvalidSchedule();
if (_duration == 0) revert InvalidSchedule();
if (_cliffDuration > _duration) revert InvalidSchedule();
beneficiary = _beneficiary;
start = _start;
cliff = _start + _cliffDuration;
duration = _duration;
}
function deposit(address token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
emit TokensDeposited(token, amount);
}
function vestedAmount(address token, uint64 timestamp) public view returns (uint256) {
uint256 totalAllocation = IERC20(token).balanceOf(address(this)) + released[token];
if (timestamp < cliff) {
return 0;
}
if (timestamp >= start + duration) {
return totalAllocation;
}
uint256 elapsed = timestamp - start;
return (totalAllocation * elapsed) / duration;
}
function releasable(address token) public view returns (uint256) {
uint256 vested = vestedAmount(token, uint64(block.timestamp));
return vested - released[token];
}
function release(address token) external nonReentrant {
if (msg.sender != beneficiary) revert NotBeneficiary();
uint256 amount = releasable(token);
if (amount == 0) revert NothingToRelease();
released[token] += amount;
IERC20(token).safeTransfer(beneficiary, amount);
emit TokensReleased(token, amount);
}
}
How the contract works
1. Schedule validation in the constructor
The constructor rejects invalid schedules early:
- beneficiary must not be the zero address,
- duration must be non-zero,
- cliff cannot exceed duration.
This prevents deployment of a contract that can never release tokens or that has inconsistent timing.
2. Deposits are permissionless
Anyone can deposit tokens into the vesting wallet using deposit(). This is useful because:
- the project treasury can fund the wallet,
- a multisig can top it up later,
- a third party can transfer tokens in if needed.
If you want stricter control, you can restrict deposits to an owner or factory contract. For many vesting setups, permissionless deposits are acceptable because they do not affect who can withdraw.
3. Vesting is calculated from total allocation
The key idea is this line:
uint256 totalAllocation = IERC20(token).balanceOf(address(this)) + released[token];
This treats the vesting allocation as the sum of:
- tokens still held by the contract,
- tokens already released.
That means the vesting schedule applies to the full funded amount, not just the current balance. This is important because the beneficiary may claim tokens in multiple transactions over time.
4. Claims are incremental
The released[token] mapping tracks how much has already been paid out. When the beneficiary calls release(), the contract transfers only the difference between vested and already released tokens.
This avoids double claims and makes the contract safe for repeated use.
Example vesting timeline
Assume the following schedule:
- start: January 1
- cliff: 30 days
- duration: 365 days
- total funded amount: 120,000 tokens
At different timestamps:
| Time | Vested amount |
|---|---|
| Day 0 | 0 |
| Day 15 | 0 |
| Day 30 | 9,863 |
| Day 180 | 59,178 |
| Day 365 | 120,000 |
The exact values depend on integer division, so small rounding differences are expected. The contract always rounds down, which is the safest default because it never releases more than intended.
Why this design is safer than a naive implementation
A naive vesting contract often makes one of these mistakes:
- releases the full balance immediately after the cliff,
- forgets to subtract previously released tokens,
- uses
transfer()instead ofsafeTransfer(), - allows anyone to withdraw,
- ignores reentrancy risks,
- assumes a fixed token amount without accounting for additional deposits.
The implementation above avoids those issues by combining explicit accounting with a minimal external surface area.
| Risk | Naive approach | Safer approach |
|---|---|---|
| Double withdrawal | No release tracking | released[token] mapping |
| Unsafe token transfer | transfer() | SafeERC20.safeTransfer() |
| Unauthorized claims | Public release function | Beneficiary-only release |
| Reentrancy | State updated after transfer | State updated before transfer + nonReentrant |
| Schedule errors | No validation | Constructor checks |
Practical integration pattern
A common production workflow is:
- Deploy the vesting wallet with the beneficiary and schedule.
- Fund it with the required ERC20 tokens.
- Let the beneficiary claim periodically.
- Monitor
TokensReleasedevents for accounting and reporting.
For example, a treasury multisig might deploy the contract during a token launch, then transfer the full allocation into the wallet. The beneficiary can later claim monthly or quarterly without requiring manual approval from the treasury.
If you are integrating this into a frontend, expose:
vestedAmount(token, timestamp)releasable(token)released(token)beneficiary()cliff()duration()
These functions are enough to build a clear dashboard showing locked, vested, and claimable balances.
Best practices for production use
Prefer immutable schedule parameters
The beneficiary, start time, cliff, and duration are immutable in this design. That is a good default because it prevents governance or admin mistakes from changing the vesting terms after deployment.
Use a trusted funding process
Even though deposits are permissionless here, the actual funding source should be controlled. In practice, a multisig or treasury contract should send the intended allocation in one or more transactions.
Consider token-specific edge cases
Some ERC20 tokens have unusual behavior, such as:
- transfer fees,
- rebasing balances,
- blacklist restrictions,
- non-standard return values.
SafeERC20 helps with return-value handling, but it cannot fix token economics. If you plan to vest such tokens, test them carefully.
Add off-chain monitoring
Events are essential for operational visibility. Index TokensDeposited and TokensReleased so your team can reconcile balances against vesting reports and legal agreements.
Test boundary conditions
Your test suite should cover:
- before cliff,
- exactly at cliff,
- exactly at end,
- partial claim after partial vesting,
- repeated claims,
- multiple deposits,
- zero releasable amount,
- malformed constructor inputs.
Extending the contract
This pattern can be extended in several useful ways.
Multiple beneficiaries
You can deploy one vesting wallet per beneficiary, which is often the simplest and safest approach. If you need a shared contract for many beneficiaries, introduce a struct-based schedule mapping and be prepared for more complex accounting.
Revocable vesting
Some organizations want the ability to revoke unvested tokens if a contributor leaves early. That requires a separate admin role and careful accounting for already vested amounts. Revocation increases complexity and should be added only when there is a clear business need.
Token recovery for unrelated assets
A vesting wallet may accidentally receive unrelated tokens. If you add a rescue function, ensure it cannot withdraw the vested token before the schedule completes, or restrict it to tokens that are not part of the vesting plan.
Cliff-only unlocks
If your use case needs a single unlock date rather than linear vesting, you can simplify the logic so that vestedAmount() returns zero until a specific timestamp and the full amount afterward.
Testing strategy
A good test suite should verify both arithmetic and access control. Use timestamp manipulation in your framework to simulate the passage of time.
Recommended test cases:
release()reverts for non-beneficiary callers,release()reverts before the cliff,- vested amount increases linearly over time,
- released tokens are deducted from future claims,
- deposits after deployment are included in future vesting calculations,
- the final claim empties the remaining releasable balance.
A useful invariant is:
released[token] + contract balance for token = total funded amount - any external transfers
If your contract does not allow arbitrary external transfers, this invariant becomes easier to reason about.
Common mistakes to avoid
Using block numbers instead of timestamps
Vesting schedules are usually time-based, not block-based. Use block.timestamp unless you have a strong reason to do otherwise.
Forgetting integer rounding
Solidity truncates fractional results. Always expect the vested amount to round down slightly until the schedule completes.
Making the beneficiary also the admin
If the beneficiary can change the schedule, the vesting promise becomes weaker. Keep schedule control separate from claim rights.
Assuming one token forever
A vesting wallet may hold multiple ERC20 tokens, especially if the same address is reused for different distributions. Keep accounting token-specific.
Conclusion
A safe ERC20 vesting wallet should be simple, explicit, and easy to audit. The contract in this tutorial uses a linear schedule, optional cliff, release tracking, and safe token transfers to provide a practical foundation for real-world token distribution.
For many teams, this pattern is enough to support employee grants, advisor allocations, ecosystem incentives, and treasury-managed unlocks without introducing unnecessary complexity.