ERC4626.sol 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of
  18. * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as
  19. * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
  20. *
  21. * _Available since v4.7._
  22. */
  23. abstract contract ERC4626 is ERC20, IERC4626 {
  24. using Math for uint256;
  25. IERC20 private immutable _asset;
  26. uint8 private immutable _decimals;
  27. /**
  28. * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
  29. */
  30. constructor(IERC20 asset_) {
  31. (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
  32. _decimals = success ? assetDecimals : super.decimals();
  33. _asset = asset_;
  34. }
  35. /**
  36. * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
  37. */
  38. function _tryGetAssetDecimals(IERC20 asset_) private returns (bool, uint8) {
  39. (bool success, bytes memory encodedDecimals) = address(asset_).call(
  40. abi.encodeWithSelector(IERC20Metadata.decimals.selector)
  41. );
  42. if (success && encodedDecimals.length >= 32) {
  43. uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
  44. if (returnedDecimals <= type(uint8).max) {
  45. return (true, uint8(returnedDecimals));
  46. }
  47. }
  48. return (false, 0);
  49. }
  50. /**
  51. * @dev Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset
  52. * has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on
  53. * inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value.
  54. * See {IERC20Metadata-decimals}.
  55. */
  56. function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
  57. return _decimals;
  58. }
  59. /** @dev See {IERC4626-asset}. */
  60. function asset() public view virtual override returns (address) {
  61. return address(_asset);
  62. }
  63. /** @dev See {IERC4626-totalAssets}. */
  64. function totalAssets() public view virtual override returns (uint256) {
  65. return _asset.balanceOf(address(this));
  66. }
  67. /** @dev See {IERC4626-convertToShares}. */
  68. function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) {
  69. return _convertToShares(assets, Math.Rounding.Down);
  70. }
  71. /** @dev See {IERC4626-convertToAssets}. */
  72. function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) {
  73. return _convertToAssets(shares, Math.Rounding.Down);
  74. }
  75. /** @dev See {IERC4626-maxDeposit}. */
  76. function maxDeposit(address) public view virtual override returns (uint256) {
  77. return _isVaultCollateralized() ? type(uint256).max : 0;
  78. }
  79. /** @dev See {IERC4626-maxMint}. */
  80. function maxMint(address) public view virtual override returns (uint256) {
  81. return type(uint256).max;
  82. }
  83. /** @dev See {IERC4626-maxWithdraw}. */
  84. function maxWithdraw(address owner) public view virtual override returns (uint256) {
  85. return _convertToAssets(balanceOf(owner), Math.Rounding.Down);
  86. }
  87. /** @dev See {IERC4626-maxRedeem}. */
  88. function maxRedeem(address owner) public view virtual override returns (uint256) {
  89. return balanceOf(owner);
  90. }
  91. /** @dev See {IERC4626-previewDeposit}. */
  92. function previewDeposit(uint256 assets) public view virtual override returns (uint256) {
  93. return _convertToShares(assets, Math.Rounding.Down);
  94. }
  95. /** @dev See {IERC4626-previewMint}. */
  96. function previewMint(uint256 shares) public view virtual override returns (uint256) {
  97. return _convertToAssets(shares, Math.Rounding.Up);
  98. }
  99. /** @dev See {IERC4626-previewWithdraw}. */
  100. function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {
  101. return _convertToShares(assets, Math.Rounding.Up);
  102. }
  103. /** @dev See {IERC4626-previewRedeem}. */
  104. function previewRedeem(uint256 shares) public view virtual override returns (uint256) {
  105. return _convertToAssets(shares, Math.Rounding.Down);
  106. }
  107. /** @dev See {IERC4626-deposit}. */
  108. function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {
  109. require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max");
  110. uint256 shares = previewDeposit(assets);
  111. _deposit(_msgSender(), receiver, assets, shares);
  112. return shares;
  113. }
  114. /** @dev See {IERC4626-mint}. */
  115. function mint(uint256 shares, address receiver) public virtual override returns (uint256) {
  116. require(shares <= maxMint(receiver), "ERC4626: mint more than max");
  117. uint256 assets = previewMint(shares);
  118. _deposit(_msgSender(), receiver, assets, shares);
  119. return assets;
  120. }
  121. /** @dev See {IERC4626-withdraw}. */
  122. function withdraw(
  123. uint256 assets,
  124. address receiver,
  125. address owner
  126. ) public virtual override returns (uint256) {
  127. require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max");
  128. uint256 shares = previewWithdraw(assets);
  129. _withdraw(_msgSender(), receiver, owner, assets, shares);
  130. return shares;
  131. }
  132. /** @dev See {IERC4626-redeem}. */
  133. function redeem(
  134. uint256 shares,
  135. address receiver,
  136. address owner
  137. ) public virtual override returns (uint256) {
  138. require(shares <= maxRedeem(owner), "ERC4626: redeem more than max");
  139. uint256 assets = previewRedeem(shares);
  140. _withdraw(_msgSender(), receiver, owner, assets, shares);
  141. return assets;
  142. }
  143. /**
  144. * @dev Internal conversion function (from assets to shares) with support for rounding direction.
  145. *
  146. * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset
  147. * would represent an infinite amount of shares.
  148. */
  149. function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256 shares) {
  150. uint256 supply = totalSupply();
  151. return
  152. (assets == 0 || supply == 0)
  153. ? _initialConvertToShares(assets, rounding)
  154. : assets.mulDiv(supply, totalAssets(), rounding);
  155. }
  156. /**
  157. * @dev Internal conversion function (from assets to shares) to apply when the vault is empty.
  158. *
  159. * NOTE: Make sure to keep this function consistent with {_initialConvertToAssets} when overriding it.
  160. */
  161. function _initialConvertToShares(
  162. uint256 assets,
  163. Math.Rounding /*rounding*/
  164. ) internal view virtual returns (uint256 shares) {
  165. return assets;
  166. }
  167. /**
  168. * @dev Internal conversion function (from shares to assets) with support for rounding direction.
  169. */
  170. function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256 assets) {
  171. uint256 supply = totalSupply();
  172. return
  173. (supply == 0) ? _initialConvertToAssets(shares, rounding) : shares.mulDiv(totalAssets(), supply, rounding);
  174. }
  175. /**
  176. * @dev Internal conversion function (from shares to assets) to apply when the vault is empty.
  177. *
  178. * NOTE: Make sure to keep this function consistent with {_initialConvertToShares} when overriding it.
  179. */
  180. function _initialConvertToAssets(
  181. uint256 shares,
  182. Math.Rounding /*rounding*/
  183. ) internal view virtual returns (uint256 assets) {
  184. return shares;
  185. }
  186. /**
  187. * @dev Deposit/mint common workflow.
  188. */
  189. function _deposit(
  190. address caller,
  191. address receiver,
  192. uint256 assets,
  193. uint256 shares
  194. ) internal virtual {
  195. // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the
  196. // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
  197. // calls the vault, which is assumed not malicious.
  198. //
  199. // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
  200. // assets are transferred and before the shares are minted, which is a valid state.
  201. // slither-disable-next-line reentrancy-no-eth
  202. SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
  203. _mint(receiver, shares);
  204. emit Deposit(caller, receiver, assets, shares);
  205. }
  206. /**
  207. * @dev Withdraw/redeem common workflow.
  208. */
  209. function _withdraw(
  210. address caller,
  211. address receiver,
  212. address owner,
  213. uint256 assets,
  214. uint256 shares
  215. ) internal virtual {
  216. if (caller != owner) {
  217. _spendAllowance(owner, caller, shares);
  218. }
  219. // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
  220. // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
  221. // calls the vault, which is assumed not malicious.
  222. //
  223. // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
  224. // shares are burned and after the assets are transferred, which is a valid state.
  225. _burn(owner, shares);
  226. SafeERC20.safeTransfer(_asset, receiver, assets);
  227. emit Withdraw(caller, receiver, owner, assets, shares);
  228. }
  229. function _isVaultCollateralized() private view returns (bool) {
  230. return totalAssets() > 0 || totalSupply() == 0;
  231. }
  232. }