ERC4626.sol 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/extensions/ERC4626.sol)
  3. pragma solidity ^0.8.0;
  4. import "../ERC20.sol";
  5. import "../utils/SafeERC20.sol";
  6. import "../../../interfaces/IERC4626.sol";
  7. import "../../../utils/math/Math.sol";
  8. /**
  9. * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
  10. * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
  11. *
  12. * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
  13. * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
  14. * the ERC20 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 uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
  28. * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
  29. * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
  30. * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
  31. * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
  32. * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
  33. * expensive than it is profitable. More details about the underlying math can be found
  34. * 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. * _Available since v4.7._
  46. */
  47. abstract contract ERC4626 is ERC20, IERC4626 {
  48. using Math for uint256;
  49. IERC20 private immutable _asset;
  50. uint8 private immutable _underlyingDecimals;
  51. /**
  52. * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
  53. */
  54. constructor(IERC20 asset_) {
  55. (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
  56. _underlyingDecimals = success ? assetDecimals : 18;
  57. _asset = asset_;
  58. }
  59. /**
  60. * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
  61. */
  62. function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
  63. (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
  64. abi.encodeWithSelector(IERC20Metadata.decimals.selector)
  65. );
  66. if (success && encodedDecimals.length >= 32) {
  67. uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
  68. if (returnedDecimals <= type(uint8).max) {
  69. return (true, uint8(returnedDecimals));
  70. }
  71. }
  72. return (false, 0);
  73. }
  74. /**
  75. * @dev Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset
  76. * has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on
  77. * inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value.
  78. * See {IERC20Metadata-decimals}.
  79. */
  80. function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
  81. return _underlyingDecimals + _decimalsOffset();
  82. }
  83. /** @dev See {IERC4626-asset}. */
  84. function asset() public view virtual override returns (address) {
  85. return address(_asset);
  86. }
  87. /** @dev See {IERC4626-totalAssets}. */
  88. function totalAssets() public view virtual override returns (uint256) {
  89. return _asset.balanceOf(address(this));
  90. }
  91. /** @dev See {IERC4626-convertToShares}. */
  92. function convertToShares(uint256 assets) public view virtual override returns (uint256) {
  93. return _convertToShares(assets, Math.Rounding.Down);
  94. }
  95. /** @dev See {IERC4626-convertToAssets}. */
  96. function convertToAssets(uint256 shares) public view virtual override returns (uint256) {
  97. return _convertToAssets(shares, Math.Rounding.Down);
  98. }
  99. /** @dev See {IERC4626-maxDeposit}. */
  100. function maxDeposit(address) public view virtual override returns (uint256) {
  101. return type(uint256).max;
  102. }
  103. /** @dev See {IERC4626-maxMint}. */
  104. function maxMint(address) public view virtual override returns (uint256) {
  105. return type(uint256).max;
  106. }
  107. /** @dev See {IERC4626-maxWithdraw}. */
  108. function maxWithdraw(address owner) public view virtual override returns (uint256) {
  109. return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
  110. }
  111. /** @dev See {IERC4626-maxRedeem}. */
  112. function maxRedeem(address owner) public view virtual override returns (uint256) {
  113. return balanceOf(owner);
  114. }
  115. /** @dev See {IERC4626-previewDeposit}. */
  116. function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
  117. return _convertToShares(assets, Math.Rounding.Down);
  118. }
  119. /** @dev See {IERC4626-previewMint}. */
  120. function previewMint(uint256 shares) public view virtual override returns (uint256) {
  121. return _convertToAssets(shares, Math.Rounding.Up);
  122. }
  123. /** @dev See {IERC4626-previewWithdraw}. */
  124. function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
  125. return _convertToShares(assets, Math.Rounding.Up);
  126. }
  127. /** @dev See {IERC4626-previewRedeem}. */
  128. function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
  129. return _convertToAssets(shares, Math.Rounding.Down);
  130. }
  131. /** @dev See {IERC4626-deposit}. */
  132. function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
  133. require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");
  134. uint256 shares = previewDeposit(assets);
  135. _deposit(_msgSender(), receiver, assets, shares);
  136. return shares;
  137. }
  138. /** @dev See {IERC4626-mint}.
  139. *
  140. * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
  141. * In this case, the shares will be minted without requiring any assets to be deposited.
  142. */
  143. function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
  144. require(shares <= maxMint(receiver), "ERC4626: mint more than max");
  145. uint256 assets = previewMint(shares);
  146. _deposit(_msgSender(), receiver, assets, shares);
  147. return assets;
  148. }
  149. /** @dev See {IERC4626-withdraw}. */
  150. function withdraw(uint256 assets, address receiver, address owner) public virtual override returns (uint256) {
  151. require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");
  152. uint256 shares = previewWithdraw(assets);
  153. _withdraw(_msgSender(), receiver, owner, assets, shares);
  154. return shares;
  155. }
  156. /** @dev See {IERC4626-redeem}. */
  157. function redeem(uint256 shares, address receiver, address owner) public virtual override returns (uint256) {
  158. require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");
  159. uint256 assets = previewRedeem(shares);
  160. _withdraw(_msgSender(), receiver, owner, assets, shares);
  161. return assets;
  162. }
  163. /**
  164. * @dev Internal conversion function (from assets to shares) with support for rounding direction.
  165. *
  166. * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset
  167. * would represent an infinite amount of shares.
  168. */
  169. function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
  170. return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
  171. }
  172. /**
  173. * @dev Internal conversion function (from shares to assets) with support for rounding direction.
  174. */
  175. function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
  176. return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
  177. }
  178. /**
  179. * @dev Deposit/mint common workflow.
  180. */
  181. function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
  182. // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the
  183. // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
  184. // calls the vault, which is assumed not malicious.
  185. //
  186. // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
  187. // assets are transferred and before the shares are minted, which is a valid state.
  188. // slither-disable-next-line reentrancy-no-eth
  189. SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
  190. _mint(receiver, shares);
  191. emit Deposit(caller, receiver, assets, shares);
  192. }
  193. /**
  194. * @dev Withdraw/redeem common workflow.
  195. */
  196. function _withdraw(
  197. address caller,
  198. address receiver,
  199. address owner,
  200. uint256 assets,
  201. uint256 shares
  202. ) internal virtual {
  203. if (caller != owner) {
  204. _spendAllowance(owner, caller, shares);
  205. }
  206. // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
  207. // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
  208. // calls the vault, which is assumed not malicious.
  209. //
  210. // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
  211. // shares are burned and after the assets are transferred, which is a valid state.
  212. _burn(owner, shares);
  213. SafeERC20.safeTransfer(_asset, receiver, assets);
  214. emit Withdraw(caller, receiver, owner, assets, shares);
  215. }
  216. function _decimalsOffset() internal view virtual returns (uint8) {
  217. return 0;
  218. }
  219. }