ERC4626.sol 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
  3. pragma solidity ^0.8.20;
  4. import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
  5. import {SafeERC20} from "../utils/SafeERC20.sol";
  6. import {IERC4626} from "../../../interfaces/IERC4626.sol";
  7. import {Math} from "../../../utils/math/Math.sol";
  8. /**
  9. * @dev Implementation of the ERC-4626 "Tokenized Vault Standard" as defined in
  10. * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
  11. *
  12. * This extension allows the minting and burning of "shares" (represented using the ERC-20 inheritance) in exchange for
  13. * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
  14. * the ERC-20 standard. Any additional extensions included along it would affect the "shares" token represented by this
  15. * contract and not the "assets" token which is an independent contract.
  16. *
  17. * [CAUTION]
  18. * ====
  19. * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
  20. * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
  21. * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
  22. * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
  23. * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
  24. * verifying the amount received is as expected, using a wrapper that performs these checks such as
  25. * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
  26. *
  27. * Since v4.9, this implementation introduces configurable virtual assets and shares to help developers mitigate that risk.
  28. * The `_decimalsOffset()` corresponds to an offset in the decimal representation between the underlying asset's decimals
  29. * and the vault decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which
  30. * itself determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default
  31. * offset (0) makes it non-profitable even if an attacker is able to capture value from multiple user deposits, as a result
  32. * of the value being captured by the virtual shares (out of the attacker's donation) matching the attacker's expected gains.
  33. * With a larger offset, the attack becomes orders of magnitude more expensive than it is profitable. More details about the
  34. * underlying math can be found xref:erc4626.adoc#inflation-attack[here].
  35. *
  36. * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
  37. * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
  38. * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
  39. * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
  40. * `_convertToShares` and `_convertToAssets` functions.
  41. *
  42. * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
  43. * ====
  44. */
  45. abstract contract ERC4626 is ERC20, IERC4626 {
  46. using Math for uint256;
  47. IERC20 private immutable _asset;
  48. uint8 private immutable _underlyingDecimals;
  49. /**
  50. * @dev Attempted to deposit more assets than the max amount for `receiver`.
  51. */
  52. error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
  53. /**
  54. * @dev Attempted to mint more shares than the max amount for `receiver`.
  55. */
  56. error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
  57. /**
  58. * @dev Attempted to withdraw more assets than the max amount for `receiver`.
  59. */
  60. error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
  61. /**
  62. * @dev Attempted to redeem more shares than the max amount for `receiver`.
  63. */
  64. error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
  65. /**
  66. * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC-20 or ERC-777).
  67. */
  68. constructor(IERC20 asset_) {
  69. (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
  70. _underlyingDecimals = success ? assetDecimals : 18;
  71. _asset = asset_;
  72. }
  73. /**
  74. * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
  75. */
  76. function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool ok, uint8 assetDecimals) {
  77. (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
  78. abi.encodeCall(IERC20Metadata.decimals, ())
  79. );
  80. if (success && encodedDecimals.length >= 32) {
  81. uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
  82. if (returnedDecimals <= type(uint8).max) {
  83. return (true, uint8(returnedDecimals));
  84. }
  85. }
  86. return (false, 0);
  87. }
  88. /**
  89. * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
  90. * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
  91. * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
  92. *
  93. * See {IERC20Metadata-decimals}.
  94. */
  95. function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
  96. return _underlyingDecimals + _decimalsOffset();
  97. }
  98. /** @dev See {IERC4626-asset}. */
  99. function asset() public view virtual returns (address) {
  100. return address(_asset);
  101. }
  102. /** @dev See {IERC4626-totalAssets}. */
  103. function totalAssets() public view virtual returns (uint256) {
  104. return _asset.balanceOf(address(this));
  105. }
  106. /** @dev See {IERC4626-convertToShares}. */
  107. function convertToShares(uint256 assets) public view virtual returns (uint256) {
  108. return _convertToShares(assets, Math.Rounding.Floor);
  109. }
  110. /** @dev See {IERC4626-convertToAssets}. */
  111. function convertToAssets(uint256 shares) public view virtual returns (uint256) {
  112. return _convertToAssets(shares, Math.Rounding.Floor);
  113. }
  114. /** @dev See {IERC4626-maxDeposit}. */
  115. function maxDeposit(address) public view virtual returns (uint256) {
  116. return type(uint256).max;
  117. }
  118. /** @dev See {IERC4626-maxMint}. */
  119. function maxMint(address) public view virtual returns (uint256) {
  120. return type(uint256).max;
  121. }
  122. /** @dev See {IERC4626-maxWithdraw}. */
  123. function maxWithdraw(address owner) public view virtual returns (uint256) {
  124. return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
  125. }
  126. /** @dev See {IERC4626-maxRedeem}. */
  127. function maxRedeem(address owner) public view virtual returns (uint256) {
  128. return balanceOf(owner);
  129. }
  130. /** @dev See {IERC4626-previewDeposit}. */
  131. function previewDeposit(uint256 assets) public view virtual returns (uint256) {
  132. return _convertToShares(assets, Math.Rounding.Floor);
  133. }
  134. /** @dev See {IERC4626-previewMint}. */
  135. function previewMint(uint256 shares) public view virtual returns (uint256) {
  136. return _convertToAssets(shares, Math.Rounding.Ceil);
  137. }
  138. /** @dev See {IERC4626-previewWithdraw}. */
  139. function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
  140. return _convertToShares(assets, Math.Rounding.Ceil);
  141. }
  142. /** @dev See {IERC4626-previewRedeem}. */
  143. function previewRedeem(uint256 shares) public view virtual returns (uint256) {
  144. return _convertToAssets(shares, Math.Rounding.Floor);
  145. }
  146. /** @dev See {IERC4626-deposit}. */
  147. function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
  148. uint256 maxAssets = maxDeposit(receiver);
  149. if (assets > maxAssets) {
  150. revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
  151. }
  152. uint256 shares = previewDeposit(assets);
  153. _deposit(_msgSender(), receiver, assets, shares);
  154. return shares;
  155. }
  156. /** @dev See {IERC4626-mint}. */
  157. function mint(uint256 shares, address receiver) public virtual returns (uint256) {
  158. uint256 maxShares = maxMint(receiver);
  159. if (shares > maxShares) {
  160. revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
  161. }
  162. uint256 assets = previewMint(shares);
  163. _deposit(_msgSender(), receiver, assets, shares);
  164. return assets;
  165. }
  166. /** @dev See {IERC4626-withdraw}. */
  167. function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
  168. uint256 maxAssets = maxWithdraw(owner);
  169. if (assets > maxAssets) {
  170. revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
  171. }
  172. uint256 shares = previewWithdraw(assets);
  173. _withdraw(_msgSender(), receiver, owner, assets, shares);
  174. return shares;
  175. }
  176. /** @dev See {IERC4626-redeem}. */
  177. function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
  178. uint256 maxShares = maxRedeem(owner);
  179. if (shares > maxShares) {
  180. revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
  181. }
  182. uint256 assets = previewRedeem(shares);
  183. _withdraw(_msgSender(), receiver, owner, assets, shares);
  184. return assets;
  185. }
  186. /**
  187. * @dev Internal conversion function (from assets to shares) with support for rounding direction.
  188. */
  189. function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
  190. return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
  191. }
  192. /**
  193. * @dev Internal conversion function (from shares to assets) with support for rounding direction.
  194. */
  195. function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
  196. return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
  197. }
  198. /**
  199. * @dev Deposit/mint common workflow.
  200. */
  201. function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
  202. // If _asset is ERC-777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
  203. // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
  204. // calls the vault, which is assumed not malicious.
  205. //
  206. // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
  207. // assets are transferred and before the shares are minted, which is a valid state.
  208. // slither-disable-next-line reentrancy-no-eth
  209. SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
  210. _mint(receiver, shares);
  211. emit Deposit(caller, receiver, assets, shares);
  212. }
  213. /**
  214. * @dev Withdraw/redeem common workflow.
  215. */
  216. function _withdraw(
  217. address caller,
  218. address receiver,
  219. address owner,
  220. uint256 assets,
  221. uint256 shares
  222. ) internal virtual {
  223. if (caller != owner) {
  224. _spendAllowance(owner, caller, shares);
  225. }
  226. // If _asset is ERC-777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
  227. // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
  228. // calls the vault, which is assumed not malicious.
  229. //
  230. // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
  231. // shares are burned and after the assets are transferred, which is a valid state.
  232. _burn(owner, shares);
  233. SafeERC20.safeTransfer(_asset, receiver, assets);
  234. emit Withdraw(caller, receiver, owner, assets, shares);
  235. }
  236. function _decimalsOffset() internal view virtual returns (uint8) {
  237. return 0;
  238. }
  239. }