An Comprehensive Analysis of ERC-4626 and DeFi

AdvancedFeb 23, 2024
This article analyzes the basic principles of ERC-4626 and its application in DeFi in an all-round way.
An Comprehensive Analysis of ERC-4626 and DeFi

01 What is ERC-4626

ERC-4626 is a tokenized vault with a single underlying EIP-20 token.

First of all, it is an ERC-20 based proposal and fully compatible with it.

Secondly, understand the concept of a vault, which is not a treasury. The treasury currently on the market is basically a contract wallet, most of which are Gnosis Safe, which mainly provides safe fund entry and exit functions. But for an organization, in addition to the inflow and outflow of funds, the flow of funds can also generate income.

The motivation for this proposal: The lack of standards for tokenized vaults has resulted in different implementation details of many vaults on the market, such as lending markets, aggregators, interest-bearing tokens, etc. This makes integrating aggregators and plugins at the protocol level difficult, error-prone, and a waste of development resources.

When the current status of this proposal is Final, it means it is a relatively stable standard.

02 Specification

Tokens that follow ERC-4626 must fully implement ERC-20, which is used to represent shares. Here are a few simple concepts.

  • Asset: The underlying token managed by the vault, following the ERC-20 standard.
  • Share: Vault token, also known as vToken. It has a proportional relationship with the asset.
  • Fee: An amount charged by the vault when an asset or share changes. It can be deposits, earnings, asset management, withdrawals, etc.
  • Slippage: The difference between the published price of share deposits and withdrawals and the actual economy. Below is more explanation of the concept of slippage in the DeFi field.

Slippage is the difference between the expected price of a trade and the actual execution price. Slippage occurs when there is a delay between placing a trade and executing it, and the price of the asset being traded changes.

For example, if you find 20 ETH and 80 USDT in the AMM pool, your expected ETH price is 4 USDT/ETH. However, if you plan to spend 20 USDT to swap in the pool, you will only end up with 4 ETH instead of the expected 5 ETH, which means you suffer a slippage loss of 1 USDT/ETH. Your actual purchase price will be 5 USDT, not the expected 4 USDT.

Slippage is particularly common in fast-moving markets or high-volatility assets, as well as long-tail assets with constrained liquidity. Regardless, it has a significant impact on trading performance and it is important to consider slippage when placing trades.

03 Contract analysis

The contract code comes from the OpenZeppelin smart contract code library:

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/ERC4626.sol

The ERC-4626 contract inherits from ERC-20. This part will not be summarized. It is also an abstract contract itself. The interfaces that the contract must implement are as follows:

The interfaces are quite rich, most of them are relatively simple and can be divided into two categories: read and write.

Write

The main interfaces for writing data are deposit, mint, withdraw, and redeem.

  • Deposit determines the amount of assets and transfers them to the vault. It mints shares at the same time. You can use the previewDeposit method to see in advance how many shares can be minted.

  • Withdraw (withdraw money) determines the amount of assets to transfer out of the vault, and burns shares at the same time. You can use the previewWithdraw method to check in advance how many shares have been burned。
  • Mint uses the shares parameter. In fact, this method is equivalent to deposit, which determines the minted shares to calculate the assets that need to be deposited. You can use the previewMint method to check in advance how many assets will be taken out.
  • Redeem uses the shares parameter, which is equivalent to withdraw, determining the burned shares to calculate the assets that need to be transferred out. You can use the previewRedeem method to check in advance how many assets will be redeemed. \

In fact, due to the existence of slippage, using the preview method to view the expected numbers may be inaccurate, which is also a common problem in the industry and may cause some security issues, which will be discussed later.

Read

The several preview methods mentioned earlier, as well as the public convertToShares and convertToAssets, actually call the _convertToShares and _convertToAssets methods internally.

These two core methods are to calculate the proportional relationship between assets and shares. The variables involved include share supply, current total assets, number of decimal points, and decimal point rounding methods.

The above is the basic implementation of the ERC-4626 abstract contract. The actual vault contract is much more complicated than it.

For the vault contract, there are two relatively important functions to implement. One is the deposit and withdrawal function, the conversion of assets and shares; the other is the way to obtain income, which will be explained with examples below.

04 Ecology and Application

Similar to some other popular EIPs, ERC-4626 also has an alliance ecosystem (https://erc4626.info/) maintained by dedicated personnel, which collects some lending protocols and applications currently on the market that are compatible with ERC-4626, and there are also news, open source libraries, security and other information. If your vault is adapted to ERC-4626, you can also submit an application there.

Below we analyze an application example, Aladdin DAO’s AladdinCRVV2 vault (https://concentrator.aladdin.club/vaults/). Aladdin DAO has many vault contracts, and this is just one of the more active ones.

AladdinCRVV2 Vault

The vault earns income by staking cvxCRV tokens.

  • The vault contract is an upgradeable contract

(https://etherscan.io/address/0x2b95A1Dcc3D405535f9ed33c219ab38E8d7e0884). And you can check through the github code that the previous version is not compatible with ERC-4626

  • In fact, there are many operation options for deposits and withdrawals, which is quite convenient and saves gas. There is too much code, so I won’t post it here.
    • Deposit: cvxCRV tokens will be deposited into the vault by default. Moreover, there is depositWithCRV, which is convenient for CRV and can also be deposited
    • When withdrawing, cvxCRV tokens will be taken out and shares will be burned by default. In addition, you can also restake by yourself when withdrawing, convert cvxCRV into CVX, and convert cvxCRV into ETH

The above is the basic analysis of the vault contract with relatively rich functions. Its essence is to stake assets to earn interest. Why is it designed like this? The main reason lies in the design of the cvxCrvStaking contract. The description of the income from staking cvxCRV is “By staking cvxCRV, you’ re earn the usual rewards from veCRV (3crv governance fee distribution from Curve + any airdrop), plus a share of 10% of the Convex LPs’ boosted CRV earnings, and CVX tokens on top of that.” The greater the number of tokens, the greater the benefits.

Safety

For ERC-4626 vaults, the main security issue is protection against inflation attacks.

When a user deposits tokens, according to the share calculation formula (shares = assets * totalSupply / totalAssets), the calculation result has a decimal point and is generally rounded down.

As you can see from the figure below, when a user deposits 500 tokens in assets, the amount of assets lost due to decimal rounding depends on the exchange rate (correspondence between per share and token assets). If the exchange rate is that of the orange curve, we get less than 1 share and lose 100%. However, if the exchange rate is that of the green curve and 5000 shares are obtained, the rounding loss is limited to a maximum of 0.02%.

Then if we focus on limiting losses to a maximum of 0.5%, we need to acquire at least 200 shares. The green rate requires only 20 tokens, but the orange rate requires 200,000 tokens.

Through several examples, it can be analyzed that the blue and green curves are safer than the yellow and orange curves, and are designed to be safer vaults.

Therefore, the main method of inflation attack is to use certain means to move the interest rate curve to the right, causing a small number of depositors to lose their share, thereby achieving the purpose of the attack.

Attack method

Inflation attacks are mainly through donations.

  1. The attacker first deposits 1 token into the vault contract. At this time, the shares he obtained are 1 and totalSupply is 1.
  2. The attacker sends 1e5 tokens directly to the vault contract. At this time, totalAssets has changed to 1e5 + 1, but totalSupply remains the same.
  3. When the victim deposits less than 1e5 tokens (x), the shares obtained are: x * 1 / (1e5 + 1), that is to say, as long as x is less than 1e5, according to the principle of rounding down the decimal, the shares that the victim obtained are 0. Even if the deposited tokens are greater than 1e5, since the attacker’s previous share was 100%, leading to significant reduction in the shares received by the victim.

Defend against attacks

There are three ways to defend against attacks:

  1. Set slippage. Earlier we introduced the concept of slippage, by setting a slippage tolerance range, if it does not receive the expected amount within a certain slippage tolerance range, the transaction will be reverted. This is the standard paradigm for dealing with slippage issues.
  2. Add enough initial assets to the vault to increase the cost of the attack. I have seen this method in the Blast staking contract. When initializing the staking, the contract requires the amount of ETH and USD to be no less than 1,000.
  3. Add “virtual liquidity” to the vault so that the price calculation behaves as if there are enough assets in the vault. The defense method is divided into 2 parts:
    • Precision offset between shares and assets.
    • Incorporate virtual shares and virtual assets into exchange rate calculations.

The specific implementation is to rewrite the _decimalsOffset() method of the standard library code provided by OpenZeppelin. This method does not require setting slippage or injecting sufficient initial funds. It is a very good way to resist inflation attacks.

05 Extension

As a relatively basic vault proposal, RC-4626 cannot meet all needs. Some proposals have also scaled it, such as ERC-7535 and EIP-7540.

ERC-7535

As mentioned earlier, ERC-4626 can only use ERC-20 as the underlying asset. This proposal mainly allows native assets to be used as underlying assets, such as ETH in the vault.

EIP-7540

This extension to ERC-4626 introduces support for asynchronous deposit and redemption processes (called “requests”). It includes new methods for starting and checking the status of these requests. Existing methods from ERC-4626, such as deposit, mint, withdraw, and redeem, are used to execute claimable requests. It is at the implementer’s discretion as to whether to add asynchronous processes for deposits, redemptions, or both.

Potential use cases:

  1. Asynchronous deposit and redemption process: By introducing the “request” concept, asynchronous deposit and redemption processes can be realized, providing a more flexible operation method.
  2. User experience improvement: The proposal emphasizes the importance of user experience and recommends the introduction of a standard discovery mechanism to help users and front-end applications better understand the duration and latency of asynchronous operations.
  3. Functional extension: EIP-7540 extends the functionality of ERC-4626 by adding new methods, making it possible to request deposits and redemptions asynchronously, and to view the status of these requests.

06 Summary

The above is the complete analysis of ERC-4626.

Due to historical reasons, many vaults currently in the market do not comply with ERC-4626 and continue to operate, such as dForce, but they cannot be applied more widely. Some vaults have already been upgraded to comply with ERC-4626, such as some contracts from Aladdin DAO (https://github.com/AladdinDAO/deployments/blob/main/deployments.mainnet.md).

In addition to earning interest through staking, vault applications can also lend out shares as collateral or stake them again to generate income. Furthermore, fundraising through vaults is also a good application scenario, as some of its basic functions can provide excellent support.

The essence of this proposal is to improve the integration efficiency between vaults and the DeFi ecosystem, and reduce development costs. The role of vaults themselves still has more room for exploration as the DeFi market grows.

Disclaimer:

  1. This article is reprinted from [LXDAO], All copyrights belong to the original author [Kahn]. If there are objections to this reprint, please contact the Gate Learn team, and they will handle it promptly.
  2. Liability Disclaimer: The views and opinions expressed in this article are solely those of the author and do not constitute any investment advice.
  3. Translations of the article into other languages are done by the Gate Learn team. Unless mentioned, copying, distributing, or plagiarizing the translated articles is prohibited.
Start Now
Sign up and get a
$100
Voucher!
Create Account