What is ERC-4626? The tokenized vault standard, and how to use it
ERC-4626 is Ethereum's standard interface for yield-bearing vaults. How shares and assets work, rounding, the inflation attack, and how to use or build one.
On this page
ERC-4626 is the Ethereum standard for tokenized vaults: contracts that take deposits of one ERC-20 token (the asset) and give back ERC-20 shares that represent a slice of everything the vault holds. As the vault earns yield, each share redeems for more of the asset. The standard fixes the interface, so any wallet, aggregator or protocol can deposit into, value and exit any compliant vault with the same calls: deposit, mint, withdraw, redeem, plus read-only functions that convert between shares and assets. It is EIP-4626, status Final.
This guide covers what the standard defines, how shares and assets relate (including the rounding rules), the inflation attack every vault has to handle, and then the practical part: how to use an ERC-4626 vault as an integrator and how to implement one with OpenZeppelin. It reads a live mainnet vault over plain JSON-RPC along the way.
Why ERC-4626 exists
Before ERC-4626, every yield-bearing token had its own interface. Compound's cTokens, Aave's aTokens and Yearn's v2 vault tokens all did the same basic thing (hold an asset, accrue yield, let you exit), but each needed its own adapter to deposit, to read the exchange rate and to withdraw. The EIP's motivation says it directly: the lack of a standard "makes integration difficult at the aggregator or plugin layer" and "forces each protocol to implement their own adapters which are error prone".
ERC-4626 replaces those adapters with one interface. A protocol that accepts ERC-4626 shares as collateral, or an aggregator that routes deposits between vaults, writes the integration once.
Real vaults that implement it today:
- sUSDS and sDAI. Sky's savings tokens wrap USDS and DAI in the savings rate. Both are ERC-4626 vaults: Spark's sUSDS docs and sDAI docs list the standard functions, with USDS or DAI as the asset.
- Yearn V3. In Yearn V3, both the allocator vaults users deposit into and the strategies they allocate to are ERC-4626 compliant vaults.
- Lending vaults such as Morpho's curated vaults, which accept one asset and lend it across markets (Morpho docs).
The ERC-4626 interface
An ERC-4626 vault is an ERC-20 token: the shares. balanceOf, transfer and totalSupply all operate on shares, and the vault must implement the ERC-20 metadata (name, symbol, decimals). On top of that, the standard adds these functions:
| Function | What it does |
|---|---|
asset() |
The address of the underlying ERC-20 token |
totalAssets() |
Total assets the vault manages, including yield, net of fees charged to assets |
convertToShares(assets) / convertToAssets(shares) |
The exchange rate in an ideal case: no fees, no limits, no slippage |
deposit(assets, receiver) |
Pull exactly assets from the caller, mint shares to receiver |
mint(shares, receiver) |
Mint exactly shares to receiver, pulling whatever assets that costs |
withdraw(assets, receiver, owner) |
Burn owner's shares, send exactly assets to receiver |
redeem(shares, receiver, owner) |
Burn exactly shares from owner, send the resulting assets to receiver |
previewDeposit / previewMint / previewWithdraw / previewRedeem |
Simulate the matching action at the current block, fees included |
maxDeposit / maxMint / maxWithdraw / maxRedeem |
The most a given account can do right now without the call reverting |
There are two events. Deposit(sender, owner, assets, shares) is emitted by deposit and mint; Withdraw(sender, receiver, owner, assets, shares) by withdraw and redeem. Indexers can follow every vault's flows from those two events alone.
The pairs matter. deposit and redeem fix the amount going in (assets or shares); mint and withdraw fix the amount coming out. Pick the one that matches what the user typed: "deposit 1,000 USDS" is deposit, "I need exactly 1,000 USDS back" is withdraw, "exit my whole position" is redeem(balanceOf(user), …).
withdraw and redeem take an owner separate from msg.sender, so a contract with a share allowance can exit on a user's behalf. The vault spends the allowance the same way transferFrom does.
Shares, assets and rounding
A vault's exchange rate is totalAssets / totalSupply. Yield raises totalAssets while the share count stays the same, so every share is worth more. That is the whole mechanism: no rebasing, no reward claims. Your share balance never changes; what it redeems for does.
Because integer division has to round somewhere, the EIP fixes which way, always in the vault's favour so that no user can extract value from the others by rounding:
| When the vault calculates… | Functions | Rounds |
|---|---|---|
| Shares to give for assets deposited | deposit, previewDeposit |
Down |
| Assets to give for shares redeemed | redeem, previewRedeem |
Down |
| Shares to take for assets withdrawn | withdraw, previewWithdraw |
Up |
| Assets to take for shares minted | mint, previewMint |
Up |
| The ideal exchange rate | convertToShares, convertToAssets |
Down |
The two kinds of read-only function have different jobs, and the EIP is explicit that they are not interchangeable:
convertTo*is the idealised rate, without fees. It is meant for display and may be implemented as a robust, slow-moving rate (the EIP mentions a time-weighted average as an acceptable choice).preview*must be as close as possible to what the real call would return in the same transaction, fees included, and never more favourable to the user.depositmust return at leastpreviewDeposit's shares. Because it tracks on-chain conditions exactly, it can be manipulated, so the EIP warns against using it as a price oracle.max*must return 0 when an action is disabled,2**256 - 1when it is unlimited, and must never revert.
Read a live ERC-4626 vault over JSON-RPC
Because the interface is standard, the same calls read any vault. This script reads sUSDS (0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD) on Ethereum with raw eth_call requests: no library, no API key. Each function is called by its 4-byte selector, the first four bytes of the keccak-256 hash of its signature (how ABIs and selectors work). All reads are pinned to one block so the numbers agree with each other.
// Read an ERC-4626 vault over plain JSON-RPC: no libraries, no API key.const RPC_URL = process.env.RPC_URL ?? "https://ethereum-rpc.publicnode.com";const VAULT = process.argv[2] ?? "0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD"; // sUSDS // Function selectors: the first 4 bytes of keccak256 of each signature.const SELECTORS = { asset: "0x38d52e0f", // asset() totalAssets: "0x01e1d114", // totalAssets() totalSupply: "0x18160ddd", // totalSupply() decimals: "0x313ce567", // decimals() convertToAssets: "0x07a2d13a", // convertToAssets(uint256) previewDeposit: "0xef8b30f7", // previewDeposit(uint256)}; let id = 0;async function rpc(method, params) { const res = await fetch(RPC_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params }), }); const { result, error } = await res.json(); if (error) throw new Error(`${method}: ${error.message}`); return result;} const uint = (n) => BigInt(n).toString(16).padStart(64, "0");const call = (to, data, block) => rpc("eth_call", [{ to, data }, block]); // Pin every read to one block so the numbers agree with each other.const block = await rpc("eth_getBlockByNumber", ["latest", false]);const tag = block.number; const asset = "0x" + (await call(VAULT, SELECTORS.asset, tag)).slice(26);const shareDecimals = Number(await call(VAULT, SELECTORS.decimals, tag));const assetDecimals = Number(await call(asset, SELECTORS.decimals, tag));const oneShare = 10n ** BigInt(shareDecimals);const oneAsset = 10n ** BigInt(assetDecimals); const totalAssets = BigInt(await call(VAULT, SELECTORS.totalAssets, tag));const totalSupply = BigInt(await call(VAULT, SELECTORS.totalSupply, tag));const assetsPerShare = BigInt(await call(VAULT, SELECTORS.convertToAssets + uint(oneShare), tag));const sharesFor1000 = BigInt(await call(VAULT, SELECTORS.previewDeposit + uint(1000n * oneAsset), tag)); const fmt = (v, d) => (Number(v) / 10 ** d).toLocaleString("en-US", { maximumFractionDigits: 6 });console.log({ block: Number(tag), time: new Date(Number(block.timestamp) * 1000).toISOString(), vault: VAULT, asset, totalAssets: fmt(totalAssets, assetDecimals), totalSupply: fmt(totalSupply, shareDecimals), assetsPerShare: fmt(assetsPerShare, assetDecimals), sharesFor1000Assets: fmt(sharesFor1000, shareDecimals),});Run with node read-vault.mjs (Node 18 or later), it printed this on 21 November 2026:
{ block: 26464705, time: '2026-11-21T16:34:59.000Z', vault: '0xa3931d71877C0E7a3148CB7Eb4463524FEc27fbD', asset: '0xdc035d45d973e3ec169d2276ddab16f1e407384f', totalAssets: '1,955,999,944.947626', totalSupply: '1,750,915,889.702216', assetsPerShare: '1.11713', sharesFor1000Assets: '895.151298'}assetis USDS (0xdC035D45d973E3EC169d2276DDab16f1e407384F), as Spark's docs list it.assetsPerShareisconvertToAssets(1 share): one sUSDS redeemed for about 1.117 USDS at that block. The ratio only climbs: it is how the savings rate reaches holders.sharesFor1000AssetsispreviewDeposit(1000 USDS): about 895 sUSDS. Check it against the rate: 1,000 / 1.11713 ≈ 895.15. sUSDS charges no deposit fee (Sky's docs), so the preview and the ideal rate agree.totalAssets / totalSupplygives the same 1.117, as it should for a vault with no fees.
Pass another vault address as the first argument (sDAI is 0x83F20F44975D03b1b09e64809B757c47f942BEeA) and the same script reads it.
The inflation attack
The best-known ERC-4626 vulnerability hits empty or nearly empty vaults, and comes straight from the rounding rules. It is also called the donation attack.
- A vault is freshly deployed. The attacker deposits 1 wei of the asset and receives 1 share.
- The attacker sees a victim's deposit of 10,000 tokens in the mempool and front-runs it by transferring 10,000 tokens straight to the vault, without calling
deposit.totalAssetsjumps to 10,000 tokens + 1 wei;totalSupplyis still 1. - The victim's deposit mints
10,000 × 1 / (10,000 + 1 wei)shares, which rounds down to 0. - The attacker's single share now owns the whole vault, about 20,000 tokens, and redeems it.
The victim's deposit was a gift. Variants with smaller numbers take part of a deposit rather than all of it.
The mitigations:
- Virtual shares and a decimals offset (OpenZeppelin's approach). OpenZeppelin's
ERC4626computes the rate as(totalSupply + 10**offset) / (totalAssets + 1): virtual shares and a virtual asset that exist from the start. A donation is then shared with the virtual shares the attacker doesn't own, so the attack loses money. According to OpenZeppelin's analysis, the default offset of 0 already makes it unprofitable, and each extra digit of offset (shares carrying more decimals than the asset) makes it orders of magnitude more expensive. This has been the default since Contracts v4.9. - An initial deposit (dead shares). The deployer makes a non-trivial first deposit so the vault is never empty and the rate can't be pushed around cheaply; OpenZeppelin's contract notes recommend this. A common variant mints those first shares to an address no one controls, so they can never be withdrawn.
- Slippage checks on the user side. A depositor who checks the shares received against a minimum (or calls through a router that does) can't be robbed this way. The EIP itself advises adding slippage-protected entry points for EOAs, since they otherwise can't revert when the output falls short.
How to use an ERC-4626 vault
If you're integrating a vault (from a dapp, a contract or a script), the flow is the same for every compliant vault:
- Read
asset()to know what token the vault takes. - Approve the vault to spend that asset:
asset.approve(vault, amount). Deposits pull the tokens withtransferFrom, so the approval comes first. If the asset supports EIP-2612 permits, a router can take a signed permit instead of a separate approval. - Check limits with
maxDeposit(receiver). A paused or capped vault returns 0 or the remaining room. - Quote with
previewDeposit(assets), and set a minimum you'll accept (say, the preview minus 0.5%). - Deposit with
deposit(assets, receiver). From a contract, check the returned share count against your minimum and revert if it's short. - Value the position at any time with
convertToAssets(balanceOf(user)). - Exit with
redeem(balanceOf(user), receiver, owner)to close fully, orwithdraw(assets, receiver, owner)for an exact amount out. Quote withpreviewRedeemorpreviewWithdrawand checkmaxRedeemormaxWithdrawfirst: a vault whose funds are lent out may not have liquidity for everyone. To exit for someone else, a contract needs an allowance on their shares; the EIP notes that a vault may support EIP-2612 permits on its shares for that, but the standard doesn't require it.
Two cautions from the EIP's security section. A contract can implement the interface without following the spec, so review a vault before letting users send it funds permissionlessly. And previewRedeem and previewMint for the same share amount can differ a lot when a vault charges entry or exit fees, so always use the preview that matches the action.
Find a wallet's vault positions with an API
Vault shares are ordinary ERC-20 balances, so a token balance API shows them. GoldRush's token balance API (balances_v2, part of the GoldRush Foundational API) lists every ERC-20 a wallet holds on a chain, with contract_address, contract_decimals and the raw balance per token. It costs 1 per call. It doesn't flag which tokens are vaults, so this script asks each token for asset() over JSON-RPC and values the ones that answer with convertToAssets.
You need Node.js 18 or later and a GoldRush API key in the GOLDRUSH_API_KEY environment variable. The script uses top-level await, so save it as vault-positions.mjs and run node vault-positions.mjs <wallet-address>:
const API = "https://api.covalenthq.com/v1";const RPC_URL = process.env.RPC_URL ?? "https://ethereum-rpc.publicnode.com";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; async function ethCall(to, data) { const res = await fetch(RPC_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_call", params: [{ to, data }, "latest"] }), }); const { result, error } = await res.json(); return error || !result || result === "0x" ? null : result;} // A wallet's ERC-4626 positions on Ethereum: its share balances, valued in the underlying asset.async function getVaultPositions(wallet) { const url = `${API}/eth-mainnet/address/${wallet}/balances_v2/?no-spam=true`; const res = await fetch(url, { headers }); if (!res.ok) throw new Error(`${res.status} ${await res.text()}`); const { data } = await res.json(); const positions = []; for (const token of data.items) { if (token.is_native_token || token.balance === "0") continue; // asset() answers on a vault and reverts on a plain ERC-20. It's a hint, not proof of compliance. const asset = await ethCall(token.contract_address, "0x38d52e0f"); if (!asset || asset.length !== 66) continue; const shares = BigInt(token.balance); const assets = await ethCall(token.contract_address, "0x07a2d13a" + shares.toString(16).padStart(64, "0")); positions.push({ vault: token.contract_ticker_symbol, address: token.contract_address, asset: "0x" + asset.slice(26), shares: token.balance, assets: assets && BigInt(assets).toString(), // in the asset's smallest unit }); } return positions;} console.log(await getVaultPositions(process.argv[2]));For each vault share it finds, it returns the vault, its underlying asset, the share balance and what those shares redeem for in the asset's smallest unit. It makes one or two eth_call requests per token, one after another, so a wallet holding hundreds of tokens takes a while and can hit a public node's rate limit: point RPC_URL at your own node for large wallets. A plain ERC-20 such as USDC reverts on asset() and is skipped. Answering asset() is a strong hint that a token is a vault, not proof that it follows the standard. To see how many wallets hold a given vault's shares, the same contract address works with token holder data.
Handle errors from the token balance API
A failed call returns the same envelope as a successful one, with data set to null. The GoldRush error handling docs show this body for a chain name the API doesn't recognise, such as a typo in eth-mainnet:
{ "data": null, "error": true, "error_message": "Chain nosuchchain-mainnet not supported.", "error_code": 501 }error_code is a JSON number and always equals the HTTP status, so the if (!res.ok) check in getVaultPositions throws with the status and this message. A 501 means the chain or endpoint can't serve the request, so retrying it unchanged won't succeed: fix the chain name. A wrong or malformed key returns a JSON 401 in the same envelope, but a request with no Authorization header at all gets an HTML page from the edge proxy (<title>401 Authorization Required</title>), which is why the script reads the error body as text. Failed requests cost no credits.
How to implement an ERC-4626 vault
Don't write the share accounting yourself. OpenZeppelin's ERC4626 implements the whole interface, the rounding rules and the virtual-share defence; you supply the asset and, for a real strategy, where the assets go. A minimal vault on OpenZeppelin Contracts 5.6.1, installed with:
npm install @openzeppelin/contracts@5.6.1Compile it with solc 0.8.25 or later, or with 0.8.24 and the EVM version set to cancun: OpenZeppelin 5.6 uses the mcopy opcode, which 0.8.24's default EVM version doesn't have.
// SPDX-License-Identifier: MITpragma solidity ^0.8.24; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol"; /// A vault over one ERC-20. Shares carry 6 more decimals than the asset, which makes/// the inflation attack far more expensive (see OpenZeppelin's ERC-4626 guide).contract SimpleVault is ERC4626 { constructor(IERC20 asset_) ERC20("Simple Vault Share", "svTKN") ERC4626(asset_) {} function _decimalsOffset() internal pure override returns (uint8) { return 6; }}That is a complete, compliant vault. By default totalAssets() is the vault's own balance of the asset, so any asset sent to it (yield paid in, or a donation) raises the value of every share. From here:
- To deploy assets into a strategy, override
totalAssets()to count what the vault holds plus what it has deployed, and move funds out and back by overriding the internal_depositand_withdrawhooks (callsuperso the transfers and events still happen). A vault whosetotalAssets()ignores deployed funds will under-price its shares. - To charge fees, follow OpenZeppelin's fee pattern: the
preview*functions must include the fee, sodeposit(100, …)takes exactly 100 tokens including the fee and mints whatpreviewDeposit(100)returned. - To cap or pause, override the
max*functions. They must reflect the real limit and must not revert. - Make the first deposit at deployment if the vault will hold real value, as described under the inflation attack.
To try it, compile it in Remix, Foundry or Hardhat with @openzeppelin/contracts@5.6.1, deploy it on a testnet with an ERC-20 as the asset, approve the vault, call deposit, transfer some of the asset to the vault directly to simulate yield, and redeem: you get back more than you put in. Then audit it before it holds anyone's money.
Beyond ERC-4626: async and multi-asset vaults
ERC-4626 assumes deposits and redemptions settle in the same transaction. Two later standards, both Final, extend it where that doesn't hold:
- ERC-7540, asynchronous vaults. Adds
requestDepositandrequestRedeem. A request goes Pending, then Claimable once the vault processes it, and the user claims with the normaldeposit,mint,withdraworredeem. It is built for real-world-asset funds, cross-chain and undercollateralised lending, liquid staking and anything else with a settlement delay. For the asynchronous side, thepreview*functions must revert, since there is no same-block answer to give. - ERC-7575, multi-asset vaults. Lets several entry points, one per asset, share a single share token, by adding a
share()function that can point to an external ERC-20. ERC-7540 requires it.
Frequently asked questions
What is ERC-4626 in simple terms?
ERC-4626 is a standard for yield-bearing vaults on Ethereum and other EVM chains. You deposit one ERC-20 token, the vault gives you share tokens, and as the vault earns yield each share redeems for more of the original token. Because every compliant vault uses the same functions (deposit, redeem, convertToAssets and so on), wallets and protocols can support all of them with one integration.
What is the difference between deposit and mint, or withdraw and redeem?
They fix different sides of the trade. deposit takes an exact amount of assets and mints however many shares that buys; mint creates an exact number of shares and takes however many assets they cost. redeem burns an exact number of shares; withdraw sends out an exact amount of assets and burns whatever shares that takes. Use redeem with the full share balance to exit a position completely.
What is the difference between convertToAssets and previewRedeem?
convertToAssets is the ideal exchange rate, without fees, and may be smoothed; it is meant for display. previewRedeem simulates an actual redemption at the current block, fees included, and must not return more than the real redeem would. Use preview* when quoting a transaction, and remember that preview* can be manipulated within a block, so neither is a safe price oracle on its own.
What is the ERC-4626 inflation attack?
An attacker deposits a tiny amount into an empty vault, then donates a large amount of the asset directly to it, so one share becomes very expensive. A victim's deposit then rounds down to zero or very few shares, and the attacker redeems the difference. OpenZeppelin's ERC4626 defends with virtual shares and a configurable decimals offset; deployers can also seed the vault with an initial deposit, and users can enforce a minimum number of shares out.
Are aTokens or cTokens ERC-4626?
Not natively. Aave's aTokens rebase (your balance grows) and Compound v2's cTokens have their own exchange-rate interface; both predate the standard. Wrappers exist that expose them as ERC-4626 vaults, which is how many protocols integrate them today. Savings tokens such as sUSDS and sDAI, Yearn V3 vaults and Morpho vaults implement ERC-4626 directly.
What are ERC-7540 and ERC-7575?
Both are Final extensions of ERC-4626. ERC-7540 adds asynchronous requests for vaults that can't settle deposits or redemptions instantly, such as real-world-asset funds. ERC-7575 lets several asset-specific vault contracts share one share token, which enables multi-asset vaults; ERC-7540 builds on it.
Next steps
- Read the standard itself: EIP-4626, especially its security considerations.
- Work through OpenZeppelin's ERC-4626 guide for the inflation-attack maths and the fee example.
- Run
read-vault.mjsabove against a vault you use, and comparepreviewDepositwithconvertToSharesto see its fees. - List a wallet's vault shares with the token balance API.
- Learn how Ethereum contract addresses work, and how to check you have the real vault and not a lookalike.