ETH Price: $2,053.09 (-1.64%)
Gas: 0.05 Gwei

Transaction Decoder

Block:
24677225 at Mar-17-2026 12:29:35 PM +UTC
Transaction Fee:
0.000169395721252125 ETH $0.35
Gas Used:
1,295,275 Gas / 0.130779735 Gwei

Emitted Events:

702 MetaMorphoV1_1.UpdateLastTotalAssets( updatedTotalAssets=4555509346005 )
703 MetaMorphoV1_1.UpdateLostAssets( newLostAssets=0 )
704 MetaMorphoV1_1.Transfer( from=0x0000000000000000000000000000000000000000, to=0xe5e2Baf96198c56380dDD5E992D7d1ADa0e989c0, value=1119599821260840258 )
705 MetaMorphoV1_1.AccrueInterest( newTotalAssets=4555509346005, feeShares=1119599821260840258 )
706 MetaMorphoV1_1.UpdateLastTotalAssets( updatedTotalAssets=2669236068568 )
707 AdaptiveCurveIrm.BorrowRateUpdate( id=64D65C9A2D91C36D56FBC42D69E979335320169B3DF63BF92789E2C8883FCC64, avgBorrowRate=1532271184, rateAtTarget=1019197027 )
708 Morpho.AccrueInterest( id=64D65C9A2D91C36D56FBC42D69E979335320169B3DF63BF92789E2C8883FCC64, prevBorrowRate=1532271184, interest=114789412, feeShares=0 )
709 Morpho.Withdraw( id=64D65C9A2D91C36D56FBC42D69E979335320169B3DF63BF92789E2C8883FCC64, caller=MetaMorphoV1_1, onBehalf=MetaMorphoV1_1, receiver=MetaMorphoV1_1, assets=1387681675875, shares=1293723166138595589 )
710 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb, 0x00000000000000000000000068aea7b82df6ccdf76235d46445ed83f85f845a3, 000000000000000000000000000000000000000000000000000001431845fa63 )
711 AdaptiveCurveIrm.BorrowRateUpdate( id=B323495F7E4148BE5643A4EA4A8221EEF163E4BCCFDEDC2A6F4696BAACBC86CC, avgBorrowRate=1532503156, rateAtTarget=1019256523 )
712 Morpho.AccrueInterest( id=B323495F7E4148BE5643A4EA4A8221EEF163E4BCCFDEDC2A6F4696BAACBC86CC, prevBorrowRate=1532503156, interest=158026742, feeShares=0 )
713 Morpho.Withdraw( id=B323495F7E4148BE5643A4EA4A8221EEF163E4BCCFDEDC2A6F4696BAACBC86CC, caller=MetaMorphoV1_1, onBehalf=MetaMorphoV1_1, receiver=MetaMorphoV1_1, assets=498591601562, shares=443947536124891620 )
714 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000bbbbbbbbbb9cc5e90e3b3af64bdaf62c37eeffcb, 0x00000000000000000000000068aea7b82df6ccdf76235d46445ed83f85f845a3, 000000000000000000000000000000000000000000000000000000741660139a )
715 MetaMorphoV1_1.Transfer( from=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, to=0x0000000000000000000000000000000000000000, value=1829923873529615508240412 )
716 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x00000000000000000000000068aea7b82df6ccdf76235d46445ed83f85f845a3, 0x000000000000000000000000888239ffa9a0613f9142c808aa9f7d1948a14f75, 000000000000000000000000000000000000000000000000000001b72ea60dfd )
717 MetaMorphoV1_1.Withdraw( sender=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, receiver=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, owner=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, assets=1886273277437, shares=1829923873529615508240412 )
718 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000be53a109b494e5c9f97b9cd39fe969be68bf6204, 0x0000000000000000000000000000000000000000000000000000000000000000, 0000000000000000000000000000000000000000000000000000009ec2bd5c33 )
719 FiatTokenProxy.0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef( 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, 0x000000000000000000000000888239ffa9a0613f9142c808aa9f7d1948a14f75, 0x000000000000000000000000be53a109b494e5c9f97b9cd39fe969be68bf6204, 000000000000000000000000000000000000000000000000000001b72ea60dfd )
720 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db( 0xfbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db, 0x000000000000000000000000be53a109b494e5c9f97b9cd39fe969be68bf6204, 0x000000000000000000000000be53a109b494e5c9f97b9cd39fe969be68bf6204, 0x000000000000000000000000be53a109b494e5c9f97b9cd39fe969be68bf6204, 000000000000000000000000000000000000000000000000000001b72ea60dfd, 0000000000000000000000000000000000000000000000000000009ec2bd5c33 )
721 Yearn V3 Vault.DebtUpdated( strategy=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, current_debt=3769444131719, new_debt=1883170854282 )

Account State Difference:

  Address   Before After State Difference Code
0x1e9eB053...5356b8671
0x28313239...29eE17961
0.0258619518099949 Eth
Nonce: 24935
0.025692556088742775 Eth
Nonce: 24936
0.000169395721252125
(quasarbuilder)
8.004760268031040573 Eth8.004760268032335848 Eth0.000000000001295275
0x68Aea7b8...f85F845A3
0x870aC11D...F79Ba00BC
(Morpho: Adaptive Curve Irm)
0x888239Ff...948a14f75
0xA0b86991...E3606eB48
0xBBBBBbbB...C37EEFFCb
(Morpho: Morpho)
0xBe53A109...E68BF6204

Execution Trace

yHaaSRelayer.forwardCall( debtAllocatorAddress=0x1e9eB053228B1156831759401dE0E115356b8671, data=0xDA5F3286000000000000000000000000BE53A109B494E5C9F97B9CD39FE969BE68BF6204000000000000000000000000888239FFA9A0613F9142C808AA9F7D1948A14F75000000000000000000000000000000000000000000000000000001B675BAD58B ) => ( success=True )
  • DebtAllocator.update_debt( _vault=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204, _strategy=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, _targetDebt=1883170854283 )
    • DebtAllocator.update_debt( _vault=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204, _strategy=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, _targetDebt=1883170854283 )
      • V3.update_debt( strategy=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, target_debt=1883170854283, max_loss=1 ) => ( 1883170854282 )
        • V3.update_debt( strategy=0x888239Ffa9a0613F9142C808aA9F7d1948a14f75, target_debt=1883170854283, max_loss=1 ) => ( 1883170854282 )
          • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.d905777e( )
            • TokenizedStrategy.maxRedeem( owner=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204 ) => ( 1362622619969 )
            • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.07a2d13a( )
              • TokenizedStrategy.convertToAssets( shares=1362622619969 ) => ( 3769444338774 )
              • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.70a08231( )
                • TokenizedStrategy.balanceOf( account=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204 ) => ( 1362622619969 )
                • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.07a2d13a( )
                  • TokenizedStrategy.convertToAssets( shares=1362622619969 ) => ( 3769444338774 )
                  • FiatTokenProxy.70a08231( )
                    • FiatTokenV2_2.balanceOf( account=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204 ) => ( 67011824 )
                    • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.0a28a477( )
                      • TokenizedStrategy.previewWithdraw( assets=1886273277436 ) => ( 681872022579 )
                      • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.70a08231( )
                        • TokenizedStrategy.balanceOf( account=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204 ) => ( 1362622619969 )
                        • 0x888239ffa9a0613f9142c808aa9f7d1948a14f75.ba087652( )
                          • TokenizedStrategy.redeem( shares=681872022579, receiver=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204, owner=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204 ) => ( 1886273277437 )
                          • FiatTokenProxy.70a08231( )
                            • FiatTokenV2_2.balanceOf( account=0xBe53A109B494E5c9f97b9Cd39Fe969BE68BF6204 ) => ( 1886340289261 )
                              File 1 of 11: yHaaSRelayer
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.18;
                              
                              contract yHaaSRelayer {
                                  address public owner;
                                  address public governance;
                              
                                  mapping(address => bool) public keepers;
                              
                                  constructor() {
                                      owner = msg.sender;
                                      governance = msg.sender;
                                  }
                              
                                  function harvestStrategy(address _strategyAddress) public onlyKeepers returns (uint256 profit, uint256 loss) {
                                      (profit, loss) = StrategyAPI(_strategyAddress).report();
                                  }
                              
                                  function tendStrategy(address _strategyAddress) public onlyKeepers {
                                      StrategyAPI(_strategyAddress).tend();
                                  }
                              
                                  function processReport(address _vaultAddress, address _strategyAddress) public onlyKeepers returns (uint256 gain, uint256 loss) {
                                      (gain, loss) = VaultAPI(_vaultAddress).process_report(_strategyAddress);
                                  }
                              
                                  function forwardCall(address debtAllocatorAddress, bytes memory data) public onlyKeepers returns (bool success) {
                                      (success, ) = debtAllocatorAddress.call(data);
                                  }
                              
                                  function setKeeper(address _address, bool _allowed) external virtual onlyAuthorized {
                                      keepers[_address] = _allowed;
                                  }
                              
                                  /**
                                  @notice Changes the `owner` address.
                                  @param _owner The new address to assign as `owner`.
                                  */
                                  function setOwner(address _owner) external onlyAuthorized {
                                      require(_owner != address(0));
                                      owner = _owner;
                                  }
                              
                                  /**
                                  @notice Changes the `governance` address.
                                  @param _governance The new address to assign as `governance`.
                                  */
                                  function setGovernance(address _governance) external onlyGovernance {
                                      require(_governance != address(0));
                                      governance = _governance;
                                  }
                              
                                  modifier onlyKeepers() {
                                      require(msg.sender == owner || keepers[msg.sender] == true || msg.sender == governance, "!keeper yHaaSProxy");
                                      _;
                                  }
                              
                                  modifier onlyAuthorized() {
                                      require(msg.sender == owner || msg.sender == governance, "!authorized");
                                      _;
                                  }
                              
                                  modifier onlyGovernance() {
                                      require(msg.sender == governance, "!governance");
                                      _;
                                  }
                              } 
                              
                              interface StrategyAPI {
                                  function tend() external;
                                  function report() external returns (uint256 _profit, uint256 _loss);
                              }
                              
                              interface VaultAPI {
                                  function process_report(address) external returns (uint256 _gain, uint256 _loss);
                              }

                              File 2 of 11: MetaMorphoV1_1
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity 0.8.26;
                              import {
                                  MarketConfig,
                                  PendingUint192,
                                  PendingAddress,
                                  MarketAllocation,
                                  IMetaMorphoV1_1Base,
                                  IMetaMorphoV1_1StaticTyping
                              } from "./interfaces/IMetaMorphoV1_1.sol";
                              import {Id, MarketParams, Market, IMorpho} from "../lib/morpho-blue/src/interfaces/IMorpho.sol";
                              import {PendingUint192, PendingAddress, PendingLib} from "./libraries/PendingLib.sol";
                              import {ConstantsLib} from "./libraries/ConstantsLib.sol";
                              import {ErrorsLib} from "./libraries/ErrorsLib.sol";
                              import {EventsLib} from "./libraries/EventsLib.sol";
                              import {WAD} from "../lib/morpho-blue/src/libraries/MathLib.sol";
                              import {UtilsLib} from "../lib/morpho-blue/src/libraries/UtilsLib.sol";
                              import {SafeCast} from "../lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol";
                              import {SharesMathLib} from "../lib/morpho-blue/src/libraries/SharesMathLib.sol";
                              import {MorphoLib} from "../lib/morpho-blue/src/libraries/periphery/MorphoLib.sol";
                              import {MarketParamsLib} from "../lib/morpho-blue/src/libraries/MarketParamsLib.sol";
                              import {IERC20Metadata} from "../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol";
                              import {MorphoBalancesLib} from "../lib/morpho-blue/src/libraries/periphery/MorphoBalancesLib.sol";
                              import {Multicall} from "../lib/openzeppelin-contracts/contracts/utils/Multicall.sol";
                              import {Ownable2Step, Ownable} from "../lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol";
                              import {ERC20Permit} from "../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC20Permit.sol";
                              import {
                                  IERC20,
                                  IERC4626,
                                  ERC20,
                                  ERC4626,
                                  Math,
                                  SafeERC20
                              } from "../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/ERC4626.sol";
                              /// @title MetaMorpho
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice ERC4626 compliant vault allowing users to deposit assets to Morpho.
                              contract MetaMorphoV1_1 is ERC4626, ERC20Permit, Ownable2Step, Multicall, IMetaMorphoV1_1StaticTyping {
                                  using Math for uint256;
                                  using UtilsLib for uint256;
                                  using SafeCast for uint256;
                                  using SafeERC20 for IERC20;
                                  using MorphoLib for IMorpho;
                                  using SharesMathLib for uint256;
                                  using MorphoBalancesLib for IMorpho;
                                  using MarketParamsLib for MarketParams;
                                  using PendingLib for MarketConfig;
                                  using PendingLib for PendingUint192;
                                  using PendingLib for PendingAddress;
                                  /* IMMUTABLES */
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  IMorpho public immutable MORPHO;
                                  /// @notice OpenZeppelin decimals offset used by the ERC4626 implementation.
                                  /// @dev Calculated to be max(0, 18 - underlyingDecimals) at construction, so the initial conversion rate maximizes
                                  /// precision between shares and assets.
                                  uint8 public immutable DECIMALS_OFFSET;
                                  /* STORAGE */
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  address public curator;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  mapping(address => bool) public isAllocator;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  address public guardian;
                                  /// @inheritdoc IMetaMorphoV1_1StaticTyping
                                  mapping(Id => MarketConfig) public config;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  uint256 public timelock;
                                  /// @inheritdoc IMetaMorphoV1_1StaticTyping
                                  PendingAddress public pendingGuardian;
                                  /// @inheritdoc IMetaMorphoV1_1StaticTyping
                                  mapping(Id => PendingUint192) public pendingCap;
                                  /// @inheritdoc IMetaMorphoV1_1StaticTyping
                                  PendingUint192 public pendingTimelock;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  uint96 public fee;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  address public feeRecipient;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  address public skimRecipient;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  Id[] public supplyQueue;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  Id[] public withdrawQueue;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  uint256 public lastTotalAssets;
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  uint256 public lostAssets;
                                  /// @dev "Overrides" the ERC20's storage variable to be able to modify it.
                                  string private _name;
                                  /// @dev "Overrides" the ERC20's storage variable to be able to modify it.
                                  string private _symbol;
                                  /* CONSTRUCTOR */
                                  /// @dev Initializes the contract.
                                  /// @param owner The owner of the contract.
                                  /// @param morpho The address of the Morpho contract.
                                  /// @param initialTimelock The initial timelock.
                                  /// @param _asset The address of the underlying asset.
                                  /// @param __name The name of the vault.
                                  /// @param __symbol The symbol of the vault.
                                  /// @dev We pass "" as name and symbol to the ERC20 because these are overriden in this contract.
                                  /// This means that the contract deviates slightly from the ERC2612 standard.
                                  constructor(
                                      address owner,
                                      address morpho,
                                      uint256 initialTimelock,
                                      address _asset,
                                      string memory __name,
                                      string memory __symbol
                                  ) ERC4626(IERC20(_asset)) ERC20Permit("") ERC20("", "") Ownable(owner) {
                                      if (morpho == address(0)) revert ErrorsLib.ZeroAddress();
                                      if (initialTimelock != 0) _checkTimelockBounds(initialTimelock);
                                      _setTimelock(initialTimelock);
                                      _name = __name;
                                      emit EventsLib.SetName(__name);
                                      _symbol = __symbol;
                                      emit EventsLib.SetSymbol(__symbol);
                                      MORPHO = IMorpho(morpho);
                                      DECIMALS_OFFSET = uint8(uint256(18).zeroFloorSub(IERC20Metadata(_asset).decimals()));
                                      IERC20(_asset).forceApprove(morpho, type(uint256).max);
                                  }
                                  /* MODIFIERS */
                                  /// @dev Reverts if the caller doesn't have the curator role.
                                  modifier onlyCuratorRole() {
                                      address sender = _msgSender();
                                      if (sender != curator && sender != owner()) revert ErrorsLib.NotCuratorRole();
                                      _;
                                  }
                                  /// @dev Reverts if the caller doesn't have the allocator role.
                                  modifier onlyAllocatorRole() {
                                      address sender = _msgSender();
                                      if (!isAllocator[sender] && sender != curator && sender != owner()) {
                                          revert ErrorsLib.NotAllocatorRole();
                                      }
                                      _;
                                  }
                                  /// @dev Reverts if the caller doesn't have the guardian role.
                                  modifier onlyGuardianRole() {
                                      if (_msgSender() != owner() && _msgSender() != guardian) revert ErrorsLib.NotGuardianRole();
                                      _;
                                  }
                                  /// @dev Reverts if the caller doesn't have the curator nor the guardian role.
                                  modifier onlyCuratorOrGuardianRole() {
                                      if (_msgSender() != guardian && _msgSender() != curator && _msgSender() != owner()) {
                                          revert ErrorsLib.NotCuratorNorGuardianRole();
                                      }
                                      _;
                                  }
                                  /// @dev Makes sure conditions are met to accept a pending value.
                                  /// @dev Reverts if:
                                  /// - there's no pending value;
                                  /// - the timelock has not elapsed since the pending value has been submitted.
                                  modifier afterTimelock(uint256 validAt) {
                                      if (validAt == 0) revert ErrorsLib.NoPendingValue();
                                      if (block.timestamp < validAt) revert ErrorsLib.TimelockNotElapsed();
                                      _;
                                  }
                                  /* ONLY OWNER FUNCTIONS */
                                  function setName(string memory newName) external onlyOwner {
                                      _name = newName;
                                      emit EventsLib.SetName(newName);
                                  }
                                  function setSymbol(string memory newSymbol) external onlyOwner {
                                      _symbol = newSymbol;
                                      emit EventsLib.SetSymbol(newSymbol);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function setCurator(address newCurator) external onlyOwner {
                                      if (newCurator == curator) revert ErrorsLib.AlreadySet();
                                      curator = newCurator;
                                      emit EventsLib.SetCurator(newCurator);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function setIsAllocator(address newAllocator, bool newIsAllocator) external onlyOwner {
                                      if (isAllocator[newAllocator] == newIsAllocator) revert ErrorsLib.AlreadySet();
                                      isAllocator[newAllocator] = newIsAllocator;
                                      emit EventsLib.SetIsAllocator(newAllocator, newIsAllocator);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function setSkimRecipient(address newSkimRecipient) external onlyOwner {
                                      if (newSkimRecipient == skimRecipient) revert ErrorsLib.AlreadySet();
                                      skimRecipient = newSkimRecipient;
                                      emit EventsLib.SetSkimRecipient(newSkimRecipient);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function submitTimelock(uint256 newTimelock) external onlyOwner {
                                      if (newTimelock == timelock) revert ErrorsLib.AlreadySet();
                                      if (pendingTimelock.validAt != 0) revert ErrorsLib.AlreadyPending();
                                      _checkTimelockBounds(newTimelock);
                                      if (newTimelock > timelock) {
                                          _setTimelock(newTimelock);
                                      } else {
                                          // Safe "unchecked" cast because newTimelock <= MAX_TIMELOCK.
                                          pendingTimelock.update(uint184(newTimelock), timelock);
                                          emit EventsLib.SubmitTimelock(newTimelock);
                                      }
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function setFee(uint256 newFee) external onlyOwner {
                                      if (newFee == fee) revert ErrorsLib.AlreadySet();
                                      if (newFee > ConstantsLib.MAX_FEE) revert ErrorsLib.MaxFeeExceeded();
                                      if (newFee != 0 && feeRecipient == address(0)) revert ErrorsLib.ZeroFeeRecipient();
                                      // Accrue interest and fee using the previous fee set before changing it.
                                      _accrueInterest();
                                      // Safe "unchecked" cast because newFee <= MAX_FEE.
                                      fee = uint96(newFee);
                                      emit EventsLib.SetFee(_msgSender(), fee);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function setFeeRecipient(address newFeeRecipient) external onlyOwner {
                                      if (newFeeRecipient == feeRecipient) revert ErrorsLib.AlreadySet();
                                      if (newFeeRecipient == address(0) && fee != 0) revert ErrorsLib.ZeroFeeRecipient();
                                      // Accrue interest and fee to the previous fee recipient set before changing it.
                                      _accrueInterest();
                                      feeRecipient = newFeeRecipient;
                                      emit EventsLib.SetFeeRecipient(newFeeRecipient);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function submitGuardian(address newGuardian) external onlyOwner {
                                      if (newGuardian == guardian) revert ErrorsLib.AlreadySet();
                                      if (pendingGuardian.validAt != 0) revert ErrorsLib.AlreadyPending();
                                      if (guardian == address(0)) {
                                          _setGuardian(newGuardian);
                                      } else {
                                          pendingGuardian.update(newGuardian, timelock);
                                          emit EventsLib.SubmitGuardian(newGuardian);
                                      }
                                  }
                                  /* ONLY CURATOR FUNCTIONS */
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function submitCap(MarketParams memory marketParams, uint256 newSupplyCap) external onlyCuratorRole {
                                      Id id = marketParams.id();
                                      if (marketParams.loanToken != asset()) revert ErrorsLib.InconsistentAsset(id);
                                      if (MORPHO.lastUpdate(id) == 0) revert ErrorsLib.MarketNotCreated();
                                      if (pendingCap[id].validAt != 0) revert ErrorsLib.AlreadyPending();
                                      if (config[id].removableAt != 0) revert ErrorsLib.PendingRemoval();
                                      uint256 supplyCap = config[id].cap;
                                      if (newSupplyCap == supplyCap) revert ErrorsLib.AlreadySet();
                                      if (newSupplyCap < supplyCap) {
                                          _setCap(marketParams, id, newSupplyCap.toUint184());
                                      } else {
                                          pendingCap[id].update(newSupplyCap.toUint184(), timelock);
                                          emit EventsLib.SubmitCap(_msgSender(), id, newSupplyCap);
                                      }
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function submitMarketRemoval(MarketParams memory marketParams) external onlyCuratorRole {
                                      Id id = marketParams.id();
                                      if (config[id].removableAt != 0) revert ErrorsLib.AlreadyPending();
                                      if (config[id].cap != 0) revert ErrorsLib.NonZeroCap();
                                      if (!config[id].enabled) revert ErrorsLib.MarketNotEnabled(id);
                                      if (pendingCap[id].validAt != 0) revert ErrorsLib.PendingCap(id);
                                      // Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
                                      config[id].removableAt = uint64(block.timestamp + timelock);
                                      emit EventsLib.SubmitMarketRemoval(_msgSender(), id);
                                  }
                                  /* ONLY ALLOCATOR FUNCTIONS */
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function setSupplyQueue(Id[] calldata newSupplyQueue) external onlyAllocatorRole {
                                      uint256 length = newSupplyQueue.length;
                                      if (length > ConstantsLib.MAX_QUEUE_LENGTH) revert ErrorsLib.MaxQueueLengthExceeded();
                                      for (uint256 i; i < length; ++i) {
                                          if (config[newSupplyQueue[i]].cap == 0) revert ErrorsLib.UnauthorizedMarket(newSupplyQueue[i]);
                                      }
                                      supplyQueue = newSupplyQueue;
                                      emit EventsLib.SetSupplyQueue(_msgSender(), newSupplyQueue);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function updateWithdrawQueue(uint256[] calldata indexes) external onlyAllocatorRole {
                                      uint256 newLength = indexes.length;
                                      uint256 currLength = withdrawQueue.length;
                                      bool[] memory seen = new bool[](currLength);
                                      Id[] memory newWithdrawQueue = new Id[](newLength);
                                      for (uint256 i; i < newLength; ++i) {
                                          uint256 prevIndex = indexes[i];
                                          // If prevIndex >= currLength, it will revert with native "Index out of bounds".
                                          Id id = withdrawQueue[prevIndex];
                                          if (seen[prevIndex]) revert ErrorsLib.DuplicateMarket(id);
                                          seen[prevIndex] = true;
                                          newWithdrawQueue[i] = id;
                                      }
                                      for (uint256 i; i < currLength; ++i) {
                                          if (!seen[i]) {
                                              Id id = withdrawQueue[i];
                                              if (config[id].cap != 0) revert ErrorsLib.InvalidMarketRemovalNonZeroCap(id);
                                              if (pendingCap[id].validAt != 0) revert ErrorsLib.PendingCap(id);
                                              if (MORPHO.supplyShares(id, address(this)) != 0) {
                                                  if (config[id].removableAt == 0) revert ErrorsLib.InvalidMarketRemovalNonZeroSupply(id);
                                                  if (block.timestamp < config[id].removableAt) {
                                                      revert ErrorsLib.InvalidMarketRemovalTimelockNotElapsed(id);
                                                  }
                                              }
                                              delete config[id];
                                          }
                                      }
                                      withdrawQueue = newWithdrawQueue;
                                      emit EventsLib.SetWithdrawQueue(_msgSender(), newWithdrawQueue);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function reallocate(MarketAllocation[] calldata allocations) external onlyAllocatorRole {
                                      uint256 totalSupplied;
                                      uint256 totalWithdrawn;
                                      for (uint256 i; i < allocations.length; ++i) {
                                          MarketAllocation memory allocation = allocations[i];
                                          Id id = allocation.marketParams.id();
                                          if (!config[id].enabled) revert ErrorsLib.MarketNotEnabled(id);
                                          (uint256 supplyAssets, uint256 supplyShares,) = _accruedSupplyBalance(allocation.marketParams, id);
                                          uint256 withdrawn = supplyAssets.zeroFloorSub(allocation.assets);
                                          if (withdrawn > 0) {
                                              // Guarantees that unknown frontrunning donations can be withdrawn, in order to disable a market.
                                              uint256 shares;
                                              if (allocation.assets == 0) {
                                                  shares = supplyShares;
                                                  withdrawn = 0;
                                              }
                                              (uint256 withdrawnAssets, uint256 withdrawnShares) =
                                                  MORPHO.withdraw(allocation.marketParams, withdrawn, shares, address(this), address(this));
                                              emit EventsLib.ReallocateWithdraw(_msgSender(), id, withdrawnAssets, withdrawnShares);
                                              totalWithdrawn += withdrawnAssets;
                                          } else {
                                              uint256 suppliedAssets = allocation.assets == type(uint256).max
                                                  ? totalWithdrawn.zeroFloorSub(totalSupplied)
                                                  : allocation.assets.zeroFloorSub(supplyAssets);
                                              if (suppliedAssets == 0) continue;
                                              uint256 supplyCap = config[id].cap;
                                              if (supplyAssets + suppliedAssets > supplyCap) revert ErrorsLib.SupplyCapExceeded(id);
                                              // The market's loan asset is guaranteed to be the vault's asset because it has a non-zero supply cap.
                                              (, uint256 suppliedShares) =
                                                  MORPHO.supply(allocation.marketParams, suppliedAssets, 0, address(this), hex"");
                                              emit EventsLib.ReallocateSupply(_msgSender(), id, suppliedAssets, suppliedShares);
                                              totalSupplied += suppliedAssets;
                                          }
                                      }
                                      if (totalWithdrawn != totalSupplied) revert ErrorsLib.InconsistentReallocation();
                                  }
                                  /* REVOKE FUNCTIONS */
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function revokePendingTimelock() external onlyGuardianRole {
                                      delete pendingTimelock;
                                      emit EventsLib.RevokePendingTimelock(_msgSender());
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function revokePendingGuardian() external onlyGuardianRole {
                                      delete pendingGuardian;
                                      emit EventsLib.RevokePendingGuardian(_msgSender());
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function revokePendingCap(Id id) external onlyCuratorOrGuardianRole {
                                      delete pendingCap[id];
                                      emit EventsLib.RevokePendingCap(_msgSender(), id);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function revokePendingMarketRemoval(Id id) external onlyCuratorOrGuardianRole {
                                      delete config[id].removableAt;
                                      emit EventsLib.RevokePendingMarketRemoval(_msgSender(), id);
                                  }
                                  /* EXTERNAL */
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function supplyQueueLength() external view returns (uint256) {
                                      return supplyQueue.length;
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function withdrawQueueLength() external view returns (uint256) {
                                      return withdrawQueue.length;
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function acceptTimelock() external afterTimelock(pendingTimelock.validAt) {
                                      _setTimelock(pendingTimelock.value);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function acceptGuardian() external afterTimelock(pendingGuardian.validAt) {
                                      _setGuardian(pendingGuardian.value);
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function acceptCap(MarketParams memory marketParams)
                                      external
                                      afterTimelock(pendingCap[marketParams.id()].validAt)
                                  {
                                      Id id = marketParams.id();
                                      // Safe "unchecked" cast because pendingCap <= type(uint184).max.
                                      _setCap(marketParams, id, uint184(pendingCap[id].value));
                                  }
                                  /// @inheritdoc IMetaMorphoV1_1Base
                                  function skim(address token) external {
                                      if (skimRecipient == address(0)) revert ErrorsLib.ZeroAddress();
                                      uint256 amount = IERC20(token).balanceOf(address(this));
                                      IERC20(token).safeTransfer(skimRecipient, amount);
                                      emit EventsLib.Skim(_msgSender(), token, amount);
                                  }
                                  /* ERC4626 (PUBLIC) */
                                  /// @inheritdoc IERC20Metadata
                                  function decimals() public view override(ERC20, ERC4626) returns (uint8) {
                                      return ERC4626.decimals();
                                  }
                                  function name() public view override(IERC20Metadata, ERC20) returns (string memory) {
                                      return _name;
                                  }
                                  function symbol() public view override(IERC20Metadata, ERC20) returns (string memory) {
                                      return _symbol;
                                  }
                                  /// @inheritdoc IERC4626
                                  /// @dev Warning: May be higher than the actual max deposit due to duplicate markets in the supplyQueue.
                                  function maxDeposit(address) public view override returns (uint256) {
                                      return _maxDeposit();
                                  }
                                  /// @inheritdoc IERC4626
                                  /// @dev Warning: May be higher than the actual max mint due to duplicate markets in the supplyQueue.
                                  function maxMint(address) public view override returns (uint256) {
                                      uint256 suppliable = _maxDeposit();
                                      return _convertToShares(suppliable, Math.Rounding.Floor);
                                  }
                                  /// @inheritdoc IERC4626
                                  /// @dev Warning: May be lower than the actual amount of assets that can be withdrawn by `owner` due to conversion
                                  /// roundings between shares and assets.
                                  function maxWithdraw(address owner) public view override returns (uint256 assets) {
                                      (assets,,) = _maxWithdraw(owner);
                                  }
                                  /// @inheritdoc IERC4626
                                  /// @dev Warning: May be lower than the actual amount of shares that can be redeemed by `owner` due to conversion
                                  /// roundings between shares and assets.
                                  function maxRedeem(address owner) public view override returns (uint256) {
                                      (uint256 assets, uint256 newTotalSupply, uint256 newTotalAssets) = _maxWithdraw(owner);
                                      return _convertToSharesWithTotals(assets, newTotalSupply, newTotalAssets, Math.Rounding.Floor);
                                  }
                                  /// @inheritdoc IERC4626
                                  function deposit(uint256 assets, address receiver) public override returns (uint256 shares) {
                                      _accrueInterest();
                                      shares = _convertToSharesWithTotals(assets, totalSupply(), lastTotalAssets, Math.Rounding.Floor);
                                      _deposit(_msgSender(), receiver, assets, shares);
                                  }
                                  /// @inheritdoc IERC4626
                                  function mint(uint256 shares, address receiver) public override returns (uint256 assets) {
                                      _accrueInterest();
                                      assets = _convertToAssetsWithTotals(shares, totalSupply(), lastTotalAssets, Math.Rounding.Ceil);
                                      _deposit(_msgSender(), receiver, assets, shares);
                                  }
                                  /// @inheritdoc IERC4626
                                  function withdraw(uint256 assets, address receiver, address owner) public override returns (uint256 shares) {
                                      _accrueInterest();
                                      // Do not call expensive `maxWithdraw` and optimistically withdraw assets.
                                      shares = _convertToSharesWithTotals(assets, totalSupply(), lastTotalAssets, Math.Rounding.Ceil);
                                      _withdraw(_msgSender(), receiver, owner, assets, shares);
                                  }
                                  /// @inheritdoc IERC4626
                                  function redeem(uint256 shares, address receiver, address owner) public override returns (uint256 assets) {
                                      _accrueInterest();
                                      // Do not call expensive `maxRedeem` and optimistically redeem shares.
                                      assets = _convertToAssetsWithTotals(shares, totalSupply(), lastTotalAssets, Math.Rounding.Floor);
                                      _withdraw(_msgSender(), receiver, owner, assets, shares);
                                  }
                                  /// @inheritdoc IERC4626
                                  /// @dev totalAssets is the sum of the vault's assets on the Morpho markets plus the lost assets (see corresponding
                                  /// docs in IMetaMorphoV1_1.sol).
                                  function totalAssets() public view override returns (uint256) {
                                      (, uint256 newTotalAssets,) = _accruedFeeAndAssets();
                                      return newTotalAssets;
                                  }
                                  /* ERC4626 (INTERNAL) */
                                  /// @inheritdoc ERC4626
                                  function _decimalsOffset() internal view override returns (uint8) {
                                      return DECIMALS_OFFSET;
                                  }
                                  /// @dev Returns the maximum amount of asset (`assets`) that the `owner` can withdraw from the vault, as well as the
                                  /// new vault's total supply (`newTotalSupply`) and total assets (`newTotalAssets`).
                                  function _maxWithdraw(address owner)
                                      internal
                                      view
                                      returns (uint256 assets, uint256 newTotalSupply, uint256 newTotalAssets)
                                  {
                                      uint256 feeShares;
                                      (feeShares, newTotalAssets,) = _accruedFeeAndAssets();
                                      newTotalSupply = totalSupply() + feeShares;
                                      assets = _convertToAssetsWithTotals(balanceOf(owner), newTotalSupply, newTotalAssets, Math.Rounding.Floor);
                                      assets -= _simulateWithdrawMorpho(assets);
                                  }
                                  /// @dev Returns the maximum amount of assets that the vault can supply on Morpho.
                                  function _maxDeposit() internal view returns (uint256 totalSuppliable) {
                                      for (uint256 i; i < supplyQueue.length; ++i) {
                                          Id id = supplyQueue[i];
                                          uint256 supplyCap = config[id].cap;
                                          if (supplyCap == 0) continue;
                                          uint256 supplyShares = MORPHO.supplyShares(id, address(this));
                                          (uint256 totalSupplyAssets, uint256 totalSupplyShares,,) = MORPHO.expectedMarketBalances(_marketParams(id));
                                          // `supplyAssets` needs to be rounded up for `totalSuppliable` to be rounded down.
                                          uint256 supplyAssets = supplyShares.toAssetsUp(totalSupplyAssets, totalSupplyShares);
                                          totalSuppliable += supplyCap.zeroFloorSub(supplyAssets);
                                      }
                                  }
                                  /// @inheritdoc ERC4626
                                  /// @dev The accrual of performance fees is taken into account in the conversion.
                                  function _convertToShares(uint256 assets, Math.Rounding rounding) internal view override returns (uint256) {
                                      (uint256 feeShares, uint256 newTotalAssets,) = _accruedFeeAndAssets();
                                      return _convertToSharesWithTotals(assets, totalSupply() + feeShares, newTotalAssets, rounding);
                                  }
                                  /// @inheritdoc ERC4626
                                  /// @dev The accrual of performance fees is taken into account in the conversion.
                                  function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view override returns (uint256) {
                                      (uint256 feeShares, uint256 newTotalAssets,) = _accruedFeeAndAssets();
                                      return _convertToAssetsWithTotals(shares, totalSupply() + feeShares, newTotalAssets, rounding);
                                  }
                                  /// @dev Returns the amount of shares that the vault would exchange for the amount of `assets` provided.
                                  /// @dev It assumes that the arguments `newTotalSupply` and `newTotalAssets` are up to date.
                                  function _convertToSharesWithTotals(
                                      uint256 assets,
                                      uint256 newTotalSupply,
                                      uint256 newTotalAssets,
                                      Math.Rounding rounding
                                  ) internal view returns (uint256) {
                                      return assets.mulDiv(newTotalSupply + 10 ** _decimalsOffset(), newTotalAssets + 1, rounding);
                                  }
                                  /// @dev Returns the amount of assets that the vault would exchange for the amount of `shares` provided.
                                  /// @dev It assumes that the arguments `newTotalSupply` and `newTotalAssets` are up to date.
                                  function _convertToAssetsWithTotals(
                                      uint256 shares,
                                      uint256 newTotalSupply,
                                      uint256 newTotalAssets,
                                      Math.Rounding rounding
                                  ) internal view returns (uint256) {
                                      return shares.mulDiv(newTotalAssets + 1, newTotalSupply + 10 ** _decimalsOffset(), rounding);
                                  }
                                  /// @inheritdoc ERC4626
                                  /// @dev Used in mint or deposit to deposit the underlying asset to Morpho markets.
                                  function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal override {
                                      super._deposit(caller, receiver, assets, shares);
                                      _supplyMorpho(assets);
                                      // `lastTotalAssets + assets` may be a little above `totalAssets()`.
                                      // This can lead to a small accrual of `lostAssets` at the next interaction.
                                      _updateLastTotalAssets(lastTotalAssets + assets);
                                  }
                                  /// @inheritdoc ERC4626
                                  /// @dev Used in redeem or withdraw to withdraw the underlying asset from Morpho markets.
                                  /// @dev Depending on 3 cases, reverts when withdrawing "too much" with:
                                  /// 1. NotEnoughLiquidity when withdrawing more than available liquidity.
                                  /// 2. ERC20InsufficientAllowance when withdrawing more than `caller`'s allowance.
                                  /// 3. ERC20InsufficientBalance when withdrawing more than `owner`'s balance.
                                  function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)
                                      internal
                                      override
                                  {
                                      // `lastTotalAssets - assets` may be a little above `totalAssets()`.
                                      // This can lead to a small accrual of `lostAssets` at the next interaction.
                                      // clamp at 0 so the error raised is the more informative NotEnoughLiquidity.
                                      _updateLastTotalAssets(lastTotalAssets.zeroFloorSub(assets));
                                      _withdrawMorpho(assets);
                                      super._withdraw(caller, receiver, owner, assets, shares);
                                  }
                                  /* INTERNAL */
                                  /// @dev Returns the market params of the market defined by `id`.
                                  function _marketParams(Id id) internal view returns (MarketParams memory) {
                                      return MORPHO.idToMarketParams(id);
                                  }
                                  /// @dev Accrues interest on Morpho Blue and returns the vault's assets & corresponding shares supplied on the
                                  /// market defined by `marketParams`, as well as the market's state.
                                  /// @dev Assumes that the inputs `marketParams` and `id` match.
                                  function _accruedSupplyBalance(MarketParams memory marketParams, Id id)
                                      internal
                                      returns (uint256 assets, uint256 shares, Market memory market)
                                  {
                                      MORPHO.accrueInterest(marketParams);
                                      market = MORPHO.market(id);
                                      shares = MORPHO.supplyShares(id, address(this));
                                      assets = shares.toAssetsDown(market.totalSupplyAssets, market.totalSupplyShares);
                                  }
                                  /// @dev Reverts if `newTimelock` is not within the bounds.
                                  function _checkTimelockBounds(uint256 newTimelock) internal pure {
                                      if (newTimelock > ConstantsLib.MAX_TIMELOCK) revert ErrorsLib.AboveMaxTimelock();
                                      if (newTimelock < ConstantsLib.POST_INITIALIZATION_MIN_TIMELOCK) revert ErrorsLib.BelowMinTimelock();
                                  }
                                  /// @dev Sets `timelock` to `newTimelock`.
                                  function _setTimelock(uint256 newTimelock) internal {
                                      timelock = newTimelock;
                                      emit EventsLib.SetTimelock(_msgSender(), newTimelock);
                                      delete pendingTimelock;
                                  }
                                  /// @dev Sets `guardian` to `newGuardian`.
                                  function _setGuardian(address newGuardian) internal {
                                      guardian = newGuardian;
                                      emit EventsLib.SetGuardian(_msgSender(), newGuardian);
                                      delete pendingGuardian;
                                  }
                                  /// @dev Sets the cap of the market defined by `id` to `supplyCap`.
                                  /// @dev Assumes that the inputs `marketParams` and `id` match.
                                  function _setCap(MarketParams memory marketParams, Id id, uint184 supplyCap) internal {
                                      MarketConfig storage marketConfig = config[id];
                                      if (supplyCap > 0) {
                                          if (!marketConfig.enabled) {
                                              withdrawQueue.push(id);
                                              if (withdrawQueue.length > ConstantsLib.MAX_QUEUE_LENGTH) revert ErrorsLib.MaxQueueLengthExceeded();
                                              marketConfig.enabled = true;
                                              // Take into account assets of the new market without applying a fee.
                                              _updateLastTotalAssets(lastTotalAssets + MORPHO.expectedSupplyAssets(marketParams, address(this)));
                                              emit EventsLib.SetWithdrawQueue(msg.sender, withdrawQueue);
                                          }
                                          marketConfig.removableAt = 0;
                                      }
                                      marketConfig.cap = supplyCap;
                                      emit EventsLib.SetCap(_msgSender(), id, supplyCap);
                                      delete pendingCap[id];
                                  }
                                  /* LIQUIDITY ALLOCATION */
                                  /// @dev Supplies `assets` to Morpho.
                                  function _supplyMorpho(uint256 assets) internal {
                                      for (uint256 i; i < supplyQueue.length; ++i) {
                                          Id id = supplyQueue[i];
                                          uint256 supplyCap = config[id].cap;
                                          if (supplyCap == 0) continue;
                                          MarketParams memory marketParams = _marketParams(id);
                                          MORPHO.accrueInterest(marketParams);
                                          Market memory market = MORPHO.market(id);
                                          uint256 supplyShares = MORPHO.supplyShares(id, address(this));
                                          // `supplyAssets` needs to be rounded up for `toSupply` to be rounded down.
                                          uint256 supplyAssets = supplyShares.toAssetsUp(market.totalSupplyAssets, market.totalSupplyShares);
                                          uint256 toSupply = UtilsLib.min(supplyCap.zeroFloorSub(supplyAssets), assets);
                                          if (toSupply > 0) {
                                              // Using try/catch to skip markets that revert.
                                              try MORPHO.supply(marketParams, toSupply, 0, address(this), hex"") {
                                                  assets -= toSupply;
                                              } catch {}
                                          }
                                          if (assets == 0) return;
                                      }
                                      if (assets != 0) revert ErrorsLib.AllCapsReached();
                                  }
                                  /// @dev Withdraws `assets` from Morpho.
                                  function _withdrawMorpho(uint256 assets) internal {
                                      for (uint256 i; i < withdrawQueue.length; ++i) {
                                          Id id = withdrawQueue[i];
                                          MarketParams memory marketParams = _marketParams(id);
                                          (uint256 supplyAssets,, Market memory market) = _accruedSupplyBalance(marketParams, id);
                                          uint256 toWithdraw = UtilsLib.min(
                                              _withdrawable(marketParams, market.totalSupplyAssets, market.totalBorrowAssets, supplyAssets), assets
                                          );
                                          if (toWithdraw > 0) {
                                              // Using try/catch to skip markets that revert.
                                              try MORPHO.withdraw(marketParams, toWithdraw, 0, address(this), address(this)) {
                                                  assets -= toWithdraw;
                                              } catch {}
                                          }
                                          if (assets == 0) return;
                                      }
                                      if (assets != 0) revert ErrorsLib.NotEnoughLiquidity();
                                  }
                                  /// @dev Simulates a withdraw of `assets` from Morpho.
                                  /// @return The remaining assets to be withdrawn.
                                  function _simulateWithdrawMorpho(uint256 assets) internal view returns (uint256) {
                                      for (uint256 i; i < withdrawQueue.length; ++i) {
                                          Id id = withdrawQueue[i];
                                          MarketParams memory marketParams = _marketParams(id);
                                          uint256 supplyShares = MORPHO.supplyShares(id, address(this));
                                          (uint256 totalSupplyAssets, uint256 totalSupplyShares, uint256 totalBorrowAssets,) =
                                              MORPHO.expectedMarketBalances(marketParams);
                                          // The vault withdrawing from Morpho cannot fail because:
                                          // 1. oracle.price() is never called (the vault doesn't borrow)
                                          // 2. the amount is capped to the liquidity available on Morpho
                                          // 3. virtually accruing interest didn't fail
                                          assets = assets.zeroFloorSub(
                                              _withdrawable(
                                                  marketParams,
                                                  totalSupplyAssets,
                                                  totalBorrowAssets,
                                                  supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares)
                                              )
                                          );
                                          if (assets == 0) break;
                                      }
                                      return assets;
                                  }
                                  /// @dev Returns the withdrawable amount of assets from the market defined by `marketParams`, given the market's
                                  /// total supply and borrow assets and the vault's assets supplied.
                                  function _withdrawable(
                                      MarketParams memory marketParams,
                                      uint256 totalSupplyAssets,
                                      uint256 totalBorrowAssets,
                                      uint256 supplyAssets
                                  ) internal view returns (uint256) {
                                      // Inside a flashloan callback, liquidity on Morpho Blue may be limited to the singleton's balance.
                                      uint256 availableLiquidity = UtilsLib.min(
                                          totalSupplyAssets - totalBorrowAssets, ERC20(marketParams.loanToken).balanceOf(address(MORPHO))
                                      );
                                      return UtilsLib.min(supplyAssets, availableLiquidity);
                                  }
                                  /* FEE MANAGEMENT */
                                  /// @dev Updates `lastTotalAssets` to `updatedTotalAssets`.
                                  function _updateLastTotalAssets(uint256 updatedTotalAssets) internal {
                                      lastTotalAssets = updatedTotalAssets;
                                      emit EventsLib.UpdateLastTotalAssets(updatedTotalAssets);
                                  }
                                  /// @dev Accrues `lastTotalAssets`, `lostAssets` and mints the fee shares to the fee recipient.
                                  function _accrueInterest() internal {
                                      (uint256 feeShares, uint256 newTotalAssets, uint256 newLostAssets) = _accruedFeeAndAssets();
                                      _updateLastTotalAssets(newTotalAssets);
                                      lostAssets = newLostAssets;
                                      emit EventsLib.UpdateLostAssets(newLostAssets);
                                      if (feeShares != 0) _mint(feeRecipient, feeShares);
                                      emit EventsLib.AccrueInterest(newTotalAssets, feeShares);
                                  }
                                  /// @dev Computes and returns the `feeShares` to mint, the new `totalAssets` and the new `lostAssets`.
                                  /// @return feeShares the shares to mint to `feeRecipient`.
                                  /// @return newTotalAssets the new `totalAssets`.
                                  /// @return newLostAssets the new lostAssets.
                                  function _accruedFeeAndAssets()
                                      internal
                                      view
                                      returns (uint256 feeShares, uint256 newTotalAssets, uint256 newLostAssets)
                                  {
                                      // The assets that the vault has on Morpho.
                                      uint256 realTotalAssets;
                                      for (uint256 i; i < withdrawQueue.length; ++i) {
                                          realTotalAssets += MORPHO.expectedSupplyAssets(_marketParams(withdrawQueue[i]), address(this));
                                      }
                                      // If the vault lost some assets (realTotalAssets decreased), lostAssets is increased.
                                      if (realTotalAssets < lastTotalAssets - lostAssets) newLostAssets = lastTotalAssets - realTotalAssets;
                                      // If it did not, lostAssets stays the same.
                                      else newLostAssets = lostAssets;
                                      newTotalAssets = realTotalAssets + newLostAssets;
                                      uint256 totalInterest = newTotalAssets - lastTotalAssets;
                                      if (totalInterest != 0 && fee != 0) {
                                          // It is acknowledged that `feeAssets` may be rounded down to 0 if `totalInterest * fee < WAD`.
                                          uint256 feeAssets = totalInterest.mulDiv(fee, WAD);
                                          // The fee assets is subtracted from the total assets in this calculation to compensate for the fact
                                          // that total assets is already increased by the total interest (including the fee assets).
                                          feeShares =
                                              _convertToSharesWithTotals(feeAssets, totalSupply(), newTotalAssets - feeAssets, Math.Rounding.Floor);
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              import {IMorpho, Id, MarketParams} from "../../lib/morpho-blue/src/interfaces/IMorpho.sol";
                              import {IERC4626} from "../../lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
                              import {IERC20Permit} from "../../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol";
                              import {MarketConfig, PendingUint192, PendingAddress} from "../libraries/PendingLib.sol";
                              struct MarketAllocation {
                                  /// @notice The market to allocate.
                                  MarketParams marketParams;
                                  /// @notice The amount of assets to allocate.
                                  uint256 assets;
                              }
                              interface IMulticall {
                                  function multicall(bytes[] calldata) external returns (bytes[] memory);
                              }
                              interface IOwnable {
                                  function owner() external view returns (address);
                                  function transferOwnership(address) external;
                                  function renounceOwnership() external;
                                  function acceptOwnership() external;
                                  function pendingOwner() external view returns (address);
                              }
                              /// @dev This interface is used for factorizing IMetaMorphoV1_1StaticTyping and IMetaMorphoV1_1.
                              /// @dev Consider using the IMetaMorphoV1_1 interface instead of this one.
                              interface IMetaMorphoV1_1Base {
                                  /// @notice The address of the Morpho contract.
                                  function MORPHO() external view returns (IMorpho);
                                  function DECIMALS_OFFSET() external view returns (uint8);
                                  /// @notice The address of the curator.
                                  function curator() external view returns (address);
                                  /// @notice Stores whether an address is an allocator or not.
                                  function isAllocator(address target) external view returns (bool);
                                  /// @notice The current guardian. Can be set even without the timelock set.
                                  function guardian() external view returns (address);
                                  /// @notice The current fee.
                                  function fee() external view returns (uint96);
                                  /// @notice The fee recipient.
                                  function feeRecipient() external view returns (address);
                                  /// @notice The skim recipient.
                                  function skimRecipient() external view returns (address);
                                  /// @notice The current timelock.
                                  function timelock() external view returns (uint256);
                                  /// @dev Stores the order of markets on which liquidity is supplied upon deposit.
                                  /// @dev Can contain any market. A market is skipped as soon as its supply cap is reached.
                                  function supplyQueue(uint256) external view returns (Id);
                                  /// @notice Returns the length of the supply queue.
                                  function supplyQueueLength() external view returns (uint256);
                                  /// @dev Stores the order of markets from which liquidity is withdrawn upon withdrawal.
                                  /// @dev Always contain all non-zero cap markets as well as all markets on which the vault supplies liquidity,
                                  /// without duplicate.
                                  function withdrawQueue(uint256) external view returns (Id);
                                  /// @notice Returns the length of the withdraw queue.
                                  function withdrawQueueLength() external view returns (uint256);
                                  /// @notice Stores the total assets managed by this vault when the fee was last accrued.
                                  /// @dev May be greater than `totalAssets()` due to removal of markets with non-zero supply or socialized bad debt.
                                  /// This difference will decrease the fee accrued until one of the functions updating `lastTotalAssets` is
                                  /// triggered (deposit/mint/withdraw/redeem/setFee/setFeeRecipient).
                                  function lastTotalAssets() external view returns (uint256);
                                  /// @notice Stores the missing assets due to realized bad debt or forced market removal.
                                  /// @dev In order to cover those lost assets, it is advised to supply on behalf of address(1) on the vault
                                  /// (canonical method).
                                  function lostAssets() external view returns (uint256);
                                  /// @notice Submits a `newTimelock`.
                                  /// @dev Warning: Reverts if a timelock is already pending. Revoke the pending timelock to overwrite it.
                                  /// @dev In case the new timelock is higher than the current one, the timelock is set immediately.
                                  function submitTimelock(uint256 newTimelock) external;
                                  /// @notice Accepts the pending timelock.
                                  function acceptTimelock() external;
                                  /// @notice Revokes the pending timelock.
                                  /// @dev Does not revert if there is no pending timelock.
                                  function revokePendingTimelock() external;
                                  /// @notice Submits a `newSupplyCap` for the market defined by `marketParams`.
                                  /// @dev Warning: Reverts if a cap is already pending. Revoke the pending cap to overwrite it.
                                  /// @dev Warning: Reverts if a market removal is pending.
                                  /// @dev In case the new cap is lower than the current one, the cap is set immediately.
                                  function submitCap(MarketParams memory marketParams, uint256 newSupplyCap) external;
                                  /// @notice Accepts the pending cap of the market defined by `marketParams`.
                                  function acceptCap(MarketParams memory marketParams) external;
                                  /// @notice Revokes the pending cap of the market defined by `id`.
                                  /// @dev Does not revert if there is no pending cap.
                                  function revokePendingCap(Id id) external;
                                  /// @notice Submits a forced market removal from the vault, eventually losing all funds supplied to the market.
                                  /// @notice Funds can be recovered by enabling this market again and withdrawing from it (using `reallocate`),
                                  /// but funds will be distributed pro-rata to the shares at the time of withdrawal, not at the time of removal.
                                  /// @notice This forced removal is expected to be used as an emergency process in case a market constantly reverts.
                                  /// To softly remove a sane market, the curator role is expected to bundle a reallocation that empties the market
                                  /// first (using `reallocate`), followed by the removal of the market (using `updateWithdrawQueue`).
                                  /// @dev Warning: Removing a market with non-zero supply will instantly impact the vault's price per share.
                                  /// @dev Warning: Reverts for non-zero cap or if there is a pending cap. Successfully submitting a zero cap will
                                  /// prevent such reverts.
                                  function submitMarketRemoval(MarketParams memory marketParams) external;
                                  /// @notice Revokes the pending removal of the market defined by `id`.
                                  /// @dev Does not revert if there is no pending market removal.
                                  function revokePendingMarketRemoval(Id id) external;
                                  /// @notice Sets the name of the vault.
                                  function setName(string memory newName) external;
                                  /// @notice Sets the symbol of the vault.
                                  function setSymbol(string memory newSymbol) external;
                                  /// @notice Submits a `newGuardian`.
                                  /// @notice Warning: a malicious guardian could disrupt the vault's operation, and would have the power to revoke
                                  /// any pending guardian.
                                  /// @dev In case there is no guardian, the gardian is set immediately.
                                  /// @dev Warning: Submitting a gardian will overwrite the current pending gardian.
                                  function submitGuardian(address newGuardian) external;
                                  /// @notice Accepts the pending guardian.
                                  function acceptGuardian() external;
                                  /// @notice Revokes the pending guardian.
                                  function revokePendingGuardian() external;
                                  /// @notice Skims the vault `token` balance to `skimRecipient`.
                                  function skim(address) external;
                                  /// @notice Sets `newAllocator` as an allocator or not (`newIsAllocator`).
                                  function setIsAllocator(address newAllocator, bool newIsAllocator) external;
                                  /// @notice Sets `curator` to `newCurator`.
                                  function setCurator(address newCurator) external;
                                  /// @notice Sets the `fee` to `newFee`.
                                  function setFee(uint256 newFee) external;
                                  /// @notice Sets `feeRecipient` to `newFeeRecipient`.
                                  function setFeeRecipient(address newFeeRecipient) external;
                                  /// @notice Sets `skimRecipient` to `newSkimRecipient`.
                                  function setSkimRecipient(address newSkimRecipient) external;
                                  /// @notice Sets `supplyQueue` to `newSupplyQueue`.
                                  /// @param newSupplyQueue is an array of enabled markets, and can contain duplicate markets, but it would only
                                  /// increase the cost of depositing to the vault.
                                  function setSupplyQueue(Id[] calldata newSupplyQueue) external;
                                  /// @notice Updates the withdraw queue. Some markets can be removed, but no market can be added.
                                  /// @notice Removing a market requires the vault to have 0 supply on it, or to have previously submitted a removal
                                  /// for this market (with the function `submitMarketRemoval`).
                                  /// @notice Warning: Anyone can supply on behalf of the vault so the call to `updateWithdrawQueue` that expects a
                                  /// market to be empty can be griefed by a front-run. To circumvent this, the allocator can simply bundle a
                                  /// reallocation that withdraws max from this market with a call to `updateWithdrawQueue`.
                                  /// @dev Warning: Removing a market with supply will decrease the fee accrued until one of the functions updating
                                  /// `lastTotalAssets` is triggered (deposit/mint/withdraw/redeem/setFee/setFeeRecipient).
                                  /// @dev Warning: `updateWithdrawQueue` is not idempotent. Submitting twice the same tx will change the queue twice.
                                  /// @param indexes The indexes of each market in the previous withdraw queue, in the new withdraw queue's order.
                                  function updateWithdrawQueue(uint256[] calldata indexes) external;
                                  /// @notice Reallocates the vault's liquidity so as to reach a given allocation of assets on each given market.
                                  /// @dev The behavior of the reallocation can be altered by state changes, including:
                                  /// - Deposits on the vault that supplies to markets that are expected to be supplied to during reallocation.
                                  /// - Withdrawals from the vault that withdraws from markets that are expected to be withdrawn from during
                                  /// reallocation.
                                  /// - Donations to the vault on markets that are expected to be supplied to during reallocation.
                                  /// - Withdrawals from markets that are expected to be withdrawn from during reallocation.
                                  /// @dev Sender is expected to pass `assets = type(uint256).max` with the last MarketAllocation of `allocations` to
                                  /// supply all the remaining withdrawn liquidity, which would ensure that `totalWithdrawn` = `totalSupplied`.
                                  /// @dev A supply in a reallocation step will make the reallocation revert if the amount is greater than the net
                                  /// amount from previous steps (i.e. total withdrawn minus total supplied).
                                  function reallocate(MarketAllocation[] calldata allocations) external;
                              }
                              /// @dev This interface is inherited by MetaMorphoV1_1 so that function signatures are checked by the compiler.
                              /// @dev Consider using the IMetaMorphoV1_1 interface instead of this one.
                              interface IMetaMorphoV1_1StaticTyping is IMetaMorphoV1_1Base {
                                  /// @notice Returns the current configuration of each market.
                                  function config(Id) external view returns (uint184 cap, bool enabled, uint64 removableAt);
                                  /// @notice Returns the pending guardian.
                                  function pendingGuardian() external view returns (address guardian, uint64 validAt);
                                  /// @notice Returns the pending cap for each market.
                                  function pendingCap(Id) external view returns (uint192 value, uint64 validAt);
                                  /// @notice Returns the pending timelock.
                                  function pendingTimelock() external view returns (uint192 value, uint64 validAt);
                              }
                              /// @title IMetaMorphoV1_1
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @dev Use this interface for MetaMorphoV1_1 to have access to all the functions with the appropriate function
                              /// signatures.
                              interface IMetaMorphoV1_1 is IMetaMorphoV1_1Base, IERC4626, IERC20Permit, IOwnable, IMulticall {
                                  /// @notice Returns the current configuration of each market.
                                  function config(Id) external view returns (MarketConfig memory);
                                  /// @notice Returns the pending guardian.
                                  function pendingGuardian() external view returns (PendingAddress memory);
                                  /// @notice Returns the pending cap for each market.
                                  function pendingCap(Id) external view returns (PendingUint192 memory);
                                  /// @notice Returns the pending timelock.
                                  function pendingTimelock() external view returns (PendingUint192 memory);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              type Id is bytes32;
                              struct MarketParams {
                                  address loanToken;
                                  address collateralToken;
                                  address oracle;
                                  address irm;
                                  uint256 lltv;
                              }
                              /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
                              /// accrual.
                              struct Position {
                                  uint256 supplyShares;
                                  uint128 borrowShares;
                                  uint128 collateral;
                              }
                              /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                              /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                              /// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
                              /// interest accrual.
                              struct Market {
                                  uint128 totalSupplyAssets;
                                  uint128 totalSupplyShares;
                                  uint128 totalBorrowAssets;
                                  uint128 totalBorrowShares;
                                  uint128 lastUpdate;
                                  uint128 fee;
                              }
                              struct Authorization {
                                  address authorizer;
                                  address authorized;
                                  bool isAuthorized;
                                  uint256 nonce;
                                  uint256 deadline;
                              }
                              struct Signature {
                                  uint8 v;
                                  bytes32 r;
                                  bytes32 s;
                              }
                              /// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
                              /// @dev Consider using the IMorpho interface instead of this one.
                              interface IMorphoBase {
                                  /// @notice The EIP-712 domain separator.
                                  /// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on chains sharing the
                                  /// same chain id and on forks because the domain separator would be the same.
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                                  /// @notice The owner of the contract.
                                  /// @dev It has the power to change the owner.
                                  /// @dev It has the power to set fees on markets and set the fee recipient.
                                  /// @dev It has the power to enable but not disable IRMs and LLTVs.
                                  function owner() external view returns (address);
                                  /// @notice The fee recipient of all markets.
                                  /// @dev The recipient receives the fees of a given market through a supply position on that market.
                                  function feeRecipient() external view returns (address);
                                  /// @notice Whether the `irm` is enabled.
                                  function isIrmEnabled(address irm) external view returns (bool);
                                  /// @notice Whether the `lltv` is enabled.
                                  function isLltvEnabled(uint256 lltv) external view returns (bool);
                                  /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
                                  /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
                                  function isAuthorized(address authorizer, address authorized) external view returns (bool);
                                  /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
                                  function nonce(address authorizer) external view returns (uint256);
                                  /// @notice Sets `newOwner` as `owner` of the contract.
                                  /// @dev Warning: No two-step transfer ownership.
                                  /// @dev Warning: The owner can be set to the zero address.
                                  function setOwner(address newOwner) external;
                                  /// @notice Enables `irm` as a possible IRM for market creation.
                                  /// @dev Warning: It is not possible to disable an IRM.
                                  function enableIrm(address irm) external;
                                  /// @notice Enables `lltv` as a possible LLTV for market creation.
                                  /// @dev Warning: It is not possible to disable a LLTV.
                                  function enableLltv(uint256 lltv) external;
                                  /// @notice Sets the `newFee` for the given market `marketParams`.
                                  /// @param newFee The new fee, scaled by WAD.
                                  /// @dev Warning: The recipient can be the zero address.
                                  function setFee(MarketParams memory marketParams, uint256 newFee) external;
                                  /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
                                  /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
                                  /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
                                  /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
                                  function setFeeRecipient(address newFeeRecipient) external;
                                  /// @notice Creates the market `marketParams`.
                                  /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
                                  /// Morpho behaves as expected:
                                  /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
                                  /// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
                                  /// burn functions are not supported.
                                  /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
                                  /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
                                  /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
                                  /// - The IRM should not re-enter Morpho.
                                  /// - The oracle should return a price with the correct scaling.
                                  /// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties
                                  /// (funds could get stuck):
                                  /// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
                                  /// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
                                  /// `toSharesDown` overflow.
                                  /// - The IRM can revert on `borrowRate`.
                                  /// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
                                  /// overflow.
                                  /// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
                                  /// `liquidate` from being used under certain market conditions.
                                  /// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
                                  /// the computation of `assetsRepaid` in `liquidate` overflow.
                                  /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
                                  /// the point where `totalBorrowShares` is very large and borrowing overflows.
                                  function createMarket(MarketParams memory marketParams) external;
                                  /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoSupply` function with the given `data`.
                                  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
                                  /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
                                  /// amount of shares is given for full compatibility and precision.
                                  /// @dev Supplying a large amount can revert for overflow.
                                  /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
                                  /// Consider using the `assets` parameter to avoid this.
                                  /// @param marketParams The market to supply assets to.
                                  /// @param assets The amount of assets to supply.
                                  /// @param shares The amount of shares to mint.
                                  /// @param onBehalf The address that will own the increased supply position.
                                  /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
                                  /// @return assetsSupplied The amount of assets supplied.
                                  /// @return sharesSupplied The amount of shares minted.
                                  function supply(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes memory data
                                  ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
                                  /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
                                  /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
                                  /// conversion roundings between shares and assets.
                                  /// @param marketParams The market to withdraw assets from.
                                  /// @param assets The amount of assets to withdraw.
                                  /// @param shares The amount of shares to burn.
                                  /// @param onBehalf The address of the owner of the supply position.
                                  /// @param receiver The address that will receive the withdrawn assets.
                                  /// @return assetsWithdrawn The amount of assets withdrawn.
                                  /// @return sharesWithdrawn The amount of shares burned.
                                  function withdraw(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
                                  /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
                                  /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
                                  /// given for full compatibility and precision.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Borrowing a large amount can revert for overflow.
                                  /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
                                  /// Consider using the `assets` parameter to avoid this.
                                  /// @param marketParams The market to borrow assets from.
                                  /// @param assets The amount of assets to borrow.
                                  /// @param shares The amount of shares to mint.
                                  /// @param onBehalf The address that will own the increased borrow position.
                                  /// @param receiver The address that will receive the borrowed assets.
                                  /// @return assetsBorrowed The amount of assets borrowed.
                                  /// @return sharesBorrowed The amount of shares minted.
                                  function borrow(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
                                  /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoRepay` function with the given `data`.
                                  /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
                                  /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
                                  /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
                                  /// roundings between shares and assets.
                                  /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
                                  /// @param marketParams The market to repay assets to.
                                  /// @param assets The amount of assets to repay.
                                  /// @param shares The amount of shares to burn.
                                  /// @param onBehalf The address of the owner of the debt position.
                                  /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
                                  /// @return assetsRepaid The amount of assets repaid.
                                  /// @return sharesRepaid The amount of shares burned.
                                  function repay(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes memory data
                                  ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
                                  /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoSupplyCollateral` function with the given `data`.
                                  /// @dev Interest are not accrued since it's not required and it saves gas.
                                  /// @dev Supplying a large amount can revert for overflow.
                                  /// @param marketParams The market to supply collateral to.
                                  /// @param assets The amount of collateral to supply.
                                  /// @param onBehalf The address that will own the increased collateral position.
                                  /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
                                  function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
                                      external;
                                  /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
                                  /// @param marketParams The market to withdraw collateral from.
                                  /// @param assets The amount of collateral to withdraw.
                                  /// @param onBehalf The address of the owner of the collateral position.
                                  /// @param receiver The address that will receive the collateral assets.
                                  function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
                                      external;
                                  /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
                                  /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
                                  /// `onMorphoLiquidate` function with the given `data`.
                                  /// @dev Either `seizedAssets` or `repaidShares` should be zero.
                                  /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
                                  /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
                                  /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
                                  /// @param marketParams The market of the position.
                                  /// @param borrower The owner of the position.
                                  /// @param seizedAssets The amount of collateral to seize.
                                  /// @param repaidShares The amount of shares to repay.
                                  /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
                                  /// @return The amount of assets seized.
                                  /// @return The amount of assets repaid.
                                  function liquidate(
                                      MarketParams memory marketParams,
                                      address borrower,
                                      uint256 seizedAssets,
                                      uint256 repaidShares,
                                      bytes memory data
                                  ) external returns (uint256, uint256);
                                  /// @notice Executes a flash loan.
                                  /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
                                  /// markets combined, plus donations).
                                  /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
                                  /// - `flashFee` is zero.
                                  /// - `maxFlashLoan` is the token's balance of this contract.
                                  /// - The receiver of `assets` is the caller.
                                  /// @param token The token to flash loan.
                                  /// @param assets The amount of assets to flash loan.
                                  /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
                                  function flashLoan(address token, uint256 assets, bytes calldata data) external;
                                  /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
                                  /// @param authorized The authorized address.
                                  /// @param newIsAuthorized The new authorization status.
                                  function setAuthorization(address authorized, bool newIsAuthorized) external;
                                  /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
                                  /// @dev Warning: Reverts if the signature has already been submitted.
                                  /// @dev The signature is malleable, but it has no impact on the security here.
                                  /// @dev The nonce is passed as argument to be able to revert with a different error message.
                                  /// @param authorization The `Authorization` struct.
                                  /// @param signature The signature.
                                  function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
                                  /// @notice Accrues interest for the given market `marketParams`.
                                  function accrueInterest(MarketParams memory marketParams) external;
                                  /// @notice Returns the data stored on the different `slots`.
                                  function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
                              }
                              /// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
                              /// @dev Consider using the IMorpho interface instead of this one.
                              interface IMorphoStaticTyping is IMorphoBase {
                                  /// @notice The state of the position of `user` on the market corresponding to `id`.
                                  /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
                                  /// accrual.
                                  function position(Id id, address user)
                                      external
                                      view
                                      returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
                                  /// @notice The state of the market corresponding to `id`.
                                  /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
                                  /// accrual.
                                  function market(Id id)
                                      external
                                      view
                                      returns (
                                          uint128 totalSupplyAssets,
                                          uint128 totalSupplyShares,
                                          uint128 totalBorrowAssets,
                                          uint128 totalBorrowShares,
                                          uint128 lastUpdate,
                                          uint128 fee
                                      );
                                  /// @notice The market params corresponding to `id`.
                                  /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
                                  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
                                  function idToMarketParams(Id id)
                                      external
                                      view
                                      returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
                              }
                              /// @title IMorpho
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
                              interface IMorpho is IMorphoBase {
                                  /// @notice The state of the position of `user` on the market corresponding to `id`.
                                  /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
                                  /// accrual.
                                  function position(Id id, address user) external view returns (Position memory p);
                                  /// @notice The state of the market corresponding to `id`.
                                  /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
                                  /// interest accrual.
                                  function market(Id id) external view returns (Market memory m);
                                  /// @notice The market params corresponding to `id`.
                                  /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
                                  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
                                  function idToMarketParams(Id id) external view returns (MarketParams memory);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              struct MarketConfig {
                                  /// @notice The maximum amount of assets that can be allocated to the market.
                                  uint184 cap;
                                  /// @notice Whether the market is in the withdraw queue.
                                  bool enabled;
                                  /// @notice The timestamp at which the market can be instantly removed from the withdraw queue.
                                  uint64 removableAt;
                              }
                              struct PendingUint192 {
                                  /// @notice The pending value to set.
                                  uint192 value;
                                  /// @notice The timestamp at which the pending value becomes valid.
                                  uint64 validAt;
                              }
                              struct PendingAddress {
                                  /// @notice The pending value to set.
                                  address value;
                                  /// @notice The timestamp at which the pending value becomes valid.
                                  uint64 validAt;
                              }
                              /// @title PendingLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to manage pending values and their validity timestamp.
                              library PendingLib {
                                  /// @dev Updates `pending`'s value to `newValue` and its corresponding `validAt` timestamp.
                                  /// @dev Assumes `timelock` <= `MAX_TIMELOCK`.
                                  function update(PendingUint192 storage pending, uint184 newValue, uint256 timelock) internal {
                                      pending.value = newValue;
                                      // Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
                                      pending.validAt = uint64(block.timestamp + timelock);
                                  }
                                  /// @dev Updates `pending`'s value to `newValue` and its corresponding `validAt` timestamp.
                                  /// @dev Assumes `timelock` <= `MAX_TIMELOCK`.
                                  function update(PendingAddress storage pending, address newValue, uint256 timelock) internal {
                                      pending.value = newValue;
                                      // Safe "unchecked" cast because timelock <= MAX_TIMELOCK.
                                      pending.validAt = uint64(block.timestamp + timelock);
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              /// @title ConstantsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing constants.
                              library ConstantsLib {
                                  /// @dev The maximum delay of a timelock.
                                  uint256 internal constant MAX_TIMELOCK = 2 weeks;
                                  /// @dev The minimum delay of a timelock post initialization.
                                  uint256 internal constant POST_INITIALIZATION_MIN_TIMELOCK = 1 days;
                                  /// @dev The maximum number of markets in the supply/withdraw queue.
                                  uint256 internal constant MAX_QUEUE_LENGTH = 30;
                                  /// @dev The maximum fee the vault can have (50%).
                                  uint256 internal constant MAX_FEE = 0.5e18;
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id} from "../../lib/morpho-blue/src/interfaces/IMorpho.sol";
                              /// @title ErrorsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing error messages.
                              library ErrorsLib {
                                  /// @notice Thrown when the address passed is the zero address.
                                  error ZeroAddress();
                                  /// @notice Thrown when the caller doesn't have the curator role.
                                  error NotCuratorRole();
                                  /// @notice Thrown when the caller doesn't have the allocator role.
                                  error NotAllocatorRole();
                                  /// @notice Thrown when the caller doesn't have the guardian role.
                                  error NotGuardianRole();
                                  /// @notice Thrown when the caller doesn't have the curator nor the guardian role.
                                  error NotCuratorNorGuardianRole();
                                  /// @notice Thrown when the market `id` cannot be set in the supply queue.
                                  error UnauthorizedMarket(Id id);
                                  /// @notice Thrown when submitting a cap for a market `id` whose loan token does not correspond to the underlying.
                                  /// asset.
                                  error InconsistentAsset(Id id);
                                  /// @notice Thrown when the supply cap has been exceeded on market `id` during a reallocation of funds.
                                  error SupplyCapExceeded(Id id);
                                  /// @notice Thrown when the fee to set exceeds the maximum fee.
                                  error MaxFeeExceeded();
                                  /// @notice Thrown when the value is already set.
                                  error AlreadySet();
                                  /// @notice Thrown when a value is already pending.
                                  error AlreadyPending();
                                  /// @notice Thrown when submitting the removal of a market when there is a cap already pending on that market.
                                  error PendingCap(Id id);
                                  /// @notice Thrown when submitting a cap for a market with a pending removal.
                                  error PendingRemoval();
                                  /// @notice Thrown when submitting a market removal for a market with a non zero cap.
                                  error NonZeroCap();
                                  /// @notice Thrown when market `id` is a duplicate in the new withdraw queue to set.
                                  error DuplicateMarket(Id id);
                                  /// @notice Thrown when market `id` is missing in the updated withdraw queue and the market has a non-zero cap set.
                                  error InvalidMarketRemovalNonZeroCap(Id id);
                                  /// @notice Thrown when market `id` is missing in the updated withdraw queue and the market has a non-zero supply.
                                  error InvalidMarketRemovalNonZeroSupply(Id id);
                                  /// @notice Thrown when market `id` is missing in the updated withdraw queue and the market is not yet disabled.
                                  error InvalidMarketRemovalTimelockNotElapsed(Id id);
                                  /// @notice Thrown when there's no pending value to set.
                                  error NoPendingValue();
                                  /// @notice Thrown when the requested liquidity cannot be withdrawn from Morpho.
                                  error NotEnoughLiquidity();
                                  /// @notice Thrown when submitting a cap for a market which does not exist.
                                  error MarketNotCreated();
                                  /// @notice Thrown when interacting with a non previously enabled market `id`.
                                  error MarketNotEnabled(Id id);
                                  /// @notice Thrown when the submitted timelock is above the max timelock.
                                  error AboveMaxTimelock();
                                  /// @notice Thrown when the submitted timelock is below the min timelock.
                                  error BelowMinTimelock();
                                  /// @notice Thrown when the timelock is not elapsed.
                                  error TimelockNotElapsed();
                                  /// @notice Thrown when too many markets are in the withdraw queue.
                                  error MaxQueueLengthExceeded();
                                  /// @notice Thrown when setting the fee to a non zero value while the fee recipient is the zero address.
                                  error ZeroFeeRecipient();
                                  /// @notice Thrown when the amount withdrawn is not exactly the amount supplied.
                                  error InconsistentReallocation();
                                  /// @notice Thrown when all caps have been reached.
                                  error AllCapsReached();
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id} from "../../lib/morpho-blue/src/interfaces/IMorpho.sol";
                              import {PendingAddress} from "./PendingLib.sol";
                              /// @title EventsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing events.
                              library EventsLib {
                                  /// @notice Emitted when the name of the vault is set.
                                  event SetName(string name);
                                  /// @notice Emitted when the symbol of the vault is set.
                                  event SetSymbol(string symbol);
                                  /// @notice Emitted when a pending `newTimelock` is submitted.
                                  event SubmitTimelock(uint256 newTimelock);
                                  /// @notice Emitted when `timelock` is set to `newTimelock`.
                                  event SetTimelock(address indexed caller, uint256 newTimelock);
                                  /// @notice Emitted when `skimRecipient` is set to `newSkimRecipient`.
                                  event SetSkimRecipient(address indexed newSkimRecipient);
                                  /// @notice Emitted `fee` is set to `newFee`.
                                  event SetFee(address indexed caller, uint256 newFee);
                                  /// @notice Emitted when a new `newFeeRecipient` is set.
                                  event SetFeeRecipient(address indexed newFeeRecipient);
                                  /// @notice Emitted when a pending `newGuardian` is submitted.
                                  event SubmitGuardian(address indexed newGuardian);
                                  /// @notice Emitted when `guardian` is set to `newGuardian`.
                                  event SetGuardian(address indexed caller, address indexed guardian);
                                  /// @notice Emitted when a pending `cap` is submitted for market identified by `id`.
                                  event SubmitCap(address indexed caller, Id indexed id, uint256 cap);
                                  /// @notice Emitted when a new `cap` is set for market identified by `id`.
                                  event SetCap(address indexed caller, Id indexed id, uint256 cap);
                                  /// @notice Emitted when the vault's last total assets is updated to `updatedTotalAssets`.
                                  event UpdateLastTotalAssets(uint256 updatedTotalAssets);
                                  /// @notice Emitted when the vault's lostAssets is updated to `newLostAssets`.
                                  event UpdateLostAssets(uint256 newLostAssets);
                                  /// @notice Emitted when the market identified by `id` is submitted for removal.
                                  event SubmitMarketRemoval(address indexed caller, Id indexed id);
                                  /// @notice Emitted when `curator` is set to `newCurator`.
                                  event SetCurator(address indexed newCurator);
                                  /// @notice Emitted when an `allocator` is set to `isAllocator`.
                                  event SetIsAllocator(address indexed allocator, bool isAllocator);
                                  /// @notice Emitted when a `pendingTimelock` is revoked.
                                  event RevokePendingTimelock(address indexed caller);
                                  /// @notice Emitted when a `pendingCap` for the market identified by `id` is revoked.
                                  event RevokePendingCap(address indexed caller, Id indexed id);
                                  /// @notice Emitted when a `pendingGuardian` is revoked.
                                  event RevokePendingGuardian(address indexed caller);
                                  /// @notice Emitted when a pending market removal is revoked.
                                  event RevokePendingMarketRemoval(address indexed caller, Id indexed id);
                                  /// @notice Emitted when the `supplyQueue` is set to `newSupplyQueue`.
                                  event SetSupplyQueue(address indexed caller, Id[] newSupplyQueue);
                                  /// @notice Emitted when the `withdrawQueue` is set to `newWithdrawQueue`.
                                  event SetWithdrawQueue(address indexed caller, Id[] newWithdrawQueue);
                                  /// @notice Emitted when a reallocation supplies assets to the market identified by `id`.
                                  /// @param id The id of the market.
                                  /// @param suppliedAssets The amount of assets supplied to the market.
                                  /// @param suppliedShares The amount of shares minted.
                                  event ReallocateSupply(address indexed caller, Id indexed id, uint256 suppliedAssets, uint256 suppliedShares);
                                  /// @notice Emitted when a reallocation withdraws assets from the market identified by `id`.
                                  /// @param id The id of the market.
                                  /// @param withdrawnAssets The amount of assets withdrawn from the market.
                                  /// @param withdrawnShares The amount of shares burned.
                                  event ReallocateWithdraw(address indexed caller, Id indexed id, uint256 withdrawnAssets, uint256 withdrawnShares);
                                  /// @notice Emitted when interest are accrued.
                                  /// @param newTotalAssets The assets of the vault after accruing the interest but before the interaction.
                                  /// @param feeShares The shares minted to the fee recipient.
                                  event AccrueInterest(uint256 newTotalAssets, uint256 feeShares);
                                  /// @notice Emitted when an `amount` of `token` is transferred to the skim recipient by `caller`.
                                  event Skim(address indexed caller, address indexed token, uint256 amount);
                                  /// @notice Emitted when a new MetaMorphoV1_1 vault is created.
                                  /// @param metaMorpho The address of the MetaMorphoV1_1 vault.
                                  /// @param caller The caller of the function.
                                  /// @param initialOwner The initial owner of the MetaMorphoV1_1 vault.
                                  /// @param initialTimelock The initial timelock of the MetaMorphoV1_1 vault.
                                  /// @param asset The address of the underlying asset.
                                  /// @param name The name of the MetaMorphoV1_1 vault.
                                  /// @param symbol The symbol of the MetaMorphoV1_1 vault.
                                  /// @param salt The salt used for the MetaMorphoV1_1 vault's CREATE2 address.
                                  event CreateMetaMorpho(
                                      address indexed metaMorpho,
                                      address indexed caller,
                                      address initialOwner,
                                      uint256 initialTimelock,
                                      address indexed asset,
                                      string name,
                                      string symbol,
                                      bytes32 salt
                                  );
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              uint256 constant WAD = 1e18;
                              /// @title MathLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to manage fixed-point arithmetic.
                              library MathLib {
                                  /// @dev Returns (`x` * `y`) / `WAD` rounded down.
                                  function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivDown(x, y, WAD);
                                  }
                                  /// @dev Returns (`x` * `WAD`) / `y` rounded down.
                                  function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivDown(x, WAD, y);
                                  }
                                  /// @dev Returns (`x` * `WAD`) / `y` rounded up.
                                  function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivUp(x, WAD, y);
                                  }
                                  /// @dev Returns (`x` * `y`) / `d` rounded down.
                                  function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
                                      return (x * y) / d;
                                  }
                                  /// @dev Returns (`x` * `y`) / `d` rounded up.
                                  function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
                                      return (x * y + (d - 1)) / d;
                                  }
                                  /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
                                  /// continuous compound interest rate.
                                  function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
                                      uint256 firstTerm = x * n;
                                      uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
                                      uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);
                                      return firstTerm + secondTerm + thirdTerm;
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {ErrorsLib} from "../libraries/ErrorsLib.sol";
                              /// @title UtilsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing helpers.
                              /// @dev Inspired by https://github.com/morpho-org/morpho-utils.
                              library UtilsLib {
                                  /// @dev Returns true if there is exactly one zero among `x` and `y`.
                                  function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
                                      assembly {
                                          z := xor(iszero(x), iszero(y))
                                      }
                                  }
                                  /// @dev Returns the min of `x` and `y`.
                                  function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                      assembly {
                                          z := xor(x, mul(xor(x, y), lt(y, x)))
                                      }
                                  }
                                  /// @dev Returns `x` safely cast to uint128.
                                  function toUint128(uint256 x) internal pure returns (uint128) {
                                      require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);
                                      return uint128(x);
                                  }
                                  /// @dev Returns max(0, x - y).
                                  function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                      assembly {
                                          z := mul(gt(x, y), sub(x, y))
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol)
                              // This file was procedurally generated from scripts/generate/templates/SafeCast.js.
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
                               * checks.
                               *
                               * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
                               * easily result in undesired exploitation or bugs, since developers usually
                               * assume that overflows raise errors. `SafeCast` restores this intuition by
                               * reverting the transaction when such an operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeCast {
                                  /**
                                   * @dev Value doesn't fit in an uint of `bits` size.
                                   */
                                  error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
                                  /**
                                   * @dev An int value doesn't fit in an uint of `bits` size.
                                   */
                                  error SafeCastOverflowedIntToUint(int256 value);
                                  /**
                                   * @dev Value doesn't fit in an int of `bits` size.
                                   */
                                  error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
                                  /**
                                   * @dev An uint value doesn't fit in an int of `bits` size.
                                   */
                                  error SafeCastOverflowedUintToInt(uint256 value);
                                  /**
                                   * @dev Returns the downcasted uint248 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint248).
                                   *
                                   * Counterpart to Solidity's `uint248` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 248 bits
                                   */
                                  function toUint248(uint256 value) internal pure returns (uint248) {
                                      if (value > type(uint248).max) {
                                          revert SafeCastOverflowedUintDowncast(248, value);
                                      }
                                      return uint248(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint240 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint240).
                                   *
                                   * Counterpart to Solidity's `uint240` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 240 bits
                                   */
                                  function toUint240(uint256 value) internal pure returns (uint240) {
                                      if (value > type(uint240).max) {
                                          revert SafeCastOverflowedUintDowncast(240, value);
                                      }
                                      return uint240(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint232 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint232).
                                   *
                                   * Counterpart to Solidity's `uint232` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 232 bits
                                   */
                                  function toUint232(uint256 value) internal pure returns (uint232) {
                                      if (value > type(uint232).max) {
                                          revert SafeCastOverflowedUintDowncast(232, value);
                                      }
                                      return uint232(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint224 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint224).
                                   *
                                   * Counterpart to Solidity's `uint224` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 224 bits
                                   */
                                  function toUint224(uint256 value) internal pure returns (uint224) {
                                      if (value > type(uint224).max) {
                                          revert SafeCastOverflowedUintDowncast(224, value);
                                      }
                                      return uint224(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint216 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint216).
                                   *
                                   * Counterpart to Solidity's `uint216` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 216 bits
                                   */
                                  function toUint216(uint256 value) internal pure returns (uint216) {
                                      if (value > type(uint216).max) {
                                          revert SafeCastOverflowedUintDowncast(216, value);
                                      }
                                      return uint216(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint208 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint208).
                                   *
                                   * Counterpart to Solidity's `uint208` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 208 bits
                                   */
                                  function toUint208(uint256 value) internal pure returns (uint208) {
                                      if (value > type(uint208).max) {
                                          revert SafeCastOverflowedUintDowncast(208, value);
                                      }
                                      return uint208(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint200 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint200).
                                   *
                                   * Counterpart to Solidity's `uint200` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 200 bits
                                   */
                                  function toUint200(uint256 value) internal pure returns (uint200) {
                                      if (value > type(uint200).max) {
                                          revert SafeCastOverflowedUintDowncast(200, value);
                                      }
                                      return uint200(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint192 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint192).
                                   *
                                   * Counterpart to Solidity's `uint192` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 192 bits
                                   */
                                  function toUint192(uint256 value) internal pure returns (uint192) {
                                      if (value > type(uint192).max) {
                                          revert SafeCastOverflowedUintDowncast(192, value);
                                      }
                                      return uint192(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint184 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint184).
                                   *
                                   * Counterpart to Solidity's `uint184` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 184 bits
                                   */
                                  function toUint184(uint256 value) internal pure returns (uint184) {
                                      if (value > type(uint184).max) {
                                          revert SafeCastOverflowedUintDowncast(184, value);
                                      }
                                      return uint184(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint176 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint176).
                                   *
                                   * Counterpart to Solidity's `uint176` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 176 bits
                                   */
                                  function toUint176(uint256 value) internal pure returns (uint176) {
                                      if (value > type(uint176).max) {
                                          revert SafeCastOverflowedUintDowncast(176, value);
                                      }
                                      return uint176(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint168 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint168).
                                   *
                                   * Counterpart to Solidity's `uint168` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 168 bits
                                   */
                                  function toUint168(uint256 value) internal pure returns (uint168) {
                                      if (value > type(uint168).max) {
                                          revert SafeCastOverflowedUintDowncast(168, value);
                                      }
                                      return uint168(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint160 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint160).
                                   *
                                   * Counterpart to Solidity's `uint160` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 160 bits
                                   */
                                  function toUint160(uint256 value) internal pure returns (uint160) {
                                      if (value > type(uint160).max) {
                                          revert SafeCastOverflowedUintDowncast(160, value);
                                      }
                                      return uint160(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint152 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint152).
                                   *
                                   * Counterpart to Solidity's `uint152` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 152 bits
                                   */
                                  function toUint152(uint256 value) internal pure returns (uint152) {
                                      if (value > type(uint152).max) {
                                          revert SafeCastOverflowedUintDowncast(152, value);
                                      }
                                      return uint152(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint144 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint144).
                                   *
                                   * Counterpart to Solidity's `uint144` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 144 bits
                                   */
                                  function toUint144(uint256 value) internal pure returns (uint144) {
                                      if (value > type(uint144).max) {
                                          revert SafeCastOverflowedUintDowncast(144, value);
                                      }
                                      return uint144(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint136 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint136).
                                   *
                                   * Counterpart to Solidity's `uint136` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 136 bits
                                   */
                                  function toUint136(uint256 value) internal pure returns (uint136) {
                                      if (value > type(uint136).max) {
                                          revert SafeCastOverflowedUintDowncast(136, value);
                                      }
                                      return uint136(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint128 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint128).
                                   *
                                   * Counterpart to Solidity's `uint128` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 128 bits
                                   */
                                  function toUint128(uint256 value) internal pure returns (uint128) {
                                      if (value > type(uint128).max) {
                                          revert SafeCastOverflowedUintDowncast(128, value);
                                      }
                                      return uint128(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint120 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint120).
                                   *
                                   * Counterpart to Solidity's `uint120` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 120 bits
                                   */
                                  function toUint120(uint256 value) internal pure returns (uint120) {
                                      if (value > type(uint120).max) {
                                          revert SafeCastOverflowedUintDowncast(120, value);
                                      }
                                      return uint120(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint112 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint112).
                                   *
                                   * Counterpart to Solidity's `uint112` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 112 bits
                                   */
                                  function toUint112(uint256 value) internal pure returns (uint112) {
                                      if (value > type(uint112).max) {
                                          revert SafeCastOverflowedUintDowncast(112, value);
                                      }
                                      return uint112(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint104 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint104).
                                   *
                                   * Counterpart to Solidity's `uint104` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 104 bits
                                   */
                                  function toUint104(uint256 value) internal pure returns (uint104) {
                                      if (value > type(uint104).max) {
                                          revert SafeCastOverflowedUintDowncast(104, value);
                                      }
                                      return uint104(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint96 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint96).
                                   *
                                   * Counterpart to Solidity's `uint96` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 96 bits
                                   */
                                  function toUint96(uint256 value) internal pure returns (uint96) {
                                      if (value > type(uint96).max) {
                                          revert SafeCastOverflowedUintDowncast(96, value);
                                      }
                                      return uint96(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint88 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint88).
                                   *
                                   * Counterpart to Solidity's `uint88` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 88 bits
                                   */
                                  function toUint88(uint256 value) internal pure returns (uint88) {
                                      if (value > type(uint88).max) {
                                          revert SafeCastOverflowedUintDowncast(88, value);
                                      }
                                      return uint88(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint80 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint80).
                                   *
                                   * Counterpart to Solidity's `uint80` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 80 bits
                                   */
                                  function toUint80(uint256 value) internal pure returns (uint80) {
                                      if (value > type(uint80).max) {
                                          revert SafeCastOverflowedUintDowncast(80, value);
                                      }
                                      return uint80(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint72 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint72).
                                   *
                                   * Counterpart to Solidity's `uint72` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 72 bits
                                   */
                                  function toUint72(uint256 value) internal pure returns (uint72) {
                                      if (value > type(uint72).max) {
                                          revert SafeCastOverflowedUintDowncast(72, value);
                                      }
                                      return uint72(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint64 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint64).
                                   *
                                   * Counterpart to Solidity's `uint64` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 64 bits
                                   */
                                  function toUint64(uint256 value) internal pure returns (uint64) {
                                      if (value > type(uint64).max) {
                                          revert SafeCastOverflowedUintDowncast(64, value);
                                      }
                                      return uint64(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint56 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint56).
                                   *
                                   * Counterpart to Solidity's `uint56` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 56 bits
                                   */
                                  function toUint56(uint256 value) internal pure returns (uint56) {
                                      if (value > type(uint56).max) {
                                          revert SafeCastOverflowedUintDowncast(56, value);
                                      }
                                      return uint56(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint48 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint48).
                                   *
                                   * Counterpart to Solidity's `uint48` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 48 bits
                                   */
                                  function toUint48(uint256 value) internal pure returns (uint48) {
                                      if (value > type(uint48).max) {
                                          revert SafeCastOverflowedUintDowncast(48, value);
                                      }
                                      return uint48(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint40 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint40).
                                   *
                                   * Counterpart to Solidity's `uint40` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 40 bits
                                   */
                                  function toUint40(uint256 value) internal pure returns (uint40) {
                                      if (value > type(uint40).max) {
                                          revert SafeCastOverflowedUintDowncast(40, value);
                                      }
                                      return uint40(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint32 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint32).
                                   *
                                   * Counterpart to Solidity's `uint32` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 32 bits
                                   */
                                  function toUint32(uint256 value) internal pure returns (uint32) {
                                      if (value > type(uint32).max) {
                                          revert SafeCastOverflowedUintDowncast(32, value);
                                      }
                                      return uint32(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint24 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint24).
                                   *
                                   * Counterpart to Solidity's `uint24` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 24 bits
                                   */
                                  function toUint24(uint256 value) internal pure returns (uint24) {
                                      if (value > type(uint24).max) {
                                          revert SafeCastOverflowedUintDowncast(24, value);
                                      }
                                      return uint24(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint16 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint16).
                                   *
                                   * Counterpart to Solidity's `uint16` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 16 bits
                                   */
                                  function toUint16(uint256 value) internal pure returns (uint16) {
                                      if (value > type(uint16).max) {
                                          revert SafeCastOverflowedUintDowncast(16, value);
                                      }
                                      return uint16(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted uint8 from uint256, reverting on
                                   * overflow (when the input is greater than largest uint8).
                                   *
                                   * Counterpart to Solidity's `uint8` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 8 bits
                                   */
                                  function toUint8(uint256 value) internal pure returns (uint8) {
                                      if (value > type(uint8).max) {
                                          revert SafeCastOverflowedUintDowncast(8, value);
                                      }
                                      return uint8(value);
                                  }
                                  /**
                                   * @dev Converts a signed int256 into an unsigned uint256.
                                   *
                                   * Requirements:
                                   *
                                   * - input must be greater than or equal to 0.
                                   */
                                  function toUint256(int256 value) internal pure returns (uint256) {
                                      if (value < 0) {
                                          revert SafeCastOverflowedIntToUint(value);
                                      }
                                      return uint256(value);
                                  }
                                  /**
                                   * @dev Returns the downcasted int248 from int256, reverting on
                                   * overflow (when the input is less than smallest int248 or
                                   * greater than largest int248).
                                   *
                                   * Counterpart to Solidity's `int248` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 248 bits
                                   */
                                  function toInt248(int256 value) internal pure returns (int248 downcasted) {
                                      downcasted = int248(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(248, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int240 from int256, reverting on
                                   * overflow (when the input is less than smallest int240 or
                                   * greater than largest int240).
                                   *
                                   * Counterpart to Solidity's `int240` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 240 bits
                                   */
                                  function toInt240(int256 value) internal pure returns (int240 downcasted) {
                                      downcasted = int240(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(240, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int232 from int256, reverting on
                                   * overflow (when the input is less than smallest int232 or
                                   * greater than largest int232).
                                   *
                                   * Counterpart to Solidity's `int232` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 232 bits
                                   */
                                  function toInt232(int256 value) internal pure returns (int232 downcasted) {
                                      downcasted = int232(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(232, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int224 from int256, reverting on
                                   * overflow (when the input is less than smallest int224 or
                                   * greater than largest int224).
                                   *
                                   * Counterpart to Solidity's `int224` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 224 bits
                                   */
                                  function toInt224(int256 value) internal pure returns (int224 downcasted) {
                                      downcasted = int224(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(224, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int216 from int256, reverting on
                                   * overflow (when the input is less than smallest int216 or
                                   * greater than largest int216).
                                   *
                                   * Counterpart to Solidity's `int216` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 216 bits
                                   */
                                  function toInt216(int256 value) internal pure returns (int216 downcasted) {
                                      downcasted = int216(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(216, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int208 from int256, reverting on
                                   * overflow (when the input is less than smallest int208 or
                                   * greater than largest int208).
                                   *
                                   * Counterpart to Solidity's `int208` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 208 bits
                                   */
                                  function toInt208(int256 value) internal pure returns (int208 downcasted) {
                                      downcasted = int208(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(208, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int200 from int256, reverting on
                                   * overflow (when the input is less than smallest int200 or
                                   * greater than largest int200).
                                   *
                                   * Counterpart to Solidity's `int200` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 200 bits
                                   */
                                  function toInt200(int256 value) internal pure returns (int200 downcasted) {
                                      downcasted = int200(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(200, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int192 from int256, reverting on
                                   * overflow (when the input is less than smallest int192 or
                                   * greater than largest int192).
                                   *
                                   * Counterpart to Solidity's `int192` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 192 bits
                                   */
                                  function toInt192(int256 value) internal pure returns (int192 downcasted) {
                                      downcasted = int192(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(192, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int184 from int256, reverting on
                                   * overflow (when the input is less than smallest int184 or
                                   * greater than largest int184).
                                   *
                                   * Counterpart to Solidity's `int184` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 184 bits
                                   */
                                  function toInt184(int256 value) internal pure returns (int184 downcasted) {
                                      downcasted = int184(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(184, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int176 from int256, reverting on
                                   * overflow (when the input is less than smallest int176 or
                                   * greater than largest int176).
                                   *
                                   * Counterpart to Solidity's `int176` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 176 bits
                                   */
                                  function toInt176(int256 value) internal pure returns (int176 downcasted) {
                                      downcasted = int176(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(176, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int168 from int256, reverting on
                                   * overflow (when the input is less than smallest int168 or
                                   * greater than largest int168).
                                   *
                                   * Counterpart to Solidity's `int168` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 168 bits
                                   */
                                  function toInt168(int256 value) internal pure returns (int168 downcasted) {
                                      downcasted = int168(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(168, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int160 from int256, reverting on
                                   * overflow (when the input is less than smallest int160 or
                                   * greater than largest int160).
                                   *
                                   * Counterpart to Solidity's `int160` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 160 bits
                                   */
                                  function toInt160(int256 value) internal pure returns (int160 downcasted) {
                                      downcasted = int160(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(160, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int152 from int256, reverting on
                                   * overflow (when the input is less than smallest int152 or
                                   * greater than largest int152).
                                   *
                                   * Counterpart to Solidity's `int152` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 152 bits
                                   */
                                  function toInt152(int256 value) internal pure returns (int152 downcasted) {
                                      downcasted = int152(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(152, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int144 from int256, reverting on
                                   * overflow (when the input is less than smallest int144 or
                                   * greater than largest int144).
                                   *
                                   * Counterpart to Solidity's `int144` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 144 bits
                                   */
                                  function toInt144(int256 value) internal pure returns (int144 downcasted) {
                                      downcasted = int144(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(144, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int136 from int256, reverting on
                                   * overflow (when the input is less than smallest int136 or
                                   * greater than largest int136).
                                   *
                                   * Counterpart to Solidity's `int136` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 136 bits
                                   */
                                  function toInt136(int256 value) internal pure returns (int136 downcasted) {
                                      downcasted = int136(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(136, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int128 from int256, reverting on
                                   * overflow (when the input is less than smallest int128 or
                                   * greater than largest int128).
                                   *
                                   * Counterpart to Solidity's `int128` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 128 bits
                                   */
                                  function toInt128(int256 value) internal pure returns (int128 downcasted) {
                                      downcasted = int128(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(128, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int120 from int256, reverting on
                                   * overflow (when the input is less than smallest int120 or
                                   * greater than largest int120).
                                   *
                                   * Counterpart to Solidity's `int120` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 120 bits
                                   */
                                  function toInt120(int256 value) internal pure returns (int120 downcasted) {
                                      downcasted = int120(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(120, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int112 from int256, reverting on
                                   * overflow (when the input is less than smallest int112 or
                                   * greater than largest int112).
                                   *
                                   * Counterpart to Solidity's `int112` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 112 bits
                                   */
                                  function toInt112(int256 value) internal pure returns (int112 downcasted) {
                                      downcasted = int112(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(112, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int104 from int256, reverting on
                                   * overflow (when the input is less than smallest int104 or
                                   * greater than largest int104).
                                   *
                                   * Counterpart to Solidity's `int104` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 104 bits
                                   */
                                  function toInt104(int256 value) internal pure returns (int104 downcasted) {
                                      downcasted = int104(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(104, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int96 from int256, reverting on
                                   * overflow (when the input is less than smallest int96 or
                                   * greater than largest int96).
                                   *
                                   * Counterpart to Solidity's `int96` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 96 bits
                                   */
                                  function toInt96(int256 value) internal pure returns (int96 downcasted) {
                                      downcasted = int96(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(96, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int88 from int256, reverting on
                                   * overflow (when the input is less than smallest int88 or
                                   * greater than largest int88).
                                   *
                                   * Counterpart to Solidity's `int88` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 88 bits
                                   */
                                  function toInt88(int256 value) internal pure returns (int88 downcasted) {
                                      downcasted = int88(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(88, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int80 from int256, reverting on
                                   * overflow (when the input is less than smallest int80 or
                                   * greater than largest int80).
                                   *
                                   * Counterpart to Solidity's `int80` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 80 bits
                                   */
                                  function toInt80(int256 value) internal pure returns (int80 downcasted) {
                                      downcasted = int80(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(80, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int72 from int256, reverting on
                                   * overflow (when the input is less than smallest int72 or
                                   * greater than largest int72).
                                   *
                                   * Counterpart to Solidity's `int72` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 72 bits
                                   */
                                  function toInt72(int256 value) internal pure returns (int72 downcasted) {
                                      downcasted = int72(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(72, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int64 from int256, reverting on
                                   * overflow (when the input is less than smallest int64 or
                                   * greater than largest int64).
                                   *
                                   * Counterpart to Solidity's `int64` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 64 bits
                                   */
                                  function toInt64(int256 value) internal pure returns (int64 downcasted) {
                                      downcasted = int64(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(64, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int56 from int256, reverting on
                                   * overflow (when the input is less than smallest int56 or
                                   * greater than largest int56).
                                   *
                                   * Counterpart to Solidity's `int56` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 56 bits
                                   */
                                  function toInt56(int256 value) internal pure returns (int56 downcasted) {
                                      downcasted = int56(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(56, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int48 from int256, reverting on
                                   * overflow (when the input is less than smallest int48 or
                                   * greater than largest int48).
                                   *
                                   * Counterpart to Solidity's `int48` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 48 bits
                                   */
                                  function toInt48(int256 value) internal pure returns (int48 downcasted) {
                                      downcasted = int48(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(48, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int40 from int256, reverting on
                                   * overflow (when the input is less than smallest int40 or
                                   * greater than largest int40).
                                   *
                                   * Counterpart to Solidity's `int40` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 40 bits
                                   */
                                  function toInt40(int256 value) internal pure returns (int40 downcasted) {
                                      downcasted = int40(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(40, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int32 from int256, reverting on
                                   * overflow (when the input is less than smallest int32 or
                                   * greater than largest int32).
                                   *
                                   * Counterpart to Solidity's `int32` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 32 bits
                                   */
                                  function toInt32(int256 value) internal pure returns (int32 downcasted) {
                                      downcasted = int32(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(32, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int24 from int256, reverting on
                                   * overflow (when the input is less than smallest int24 or
                                   * greater than largest int24).
                                   *
                                   * Counterpart to Solidity's `int24` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 24 bits
                                   */
                                  function toInt24(int256 value) internal pure returns (int24 downcasted) {
                                      downcasted = int24(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(24, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int16 from int256, reverting on
                                   * overflow (when the input is less than smallest int16 or
                                   * greater than largest int16).
                                   *
                                   * Counterpart to Solidity's `int16` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 16 bits
                                   */
                                  function toInt16(int256 value) internal pure returns (int16 downcasted) {
                                      downcasted = int16(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(16, value);
                                      }
                                  }
                                  /**
                                   * @dev Returns the downcasted int8 from int256, reverting on
                                   * overflow (when the input is less than smallest int8 or
                                   * greater than largest int8).
                                   *
                                   * Counterpart to Solidity's `int8` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - input must fit into 8 bits
                                   */
                                  function toInt8(int256 value) internal pure returns (int8 downcasted) {
                                      downcasted = int8(value);
                                      if (downcasted != value) {
                                          revert SafeCastOverflowedIntDowncast(8, value);
                                      }
                                  }
                                  /**
                                   * @dev Converts an unsigned uint256 into a signed int256.
                                   *
                                   * Requirements:
                                   *
                                   * - input must be less than or equal to maxInt256.
                                   */
                                  function toInt256(uint256 value) internal pure returns (int256) {
                                      // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
                                      if (value > uint256(type(int256).max)) {
                                          revert SafeCastOverflowedUintToInt(value);
                                      }
                                      return int256(value);
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {MathLib} from "./MathLib.sol";
                              /// @title SharesMathLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Shares management library.
                              /// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
                              /// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
                              library SharesMathLib {
                                  using MathLib for uint256;
                                  /// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
                                  /// high precision computations.
                                  /// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
                                  /// stays low enough not to inflate these assets to a significant value.
                                  /// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
                                  uint256 internal constant VIRTUAL_SHARES = 1e6;
                                  /// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
                                  /// empty.
                                  uint256 internal constant VIRTUAL_ASSETS = 1;
                                  /// @dev Calculates the value of `assets` quoted in shares, rounding down.
                                  function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
                                  }
                                  /// @dev Calculates the value of `shares` quoted in assets, rounding down.
                                  function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
                                  }
                                  /// @dev Calculates the value of `assets` quoted in shares, rounding up.
                                  function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
                                  }
                                  /// @dev Calculates the value of `shares` quoted in assets, rounding up.
                                  function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {IMorpho, Id} from "../../interfaces/IMorpho.sol";
                              import {MorphoStorageLib} from "./MorphoStorageLib.sol";
                              /// @title MorphoLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Helper library to access Morpho storage variables.
                              /// @dev Warning: Supply and borrow getters may return outdated values that do not include accrued interest.
                              library MorphoLib {
                                  function supplyShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.positionSupplySharesSlot(id, user));
                                      return uint256(morpho.extSloads(slot)[0]);
                                  }
                                  function borrowShares(IMorpho morpho, Id id, address user) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));
                                      return uint128(uint256(morpho.extSloads(slot)[0]));
                                  }
                                  function collateral(IMorpho morpho, Id id, address user) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.positionBorrowSharesAndCollateralSlot(id, user));
                                      return uint256(morpho.extSloads(slot)[0] >> 128);
                                  }
                                  function totalSupplyAssets(IMorpho morpho, Id id) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));
                                      return uint128(uint256(morpho.extSloads(slot)[0]));
                                  }
                                  function totalSupplyShares(IMorpho morpho, Id id) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.marketTotalSupplyAssetsAndSharesSlot(id));
                                      return uint256(morpho.extSloads(slot)[0] >> 128);
                                  }
                                  function totalBorrowAssets(IMorpho morpho, Id id) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));
                                      return uint128(uint256(morpho.extSloads(slot)[0]));
                                  }
                                  function totalBorrowShares(IMorpho morpho, Id id) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.marketTotalBorrowAssetsAndSharesSlot(id));
                                      return uint256(morpho.extSloads(slot)[0] >> 128);
                                  }
                                  function lastUpdate(IMorpho morpho, Id id) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));
                                      return uint128(uint256(morpho.extSloads(slot)[0]));
                                  }
                                  function fee(IMorpho morpho, Id id) internal view returns (uint256) {
                                      bytes32[] memory slot = _array(MorphoStorageLib.marketLastUpdateAndFeeSlot(id));
                                      return uint256(morpho.extSloads(slot)[0] >> 128);
                                  }
                                  function _array(bytes32 x) private pure returns (bytes32[] memory) {
                                      bytes32[] memory res = new bytes32[](1);
                                      res[0] = x;
                                      return res;
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id, MarketParams} from "../interfaces/IMorpho.sol";
                              /// @title MarketParamsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to convert a market to its id.
                              library MarketParamsLib {
                                  /// @notice The length of the data used to compute the id of a market.
                                  /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
                                  uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;
                                  /// @notice Returns the id of the market `marketParams`.
                                  function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
                                      assembly ("memory-safe") {
                                          marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
                              pragma solidity ^0.8.20;
                              import {IERC20} from "../IERC20.sol";
                              /**
                               * @dev Interface for the optional metadata functions from the ERC20 standard.
                               */
                              interface IERC20Metadata is IERC20 {
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() external view returns (string memory);
                                  /**
                                   * @dev Returns the symbol of the token.
                                   */
                                  function symbol() external view returns (string memory);
                                  /**
                                   * @dev Returns the decimals places of the token.
                                   */
                                  function decimals() external view returns (uint8);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id, MarketParams, Market, IMorpho} from "../../interfaces/IMorpho.sol";
                              import {IIrm} from "../../interfaces/IIrm.sol";
                              import {MathLib} from "../MathLib.sol";
                              import {UtilsLib} from "../UtilsLib.sol";
                              import {MorphoLib} from "./MorphoLib.sol";
                              import {SharesMathLib} from "../SharesMathLib.sol";
                              import {MarketParamsLib} from "../MarketParamsLib.sol";
                              /// @title MorphoBalancesLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Helper library exposing getters with the expected value after interest accrual.
                              /// @dev This library is not used in Morpho itself and is intended to be used by integrators.
                              /// @dev The getter to retrieve the expected total borrow shares is not exposed because interest accrual does not apply
                              /// to it. The value can be queried directly on Morpho using `totalBorrowShares`.
                              library MorphoBalancesLib {
                                  using MathLib for uint256;
                                  using MathLib for uint128;
                                  using UtilsLib for uint256;
                                  using MorphoLib for IMorpho;
                                  using SharesMathLib for uint256;
                                  using MarketParamsLib for MarketParams;
                                  /// @notice Returns the expected market balances of a market after having accrued interest.
                                  /// @return The expected total supply assets.
                                  /// @return The expected total supply shares.
                                  /// @return The expected total borrow assets.
                                  /// @return The expected total borrow shares.
                                  function expectedMarketBalances(IMorpho morpho, MarketParams memory marketParams)
                                      internal
                                      view
                                      returns (uint256, uint256, uint256, uint256)
                                  {
                                      Id id = marketParams.id();
                                      Market memory market = morpho.market(id);
                                      uint256 elapsed = block.timestamp - market.lastUpdate;
                                      // Skipped if elapsed == 0 or totalBorrowAssets == 0 because interest would be null, or if irm == address(0).
                                      if (elapsed != 0 && market.totalBorrowAssets != 0 && marketParams.irm != address(0)) {
                                          uint256 borrowRate = IIrm(marketParams.irm).borrowRateView(marketParams, market);
                                          uint256 interest = market.totalBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));
                                          market.totalBorrowAssets += interest.toUint128();
                                          market.totalSupplyAssets += interest.toUint128();
                                          if (market.fee != 0) {
                                              uint256 feeAmount = interest.wMulDown(market.fee);
                                              // The fee amount is subtracted from the total supply in this calculation to compensate for the fact
                                              // that total supply is already updated.
                                              uint256 feeShares =
                                                  feeAmount.toSharesDown(market.totalSupplyAssets - feeAmount, market.totalSupplyShares);
                                              market.totalSupplyShares += feeShares.toUint128();
                                          }
                                      }
                                      return (market.totalSupplyAssets, market.totalSupplyShares, market.totalBorrowAssets, market.totalBorrowShares);
                                  }
                                  /// @notice Returns the expected total supply assets of a market after having accrued interest.
                                  function expectedTotalSupplyAssets(IMorpho morpho, MarketParams memory marketParams)
                                      internal
                                      view
                                      returns (uint256 totalSupplyAssets)
                                  {
                                      (totalSupplyAssets,,,) = expectedMarketBalances(morpho, marketParams);
                                  }
                                  /// @notice Returns the expected total borrow assets of a market after having accrued interest.
                                  function expectedTotalBorrowAssets(IMorpho morpho, MarketParams memory marketParams)
                                      internal
                                      view
                                      returns (uint256 totalBorrowAssets)
                                  {
                                      (,, totalBorrowAssets,) = expectedMarketBalances(morpho, marketParams);
                                  }
                                  /// @notice Returns the expected total supply shares of a market after having accrued interest.
                                  function expectedTotalSupplyShares(IMorpho morpho, MarketParams memory marketParams)
                                      internal
                                      view
                                      returns (uint256 totalSupplyShares)
                                  {
                                      (, totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);
                                  }
                                  /// @notice Returns the expected supply assets balance of `user` on a market after having accrued interest.
                                  /// @dev Warning: Wrong for `feeRecipient` because their supply shares increase is not taken into account.
                                  /// @dev Warning: Withdrawing using the expected supply assets can lead to a revert due to conversion roundings from
                                  /// assets to shares.
                                  function expectedSupplyAssets(IMorpho morpho, MarketParams memory marketParams, address user)
                                      internal
                                      view
                                      returns (uint256)
                                  {
                                      Id id = marketParams.id();
                                      uint256 supplyShares = morpho.supplyShares(id, user);
                                      (uint256 totalSupplyAssets, uint256 totalSupplyShares,,) = expectedMarketBalances(morpho, marketParams);
                                      return supplyShares.toAssetsDown(totalSupplyAssets, totalSupplyShares);
                                  }
                                  /// @notice Returns the expected borrow assets balance of `user` on a market after having accrued interest.
                                  /// @dev Warning: The expected balance is rounded up, so it may be greater than the market's expected total borrow
                                  /// assets.
                                  function expectedBorrowAssets(IMorpho morpho, MarketParams memory marketParams, address user)
                                      internal
                                      view
                                      returns (uint256)
                                  {
                                      Id id = marketParams.id();
                                      uint256 borrowShares = morpho.borrowShares(id, user);
                                      (,, uint256 totalBorrowAssets, uint256 totalBorrowShares) = expectedMarketBalances(morpho, marketParams);
                                      return borrowShares.toAssetsUp(totalBorrowAssets, totalBorrowShares);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/Multicall.sol)
                              pragma solidity ^0.8.20;
                              import {Address} from "./Address.sol";
                              /**
                               * @dev Provides a function to batch together multiple calls in a single external call.
                               */
                              abstract contract Multicall {
                                  /**
                                   * @dev Receives and executes a batch of function calls on this contract.
                                   * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
                                   */
                                  function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
                                      results = new bytes[](data.length);
                                      for (uint256 i = 0; i < data.length; i++) {
                                          results[i] = Address.functionDelegateCall(address(this), data[i]);
                                      }
                                      return results;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
                              pragma solidity ^0.8.20;
                              import {Ownable} from "./Ownable.sol";
                              /**
                               * @dev Contract module which provides access control mechanism, where
                               * there is an account (an owner) that can be granted exclusive access to
                               * specific functions.
                               *
                               * The initial owner is specified at deployment time in the constructor for `Ownable`. This
                               * can later be changed with {transferOwnership} and {acceptOwnership}.
                               *
                               * This module is used through inheritance. It will make available all functions
                               * from parent (Ownable).
                               */
                              abstract contract Ownable2Step is Ownable {
                                  address private _pendingOwner;
                                  event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
                                  /**
                                   * @dev Returns the address of the pending owner.
                                   */
                                  function pendingOwner() public view virtual returns (address) {
                                      return _pendingOwner;
                                  }
                                  /**
                                   * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
                                   * Can only be called by the current owner.
                                   */
                                  function transferOwnership(address newOwner) public virtual override onlyOwner {
                                      _pendingOwner = newOwner;
                                      emit OwnershipTransferStarted(owner(), newOwner);
                                  }
                                  /**
                                   * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
                                   * Internal function without access restriction.
                                   */
                                  function _transferOwnership(address newOwner) internal virtual override {
                                      delete _pendingOwner;
                                      super._transferOwnership(newOwner);
                                  }
                                  /**
                                   * @dev The new owner accepts the ownership transfer.
                                   */
                                  function acceptOwnership() public virtual {
                                      address sender = _msgSender();
                                      if (pendingOwner() != sender) {
                                          revert OwnableUnauthorizedAccount(sender);
                                      }
                                      _transferOwnership(sender);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol)
                              pragma solidity ^0.8.20;
                              import {IERC20Permit} from "./IERC20Permit.sol";
                              import {ERC20} from "../ERC20.sol";
                              import {ECDSA} from "../../../utils/cryptography/ECDSA.sol";
                              import {EIP712} from "../../../utils/cryptography/EIP712.sol";
                              import {Nonces} from "../../../utils/Nonces.sol";
                              /**
                               * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                               * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                               *
                               * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                               * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
                               * need to send a transaction, and thus is not required to hold Ether at all.
                               */
                              abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces {
                                  bytes32 private constant PERMIT_TYPEHASH =
                                      keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
                                  /**
                                   * @dev Permit deadline has expired.
                                   */
                                  error ERC2612ExpiredSignature(uint256 deadline);
                                  /**
                                   * @dev Mismatched signature.
                                   */
                                  error ERC2612InvalidSigner(address signer, address owner);
                                  /**
                                   * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
                                   *
                                   * It's a good idea to use the same `name` that is defined as the ERC20 token name.
                                   */
                                  constructor(string memory name) EIP712(name, "1") {}
                                  /**
                                   * @inheritdoc IERC20Permit
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) public virtual {
                                      if (block.timestamp > deadline) {
                                          revert ERC2612ExpiredSignature(deadline);
                                      }
                                      bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
                                      bytes32 hash = _hashTypedDataV4(structHash);
                                      address signer = ECDSA.recover(hash, v, r, s);
                                      if (signer != owner) {
                                          revert ERC2612InvalidSigner(signer, owner);
                                      }
                                      _approve(owner, spender, value);
                                  }
                                  /**
                                   * @inheritdoc IERC20Permit
                                   */
                                  function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) {
                                      return super.nonces(owner);
                                  }
                                  /**
                                   * @inheritdoc IERC20Permit
                                   */
                                  // solhint-disable-next-line func-name-mixedcase
                                  function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {
                                      return _domainSeparatorV4();
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
                              pragma solidity ^0.8.20;
                              import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
                              import {SafeERC20} from "../utils/SafeERC20.sol";
                              import {IERC4626} from "../../../interfaces/IERC4626.sol";
                              import {Math} from "../../../utils/math/Math.sol";
                              /**
                               * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
                               * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
                               *
                               * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
                               * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
                               * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
                               * contract and not the "assets" token which is an independent contract.
                               *
                               * [CAUTION]
                               * ====
                               * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
                               * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
                               * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
                               * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
                               * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
                               * verifying the amount received is as expected, using a wrapper that performs these checks such as
                               * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
                               *
                               * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
                               * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
                               * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
                               * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
                               * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
                               * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
                               * expensive than it is profitable. More details about the underlying math can be found
                               * xref:erc4626.adoc#inflation-attack[here].
                               *
                               * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
                               * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
                               * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
                               * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
                               * `_convertToShares` and `_convertToAssets` functions.
                               *
                               * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
                               * ====
                               */
                              abstract contract ERC4626 is ERC20, IERC4626 {
                                  using Math for uint256;
                                  IERC20 private immutable _asset;
                                  uint8 private immutable _underlyingDecimals;
                                  /**
                                   * @dev Attempted to deposit more assets than the max amount for `receiver`.
                                   */
                                  error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
                                  /**
                                   * @dev Attempted to mint more shares than the max amount for `receiver`.
                                   */
                                  error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
                                  /**
                                   * @dev Attempted to withdraw more assets than the max amount for `receiver`.
                                   */
                                  error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
                                  /**
                                   * @dev Attempted to redeem more shares than the max amount for `receiver`.
                                   */
                                  error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
                                  /**
                                   * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
                                   */
                                  constructor(IERC20 asset_) {
                                      (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
                                      _underlyingDecimals = success ? assetDecimals : 18;
                                      _asset = asset_;
                                  }
                                  /**
                                   * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
                                   */
                                  function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
                                      (bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
                                          abi.encodeCall(IERC20Metadata.decimals, ())
                                      );
                                      if (success && encodedDecimals.length >= 32) {
                                          uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
                                          if (returnedDecimals <= type(uint8).max) {
                                              return (true, uint8(returnedDecimals));
                                          }
                                      }
                                      return (false, 0);
                                  }
                                  /**
                                   * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
                                   * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
                                   * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
                                   *
                                   * See {IERC20Metadata-decimals}.
                                   */
                                  function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
                                      return _underlyingDecimals + _decimalsOffset();
                                  }
                                  /** @dev See {IERC4626-asset}. */
                                  function asset() public view virtual returns (address) {
                                      return address(_asset);
                                  }
                                  /** @dev See {IERC4626-totalAssets}. */
                                  function totalAssets() public view virtual returns (uint256) {
                                      return _asset.balanceOf(address(this));
                                  }
                                  /** @dev See {IERC4626-convertToShares}. */
                                  function convertToShares(uint256 assets) public view virtual returns (uint256) {
                                      return _convertToShares(assets, Math.Rounding.Floor);
                                  }
                                  /** @dev See {IERC4626-convertToAssets}. */
                                  function convertToAssets(uint256 shares) public view virtual returns (uint256) {
                                      return _convertToAssets(shares, Math.Rounding.Floor);
                                  }
                                  /** @dev See {IERC4626-maxDeposit}. */
                                  function maxDeposit(address) public view virtual returns (uint256) {
                                      return type(uint256).max;
                                  }
                                  /** @dev See {IERC4626-maxMint}. */
                                  function maxMint(address) public view virtual returns (uint256) {
                                      return type(uint256).max;
                                  }
                                  /** @dev See {IERC4626-maxWithdraw}. */
                                  function maxWithdraw(address owner) public view virtual returns (uint256) {
                                      return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
                                  }
                                  /** @dev See {IERC4626-maxRedeem}. */
                                  function maxRedeem(address owner) public view virtual returns (uint256) {
                                      return balanceOf(owner);
                                  }
                                  /** @dev See {IERC4626-previewDeposit}. */
                                  function previewDeposit(uint256 assets) public view virtual returns (uint256) {
                                      return _convertToShares(assets, Math.Rounding.Floor);
                                  }
                                  /** @dev See {IERC4626-previewMint}. */
                                  function previewMint(uint256 shares) public view virtual returns (uint256) {
                                      return _convertToAssets(shares, Math.Rounding.Ceil);
                                  }
                                  /** @dev See {IERC4626-previewWithdraw}. */
                                  function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
                                      return _convertToShares(assets, Math.Rounding.Ceil);
                                  }
                                  /** @dev See {IERC4626-previewRedeem}. */
                                  function previewRedeem(uint256 shares) public view virtual returns (uint256) {
                                      return _convertToAssets(shares, Math.Rounding.Floor);
                                  }
                                  /** @dev See {IERC4626-deposit}. */
                                  function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
                                      uint256 maxAssets = maxDeposit(receiver);
                                      if (assets > maxAssets) {
                                          revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
                                      }
                                      uint256 shares = previewDeposit(assets);
                                      _deposit(_msgSender(), receiver, assets, shares);
                                      return shares;
                                  }
                                  /** @dev See {IERC4626-mint}.
                                   *
                                   * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
                                   * In this case, the shares will be minted without requiring any assets to be deposited.
                                   */
                                  function mint(uint256 shares, address receiver) public virtual returns (uint256) {
                                      uint256 maxShares = maxMint(receiver);
                                      if (shares > maxShares) {
                                          revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
                                      }
                                      uint256 assets = previewMint(shares);
                                      _deposit(_msgSender(), receiver, assets, shares);
                                      return assets;
                                  }
                                  /** @dev See {IERC4626-withdraw}. */
                                  function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
                                      uint256 maxAssets = maxWithdraw(owner);
                                      if (assets > maxAssets) {
                                          revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
                                      }
                                      uint256 shares = previewWithdraw(assets);
                                      _withdraw(_msgSender(), receiver, owner, assets, shares);
                                      return shares;
                                  }
                                  /** @dev See {IERC4626-redeem}. */
                                  function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
                                      uint256 maxShares = maxRedeem(owner);
                                      if (shares > maxShares) {
                                          revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
                                      }
                                      uint256 assets = previewRedeem(shares);
                                      _withdraw(_msgSender(), receiver, owner, assets, shares);
                                      return assets;
                                  }
                                  /**
                                   * @dev Internal conversion function (from assets to shares) with support for rounding direction.
                                   */
                                  function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
                                      return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
                                  }
                                  /**
                                   * @dev Internal conversion function (from shares to assets) with support for rounding direction.
                                   */
                                  function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
                                      return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
                                  }
                                  /**
                                   * @dev Deposit/mint common workflow.
                                   */
                                  function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
                                      // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
                                      // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
                                      // calls the vault, which is assumed not malicious.
                                      //
                                      // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
                                      // assets are transferred and before the shares are minted, which is a valid state.
                                      // slither-disable-next-line reentrancy-no-eth
                                      SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
                                      _mint(receiver, shares);
                                      emit Deposit(caller, receiver, assets, shares);
                                  }
                                  /**
                                   * @dev Withdraw/redeem common workflow.
                                   */
                                  function _withdraw(
                                      address caller,
                                      address receiver,
                                      address owner,
                                      uint256 assets,
                                      uint256 shares
                                  ) internal virtual {
                                      if (caller != owner) {
                                          _spendAllowance(owner, caller, shares);
                                      }
                                      // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
                                      // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
                                      // calls the vault, which is assumed not malicious.
                                      //
                                      // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
                                      // shares are burned and after the assets are transferred, which is a valid state.
                                      _burn(owner, shares);
                                      SafeERC20.safeTransfer(_asset, receiver, assets);
                                      emit Withdraw(caller, receiver, owner, assets, shares);
                                  }
                                  function _decimalsOffset() internal view virtual returns (uint8) {
                                      return 0;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
                              pragma solidity ^0.8.20;
                              import {IERC20} from "../token/ERC20/IERC20.sol";
                              import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
                              /**
                               * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
                               * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
                               */
                              interface IERC4626 is IERC20, IERC20Metadata {
                                  event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
                                  event Withdraw(
                                      address indexed sender,
                                      address indexed receiver,
                                      address indexed owner,
                                      uint256 assets,
                                      uint256 shares
                                  );
                                  /**
                                   * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
                                   *
                                   * - MUST be an ERC-20 token contract.
                                   * - MUST NOT revert.
                                   */
                                  function asset() external view returns (address assetTokenAddress);
                                  /**
                                   * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
                                   *
                                   * - SHOULD include any compounding that occurs from yield.
                                   * - MUST be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT revert.
                                   */
                                  function totalAssets() external view returns (uint256 totalManagedAssets);
                                  /**
                                   * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
                                   * scenario where all the conditions are met.
                                   *
                                   * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT show any variations depending on the caller.
                                   * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
                                   * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
                                   * from.
                                   */
                                  function convertToShares(uint256 assets) external view returns (uint256 shares);
                                  /**
                                   * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
                                   * scenario where all the conditions are met.
                                   *
                                   * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT show any variations depending on the caller.
                                   * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
                                   * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
                                   * from.
                                   */
                                  function convertToAssets(uint256 shares) external view returns (uint256 assets);
                                  /**
                                   * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
                                   * through a deposit call.
                                   *
                                   * - MUST return a limited value if receiver is subject to some deposit limit.
                                   * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
                                   * - MUST NOT revert.
                                   */
                                  function maxDeposit(address receiver) external view returns (uint256 maxAssets);
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
                                   * current on-chain conditions.
                                   *
                                   * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
                                   *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
                                   *   in the same transaction.
                                   * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
                                   *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
                                   * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by depositing.
                                   */
                                  function previewDeposit(uint256 assets) external view returns (uint256 shares);
                                  /**
                                   * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
                                   *
                                   * - MUST emit the Deposit event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   deposit execution, and are accounted for during deposit.
                                   * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
                                   *   approving enough underlying tokens to the Vault contract, etc).
                                   *
                                   * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
                                   */
                                  function deposit(uint256 assets, address receiver) external returns (uint256 shares);
                                  /**
                                   * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
                                   * - MUST return a limited value if receiver is subject to some mint limit.
                                   * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
                                   * - MUST NOT revert.
                                   */
                                  function maxMint(address receiver) external view returns (uint256 maxShares);
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
                                   * current on-chain conditions.
                                   *
                                   * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
                                   *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
                                   *   same transaction.
                                   * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
                                   *   would be accepted, regardless if the user has enough tokens approved, etc.
                                   * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by minting.
                                   */
                                  function previewMint(uint256 shares) external view returns (uint256 assets);
                                  /**
                                   * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
                                   *
                                   * - MUST emit the Deposit event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
                                   *   execution, and are accounted for during mint.
                                   * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
                                   *   approving enough underlying tokens to the Vault contract, etc).
                                   *
                                   * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
                                   */
                                  function mint(uint256 shares, address receiver) external returns (uint256 assets);
                                  /**
                                   * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
                                   * Vault, through a withdraw call.
                                   *
                                   * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
                                   * - MUST NOT revert.
                                   */
                                  function maxWithdraw(address owner) external view returns (uint256 maxAssets);
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
                                   * given current on-chain conditions.
                                   *
                                   * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
                                   *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
                                   *   called
                                   *   in the same transaction.
                                   * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
                                   *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
                                   * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by depositing.
                                   */
                                  function previewWithdraw(uint256 assets) external view returns (uint256 shares);
                                  /**
                                   * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
                                   *
                                   * - MUST emit the Withdraw event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   withdraw execution, and are accounted for during withdraw.
                                   * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
                                   *   not having enough shares, etc).
                                   *
                                   * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
                                   * Those methods should be performed separately.
                                   */
                                  function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
                                  /**
                                   * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
                                   * through a redeem call.
                                   *
                                   * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
                                   * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
                                   * - MUST NOT revert.
                                   */
                                  function maxRedeem(address owner) external view returns (uint256 maxShares);
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
                                   * given current on-chain conditions.
                                   *
                                   * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
                                   *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
                                   *   same transaction.
                                   * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
                                   *   redemption would be accepted, regardless if the user has enough shares, etc.
                                   * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
                                   */
                                  function previewRedeem(uint256 shares) external view returns (uint256 assets);
                                  /**
                                   * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
                                   *
                                   * - MUST emit the Withdraw event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   redeem execution, and are accounted for during redeem.
                                   * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
                                   *   not having enough shares, etc).
                                   *
                                   * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
                                   * Those methods should be performed separately.
                                   */
                                  function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                               * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                               *
                               * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                               * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                               * need to send a transaction, and thus is not required to hold Ether at all.
                               *
                               * ==== Security Considerations
                               *
                               * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
                               * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
                               * considered as an intention to spend the allowance in any specific way. The second is that because permits have
                               * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
                               * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
                               * generally recommended is:
                               *
                               * ```solidity
                               * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
                               *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
                               *     doThing(..., value);
                               * }
                               *
                               * function doThing(..., uint256 value) public {
                               *     token.safeTransferFrom(msg.sender, address(this), value);
                               *     ...
                               * }
                               * ```
                               *
                               * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
                               * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
                               * {SafeERC20-safeTransferFrom}).
                               *
                               * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
                               * contracts should have entry points that don't rely on permit.
                               */
                              interface IERC20Permit {
                                  /**
                                   * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                                   * given ``owner``'s signed approval.
                                   *
                                   * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                                   * ordering also apply here.
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   * - `deadline` must be a timestamp in the future.
                                   * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                                   * over the EIP712-formatted function arguments.
                                   * - the signature must use ``owner``'s current nonce (see {nonces}).
                                   *
                                   * For more information on the signature format, see the
                                   * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                                   * section].
                                   *
                                   * CAUTION: See Security Considerations above.
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external;
                                  /**
                                   * @dev Returns the current nonce for `owner`. This value must be
                                   * included whenever a signature is generated for {permit}.
                                   *
                                   * Every successful call to {permit} increases ``owner``'s nonce by one. This
                                   * prevents a signature from being used multiple times.
                                   */
                                  function nonces(address owner) external view returns (uint256);
                                  /**
                                   * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                                   */
                                  // solhint-disable-next-line func-name-mixedcase
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              /// @title ErrorsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing error messages.
                              library ErrorsLib {
                                  /// @notice Thrown when the caller is not the owner.
                                  string internal constant NOT_OWNER = "not owner";
                                  /// @notice Thrown when the LLTV to enable exceeds the maximum LLTV.
                                  string internal constant MAX_LLTV_EXCEEDED = "max LLTV exceeded";
                                  /// @notice Thrown when the fee to set exceeds the maximum fee.
                                  string internal constant MAX_FEE_EXCEEDED = "max fee exceeded";
                                  /// @notice Thrown when the value is already set.
                                  string internal constant ALREADY_SET = "already set";
                                  /// @notice Thrown when the IRM is not enabled at market creation.
                                  string internal constant IRM_NOT_ENABLED = "IRM not enabled";
                                  /// @notice Thrown when the LLTV is not enabled at market creation.
                                  string internal constant LLTV_NOT_ENABLED = "LLTV not enabled";
                                  /// @notice Thrown when the market is already created.
                                  string internal constant MARKET_ALREADY_CREATED = "market already created";
                                  /// @notice Thrown when a token to transfer doesn't have code.
                                  string internal constant NO_CODE = "no code";
                                  /// @notice Thrown when the market is not created.
                                  string internal constant MARKET_NOT_CREATED = "market not created";
                                  /// @notice Thrown when not exactly one of the input amount is zero.
                                  string internal constant INCONSISTENT_INPUT = "inconsistent input";
                                  /// @notice Thrown when zero assets is passed as input.
                                  string internal constant ZERO_ASSETS = "zero assets";
                                  /// @notice Thrown when a zero address is passed as input.
                                  string internal constant ZERO_ADDRESS = "zero address";
                                  /// @notice Thrown when the caller is not authorized to conduct an action.
                                  string internal constant UNAUTHORIZED = "unauthorized";
                                  /// @notice Thrown when the collateral is insufficient to `borrow` or `withdrawCollateral`.
                                  string internal constant INSUFFICIENT_COLLATERAL = "insufficient collateral";
                                  /// @notice Thrown when the liquidity is insufficient to `withdraw` or `borrow`.
                                  string internal constant INSUFFICIENT_LIQUIDITY = "insufficient liquidity";
                                  /// @notice Thrown when the position to liquidate is healthy.
                                  string internal constant HEALTHY_POSITION = "position is healthy";
                                  /// @notice Thrown when the authorization signature is invalid.
                                  string internal constant INVALID_SIGNATURE = "invalid signature";
                                  /// @notice Thrown when the authorization signature is expired.
                                  string internal constant SIGNATURE_EXPIRED = "signature expired";
                                  /// @notice Thrown when the nonce is invalid.
                                  string internal constant INVALID_NONCE = "invalid nonce";
                                  /// @notice Thrown when a token transfer reverted.
                                  string internal constant TRANSFER_REVERTED = "transfer reverted";
                                  /// @notice Thrown when a token transfer returned false.
                                  string internal constant TRANSFER_RETURNED_FALSE = "transfer returned false";
                                  /// @notice Thrown when a token transferFrom reverted.
                                  string internal constant TRANSFER_FROM_REVERTED = "transferFrom reverted";
                                  /// @notice Thrown when a token transferFrom returned false
                                  string internal constant TRANSFER_FROM_RETURNED_FALSE = "transferFrom returned false";
                                  /// @notice Thrown when the maximum uint128 is exceeded.
                                  string internal constant MAX_UINT128_EXCEEDED = "max uint128 exceeded";
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id} from "../../interfaces/IMorpho.sol";
                              /// @title MorphoStorageLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Helper library exposing getters to access Morpho storage variables' slot.
                              /// @dev This library is not used in Morpho itself and is intended to be used by integrators.
                              library MorphoStorageLib {
                                  /* SLOTS */
                                  uint256 internal constant OWNER_SLOT = 0;
                                  uint256 internal constant FEE_RECIPIENT_SLOT = 1;
                                  uint256 internal constant POSITION_SLOT = 2;
                                  uint256 internal constant MARKET_SLOT = 3;
                                  uint256 internal constant IS_IRM_ENABLED_SLOT = 4;
                                  uint256 internal constant IS_LLTV_ENABLED_SLOT = 5;
                                  uint256 internal constant IS_AUTHORIZED_SLOT = 6;
                                  uint256 internal constant NONCE_SLOT = 7;
                                  uint256 internal constant ID_TO_MARKET_PARAMS_SLOT = 8;
                                  /* SLOT OFFSETS */
                                  uint256 internal constant LOAN_TOKEN_OFFSET = 0;
                                  uint256 internal constant COLLATERAL_TOKEN_OFFSET = 1;
                                  uint256 internal constant ORACLE_OFFSET = 2;
                                  uint256 internal constant IRM_OFFSET = 3;
                                  uint256 internal constant LLTV_OFFSET = 4;
                                  uint256 internal constant SUPPLY_SHARES_OFFSET = 0;
                                  uint256 internal constant BORROW_SHARES_AND_COLLATERAL_OFFSET = 1;
                                  uint256 internal constant TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET = 0;
                                  uint256 internal constant TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET = 1;
                                  uint256 internal constant LAST_UPDATE_AND_FEE_OFFSET = 2;
                                  /* GETTERS */
                                  function ownerSlot() internal pure returns (bytes32) {
                                      return bytes32(OWNER_SLOT);
                                  }
                                  function feeRecipientSlot() internal pure returns (bytes32) {
                                      return bytes32(FEE_RECIPIENT_SLOT);
                                  }
                                  function positionSupplySharesSlot(Id id, address user) internal pure returns (bytes32) {
                                      return bytes32(
                                          uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT))))) + SUPPLY_SHARES_OFFSET
                                      );
                                  }
                                  function positionBorrowSharesAndCollateralSlot(Id id, address user) internal pure returns (bytes32) {
                                      return bytes32(
                                          uint256(keccak256(abi.encode(user, keccak256(abi.encode(id, POSITION_SLOT)))))
                                              + BORROW_SHARES_AND_COLLATERAL_OFFSET
                                      );
                                  }
                                  function marketTotalSupplyAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_SUPPLY_ASSETS_AND_SHARES_OFFSET);
                                  }
                                  function marketTotalBorrowAssetsAndSharesSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + TOTAL_BORROW_ASSETS_AND_SHARES_OFFSET);
                                  }
                                  function marketLastUpdateAndFeeSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, MARKET_SLOT))) + LAST_UPDATE_AND_FEE_OFFSET);
                                  }
                                  function isIrmEnabledSlot(address irm) internal pure returns (bytes32) {
                                      return keccak256(abi.encode(irm, IS_IRM_ENABLED_SLOT));
                                  }
                                  function isLltvEnabledSlot(uint256 lltv) internal pure returns (bytes32) {
                                      return keccak256(abi.encode(lltv, IS_LLTV_ENABLED_SLOT));
                                  }
                                  function isAuthorizedSlot(address authorizer, address authorizee) internal pure returns (bytes32) {
                                      return keccak256(abi.encode(authorizee, keccak256(abi.encode(authorizer, IS_AUTHORIZED_SLOT))));
                                  }
                                  function nonceSlot(address authorizer) internal pure returns (bytes32) {
                                      return keccak256(abi.encode(authorizer, NONCE_SLOT));
                                  }
                                  function idToLoanTokenSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LOAN_TOKEN_OFFSET);
                                  }
                                  function idToCollateralTokenSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + COLLATERAL_TOKEN_OFFSET);
                                  }
                                  function idToOracleSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + ORACLE_OFFSET);
                                  }
                                  function idToIrmSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + IRM_OFFSET);
                                  }
                                  function idToLltvSlot(Id id) internal pure returns (bytes32) {
                                      return bytes32(uint256(keccak256(abi.encode(id, ID_TO_MARKET_PARAMS_SLOT))) + LLTV_OFFSET);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                                  /**
                                   * @dev Returns the value of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                                  /**
                                   * @dev Returns the value of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                                  /**
                                   * @dev Moves a `value` amount of tokens from the caller's account to `to`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address to, uint256 value) external returns (bool);
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                                  /**
                                   * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
                                   * caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 value) external returns (bool);
                                  /**
                                   * @dev Moves a `value` amount of tokens from `from` to `to` using the
                                   * allowance mechanism. `value` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address from, address to, uint256 value) external returns (bool);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              import {MarketParams, Market} from "./IMorpho.sol";
                              /// @title IIrm
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
                              interface IIrm {
                                  /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
                                  /// @dev Assumes that `market` corresponds to `marketParams`.
                                  function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);
                                  /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
                                  /// storage.
                                  /// @dev Assumes that `market` corresponds to `marketParams`.
                                  function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Collection of functions related to the address type
                               */
                              library Address {
                                  /**
                                   * @dev The ETH balance of the account is not enough to perform the operation.
                                   */
                                  error AddressInsufficientBalance(address account);
                                  /**
                                   * @dev There's no code at `target` (it is not a contract).
                                   */
                                  error AddressEmptyCode(address target);
                                  /**
                                   * @dev A call to an address target failed. The target may have reverted.
                                   */
                                  error FailedInnerCall();
                                  /**
                                   * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                                   * `recipient`, forwarding all available gas and reverting on errors.
                                   *
                                   * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                                   * of certain opcodes, possibly making contracts go over the 2300 gas limit
                                   * imposed by `transfer`, making them unable to receive funds via
                                   * `transfer`. {sendValue} removes this limitation.
                                   *
                                   * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                                   *
                                   * IMPORTANT: because control is transferred to `recipient`, care must be
                                   * taken to not create reentrancy vulnerabilities. Consider using
                                   * {ReentrancyGuard} or the
                                   * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                                   */
                                  function sendValue(address payable recipient, uint256 amount) internal {
                                      if (address(this).balance < amount) {
                                          revert AddressInsufficientBalance(address(this));
                                      }
                                      (bool success, ) = recipient.call{value: amount}("");
                                      if (!success) {
                                          revert FailedInnerCall();
                                      }
                                  }
                                  /**
                                   * @dev Performs a Solidity function call using a low level `call`. A
                                   * plain `call` is an unsafe replacement for a function call: use this
                                   * function instead.
                                   *
                                   * If `target` reverts with a revert reason or custom error, it is bubbled
                                   * up by this function (like regular Solidity function calls). However, if
                                   * the call reverted with no returned reason, this function reverts with a
                                   * {FailedInnerCall} error.
                                   *
                                   * Returns the raw returned data. To convert to the expected return value,
                                   * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                                   *
                                   * Requirements:
                                   *
                                   * - `target` must be a contract.
                                   * - calling `target` with `data` must not revert.
                                   */
                                  function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                      return functionCallWithValue(target, data, 0);
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but also transferring `value` wei to `target`.
                                   *
                                   * Requirements:
                                   *
                                   * - the calling contract must have an ETH balance of at least `value`.
                                   * - the called Solidity function must be `payable`.
                                   */
                                  function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                      if (address(this).balance < value) {
                                          revert AddressInsufficientBalance(address(this));
                                      }
                                      (bool success, bytes memory returndata) = target.call{value: value}(data);
                                      return verifyCallResultFromTarget(target, success, returndata);
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but performing a static call.
                                   */
                                  function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                      (bool success, bytes memory returndata) = target.staticcall(data);
                                      return verifyCallResultFromTarget(target, success, returndata);
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but performing a delegate call.
                                   */
                                  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                      (bool success, bytes memory returndata) = target.delegatecall(data);
                                      return verifyCallResultFromTarget(target, success, returndata);
                                  }
                                  /**
                                   * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
                                   * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
                                   * unsuccessful call.
                                   */
                                  function verifyCallResultFromTarget(
                                      address target,
                                      bool success,
                                      bytes memory returndata
                                  ) internal view returns (bytes memory) {
                                      if (!success) {
                                          _revert(returndata);
                                      } else {
                                          // only check if target is a contract if the call was successful and the return data is empty
                                          // otherwise we already know that it was a contract
                                          if (returndata.length == 0 && target.code.length == 0) {
                                              revert AddressEmptyCode(target);
                                          }
                                          return returndata;
                                      }
                                  }
                                  /**
                                   * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
                                   * revert reason or with a default {FailedInnerCall} error.
                                   */
                                  function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
                                      if (!success) {
                                          _revert(returndata);
                                      } else {
                                          return returndata;
                                      }
                                  }
                                  /**
                                   * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
                                   */
                                  function _revert(bytes memory returndata) private pure {
                                      // Look for revert reason and bubble it up if present
                                      if (returndata.length > 0) {
                                          // The easiest way to bubble the revert reason is using memory via assembly
                                          /// @solidity memory-safe-assembly
                                          assembly {
                                              let returndata_size := mload(returndata)
                                              revert(add(32, returndata), returndata_size)
                                          }
                                      } else {
                                          revert FailedInnerCall();
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
                              pragma solidity ^0.8.20;
                              import {Context} from "../utils/Context.sol";
                              /**
                               * @dev Contract module which provides a basic access control mechanism, where
                               * there is an account (an owner) that can be granted exclusive access to
                               * specific functions.
                               *
                               * The initial owner is set to the address provided by the deployer. This can
                               * later be changed with {transferOwnership}.
                               *
                               * This module is used through inheritance. It will make available the modifier
                               * `onlyOwner`, which can be applied to your functions to restrict their use to
                               * the owner.
                               */
                              abstract contract Ownable is Context {
                                  address private _owner;
                                  /**
                                   * @dev The caller account is not authorized to perform an operation.
                                   */
                                  error OwnableUnauthorizedAccount(address account);
                                  /**
                                   * @dev The owner is not a valid owner account. (eg. `address(0)`)
                                   */
                                  error OwnableInvalidOwner(address owner);
                                  event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
                                  /**
                                   * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
                                   */
                                  constructor(address initialOwner) {
                                      if (initialOwner == address(0)) {
                                          revert OwnableInvalidOwner(address(0));
                                      }
                                      _transferOwnership(initialOwner);
                                  }
                                  /**
                                   * @dev Throws if called by any account other than the owner.
                                   */
                                  modifier onlyOwner() {
                                      _checkOwner();
                                      _;
                                  }
                                  /**
                                   * @dev Returns the address of the current owner.
                                   */
                                  function owner() public view virtual returns (address) {
                                      return _owner;
                                  }
                                  /**
                                   * @dev Throws if the sender is not the owner.
                                   */
                                  function _checkOwner() internal view virtual {
                                      if (owner() != _msgSender()) {
                                          revert OwnableUnauthorizedAccount(_msgSender());
                                      }
                                  }
                                  /**
                                   * @dev Leaves the contract without owner. It will not be possible to call
                                   * `onlyOwner` functions. Can only be called by the current owner.
                                   *
                                   * NOTE: Renouncing ownership will leave the contract without an owner,
                                   * thereby disabling any functionality that is only available to the owner.
                                   */
                                  function renounceOwnership() public virtual onlyOwner {
                                      _transferOwnership(address(0));
                                  }
                                  /**
                                   * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                   * Can only be called by the current owner.
                                   */
                                  function transferOwnership(address newOwner) public virtual onlyOwner {
                                      if (newOwner == address(0)) {
                                          revert OwnableInvalidOwner(address(0));
                                      }
                                      _transferOwnership(newOwner);
                                  }
                                  /**
                                   * @dev Transfers ownership of the contract to a new account (`newOwner`).
                                   * Internal function without access restriction.
                                   */
                                  function _transferOwnership(address newOwner) internal virtual {
                                      address oldOwner = _owner;
                                      _owner = newOwner;
                                      emit OwnershipTransferred(oldOwner, newOwner);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
                              pragma solidity ^0.8.20;
                              import {IERC20} from "./IERC20.sol";
                              import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
                              import {Context} from "../../utils/Context.sol";
                              import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
                              /**
                               * @dev Implementation of the {IERC20} interface.
                               *
                               * This implementation is agnostic to the way tokens are created. This means
                               * that a supply mechanism has to be added in a derived contract using {_mint}.
                               *
                               * TIP: For a detailed writeup see our guide
                               * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
                               * to implement supply mechanisms].
                               *
                               * The default value of {decimals} is 18. To change this, you should override
                               * this function so it returns a different value.
                               *
                               * We have followed general OpenZeppelin Contracts guidelines: functions revert
                               * instead returning `false` on failure. This behavior is nonetheless
                               * conventional and does not conflict with the expectations of ERC20
                               * applications.
                               *
                               * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                               * This allows applications to reconstruct the allowance for all accounts just
                               * by listening to said events. Other implementations of the EIP may not emit
                               * these events, as it isn't required by the specification.
                               */
                              abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
                                  mapping(address account => uint256) private _balances;
                                  mapping(address account => mapping(address spender => uint256)) private _allowances;
                                  uint256 private _totalSupply;
                                  string private _name;
                                  string private _symbol;
                                  /**
                                   * @dev Sets the values for {name} and {symbol}.
                                   *
                                   * All two of these values are immutable: they can only be set once during
                                   * construction.
                                   */
                                  constructor(string memory name_, string memory symbol_) {
                                      _name = name_;
                                      _symbol = symbol_;
                                  }
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() public view virtual returns (string memory) {
                                      return _name;
                                  }
                                  /**
                                   * @dev Returns the symbol of the token, usually a shorter version of the
                                   * name.
                                   */
                                  function symbol() public view virtual returns (string memory) {
                                      return _symbol;
                                  }
                                  /**
                                   * @dev Returns the number of decimals used to get its user representation.
                                   * For example, if `decimals` equals `2`, a balance of `505` tokens should
                                   * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                                   *
                                   * Tokens usually opt for a value of 18, imitating the relationship between
                                   * Ether and Wei. This is the default value returned by this function, unless
                                   * it's overridden.
                                   *
                                   * NOTE: This information is only used for _display_ purposes: it in
                                   * no way affects any of the arithmetic of the contract, including
                                   * {IERC20-balanceOf} and {IERC20-transfer}.
                                   */
                                  function decimals() public view virtual returns (uint8) {
                                      return 18;
                                  }
                                  /**
                                   * @dev See {IERC20-totalSupply}.
                                   */
                                  function totalSupply() public view virtual returns (uint256) {
                                      return _totalSupply;
                                  }
                                  /**
                                   * @dev See {IERC20-balanceOf}.
                                   */
                                  function balanceOf(address account) public view virtual returns (uint256) {
                                      return _balances[account];
                                  }
                                  /**
                                   * @dev See {IERC20-transfer}.
                                   *
                                   * Requirements:
                                   *
                                   * - `to` cannot be the zero address.
                                   * - the caller must have a balance of at least `value`.
                                   */
                                  function transfer(address to, uint256 value) public virtual returns (bool) {
                                      address owner = _msgSender();
                                      _transfer(owner, to, value);
                                      return true;
                                  }
                                  /**
                                   * @dev See {IERC20-allowance}.
                                   */
                                  function allowance(address owner, address spender) public view virtual returns (uint256) {
                                      return _allowances[owner][spender];
                                  }
                                  /**
                                   * @dev See {IERC20-approve}.
                                   *
                                   * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
                                   * `transferFrom`. This is semantically equivalent to an infinite approval.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   */
                                  function approve(address spender, uint256 value) public virtual returns (bool) {
                                      address owner = _msgSender();
                                      _approve(owner, spender, value);
                                      return true;
                                  }
                                  /**
                                   * @dev See {IERC20-transferFrom}.
                                   *
                                   * Emits an {Approval} event indicating the updated allowance. This is not
                                   * required by the EIP. See the note at the beginning of {ERC20}.
                                   *
                                   * NOTE: Does not update the allowance if the current allowance
                                   * is the maximum `uint256`.
                                   *
                                   * Requirements:
                                   *
                                   * - `from` and `to` cannot be the zero address.
                                   * - `from` must have a balance of at least `value`.
                                   * - the caller must have allowance for ``from``'s tokens of at least
                                   * `value`.
                                   */
                                  function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
                                      address spender = _msgSender();
                                      _spendAllowance(from, spender, value);
                                      _transfer(from, to, value);
                                      return true;
                                  }
                                  /**
                                   * @dev Moves a `value` amount of tokens from `from` to `to`.
                                   *
                                   * This internal function is equivalent to {transfer}, and can be used to
                                   * e.g. implement automatic token fees, slashing mechanisms, etc.
                                   *
                                   * Emits a {Transfer} event.
                                   *
                                   * NOTE: This function is not virtual, {_update} should be overridden instead.
                                   */
                                  function _transfer(address from, address to, uint256 value) internal {
                                      if (from == address(0)) {
                                          revert ERC20InvalidSender(address(0));
                                      }
                                      if (to == address(0)) {
                                          revert ERC20InvalidReceiver(address(0));
                                      }
                                      _update(from, to, value);
                                  }
                                  /**
                                   * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
                                   * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
                                   * this function.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function _update(address from, address to, uint256 value) internal virtual {
                                      if (from == address(0)) {
                                          // Overflow check required: The rest of the code assumes that totalSupply never overflows
                                          _totalSupply += value;
                                      } else {
                                          uint256 fromBalance = _balances[from];
                                          if (fromBalance < value) {
                                              revert ERC20InsufficientBalance(from, fromBalance, value);
                                          }
                                          unchecked {
                                              // Overflow not possible: value <= fromBalance <= totalSupply.
                                              _balances[from] = fromBalance - value;
                                          }
                                      }
                                      if (to == address(0)) {
                                          unchecked {
                                              // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                                              _totalSupply -= value;
                                          }
                                      } else {
                                          unchecked {
                                              // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                                              _balances[to] += value;
                                          }
                                      }
                                      emit Transfer(from, to, value);
                                  }
                                  /**
                                   * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
                                   * Relies on the `_update` mechanism
                                   *
                                   * Emits a {Transfer} event with `from` set to the zero address.
                                   *
                                   * NOTE: This function is not virtual, {_update} should be overridden instead.
                                   */
                                  function _mint(address account, uint256 value) internal {
                                      if (account == address(0)) {
                                          revert ERC20InvalidReceiver(address(0));
                                      }
                                      _update(address(0), account, value);
                                  }
                                  /**
                                   * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
                                   * Relies on the `_update` mechanism.
                                   *
                                   * Emits a {Transfer} event with `to` set to the zero address.
                                   *
                                   * NOTE: This function is not virtual, {_update} should be overridden instead
                                   */
                                  function _burn(address account, uint256 value) internal {
                                      if (account == address(0)) {
                                          revert ERC20InvalidSender(address(0));
                                      }
                                      _update(account, address(0), value);
                                  }
                                  /**
                                   * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
                                   *
                                   * This internal function is equivalent to `approve`, and can be used to
                                   * e.g. set automatic allowances for certain subsystems, etc.
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `owner` cannot be the zero address.
                                   * - `spender` cannot be the zero address.
                                   *
                                   * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
                                   */
                                  function _approve(address owner, address spender, uint256 value) internal {
                                      _approve(owner, spender, value, true);
                                  }
                                  /**
                                   * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
                                   *
                                   * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
                                   * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
                                   * `Approval` event during `transferFrom` operations.
                                   *
                                   * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
                                   * true using the following override:
                                   * ```
                                   * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
                                   *     super._approve(owner, spender, value, true);
                                   * }
                                   * ```
                                   *
                                   * Requirements are the same as {_approve}.
                                   */
                                  function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
                                      if (owner == address(0)) {
                                          revert ERC20InvalidApprover(address(0));
                                      }
                                      if (spender == address(0)) {
                                          revert ERC20InvalidSpender(address(0));
                                      }
                                      _allowances[owner][spender] = value;
                                      if (emitEvent) {
                                          emit Approval(owner, spender, value);
                                      }
                                  }
                                  /**
                                   * @dev Updates `owner` s allowance for `spender` based on spent `value`.
                                   *
                                   * Does not update the allowance value in case of infinite allowance.
                                   * Revert if not enough allowance is available.
                                   *
                                   * Does not emit an {Approval} event.
                                   */
                                  function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
                                      uint256 currentAllowance = allowance(owner, spender);
                                      if (currentAllowance != type(uint256).max) {
                                          if (currentAllowance < value) {
                                              revert ERC20InsufficientAllowance(spender, currentAllowance, value);
                                          }
                                          unchecked {
                                              _approve(owner, spender, currentAllowance - value, false);
                                          }
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
                               *
                               * These functions can be used to verify that a message was signed by the holder
                               * of the private keys of a given address.
                               */
                              library ECDSA {
                                  enum RecoverError {
                                      NoError,
                                      InvalidSignature,
                                      InvalidSignatureLength,
                                      InvalidSignatureS
                                  }
                                  /**
                                   * @dev The signature derives the `address(0)`.
                                   */
                                  error ECDSAInvalidSignature();
                                  /**
                                   * @dev The signature has an invalid length.
                                   */
                                  error ECDSAInvalidSignatureLength(uint256 length);
                                  /**
                                   * @dev The signature has an S value that is in the upper half order.
                                   */
                                  error ECDSAInvalidSignatureS(bytes32 s);
                                  /**
                                   * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
                                   * return address(0) without also returning an error description. Errors are documented using an enum (error type)
                                   * and a bytes32 providing additional information about the error.
                                   *
                                   * If no error is returned, then the address can be used for verification purposes.
                                   *
                                   * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
                                   * this function rejects them by requiring the `s` value to be in the lower
                                   * half order, and the `v` value to be either 27 or 28.
                                   *
                                   * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                                   * verification to be secure: it is possible to craft signatures that
                                   * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                                   * this is by receiving a hash of the original message (which may otherwise
                                   * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
                                   *
                                   * Documentation for signature generation:
                                   * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
                                   * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
                                   */
                                  function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) {
                                      if (signature.length == 65) {
                                          bytes32 r;
                                          bytes32 s;
                                          uint8 v;
                                          // ecrecover takes the signature parameters, and the only way to get them
                                          // currently is to use assembly.
                                          /// @solidity memory-safe-assembly
                                          assembly {
                                              r := mload(add(signature, 0x20))
                                              s := mload(add(signature, 0x40))
                                              v := byte(0, mload(add(signature, 0x60)))
                                          }
                                          return tryRecover(hash, v, r, s);
                                      } else {
                                          return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
                                      }
                                  }
                                  /**
                                   * @dev Returns the address that signed a hashed message (`hash`) with
                                   * `signature`. This address can then be used for verification purposes.
                                   *
                                   * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
                                   * this function rejects them by requiring the `s` value to be in the lower
                                   * half order, and the `v` value to be either 27 or 28.
                                   *
                                   * IMPORTANT: `hash` _must_ be the result of a hash operation for the
                                   * verification to be secure: it is possible to craft signatures that
                                   * recover to arbitrary addresses for non-hashed data. A safe way to ensure
                                   * this is by receiving a hash of the original message (which may otherwise
                                   * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
                                   */
                                  function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
                                      (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
                                      _throwError(error, errorArg);
                                      return recovered;
                                  }
                                  /**
                                   * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
                                   *
                                   * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
                                   */
                                  function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) {
                                      unchecked {
                                          bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
                                          // We do not check for an overflow here since the shift operation results in 0 or 1.
                                          uint8 v = uint8((uint256(vs) >> 255) + 27);
                                          return tryRecover(hash, v, r, s);
                                      }
                                  }
                                  /**
                                   * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
                                   */
                                  function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
                                      (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
                                      _throwError(error, errorArg);
                                      return recovered;
                                  }
                                  /**
                                   * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
                                   * `r` and `s` signature fields separately.
                                   */
                                  function tryRecover(
                                      bytes32 hash,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal pure returns (address, RecoverError, bytes32) {
                                      // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                                      // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                                      // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
                                      // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                                      //
                                      // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                                      // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                                      // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                                      // these malleable signatures as well.
                                      if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
                                          return (address(0), RecoverError.InvalidSignatureS, s);
                                      }
                                      // If the signature is valid (and not malleable), return the signer address
                                      address signer = ecrecover(hash, v, r, s);
                                      if (signer == address(0)) {
                                          return (address(0), RecoverError.InvalidSignature, bytes32(0));
                                      }
                                      return (signer, RecoverError.NoError, bytes32(0));
                                  }
                                  /**
                                   * @dev Overload of {ECDSA-recover} that receives the `v`,
                                   * `r` and `s` signature fields separately.
                                   */
                                  function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
                                      (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
                                      _throwError(error, errorArg);
                                      return recovered;
                                  }
                                  /**
                                   * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
                                   */
                                  function _throwError(RecoverError error, bytes32 errorArg) private pure {
                                      if (error == RecoverError.NoError) {
                                          return; // no error: do nothing
                                      } else if (error == RecoverError.InvalidSignature) {
                                          revert ECDSAInvalidSignature();
                                      } else if (error == RecoverError.InvalidSignatureLength) {
                                          revert ECDSAInvalidSignatureLength(uint256(errorArg));
                                      } else if (error == RecoverError.InvalidSignatureS) {
                                          revert ECDSAInvalidSignatureS(errorArg);
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol)
                              pragma solidity ^0.8.20;
                              import {MessageHashUtils} from "./MessageHashUtils.sol";
                              import {ShortStrings, ShortString} from "../ShortStrings.sol";
                              import {IERC5267} from "../../interfaces/IERC5267.sol";
                              /**
                               * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
                               *
                               * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
                               * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
                               * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
                               * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
                               *
                               * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
                               * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
                               * ({_hashTypedDataV4}).
                               *
                               * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
                               * the chain id to protect against replay attacks on an eventual fork of the chain.
                               *
                               * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
                               * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
                               *
                               * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
                               * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
                               * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
                               *
                               * @custom:oz-upgrades-unsafe-allow state-variable-immutable
                               */
                              abstract contract EIP712 is IERC5267 {
                                  using ShortStrings for *;
                                  bytes32 private constant TYPE_HASH =
                                      keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
                                  // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
                                  // invalidate the cached domain separator if the chain id changes.
                                  bytes32 private immutable _cachedDomainSeparator;
                                  uint256 private immutable _cachedChainId;
                                  address private immutable _cachedThis;
                                  bytes32 private immutable _hashedName;
                                  bytes32 private immutable _hashedVersion;
                                  ShortString private immutable _name;
                                  ShortString private immutable _version;
                                  string private _nameFallback;
                                  string private _versionFallback;
                                  /**
                                   * @dev Initializes the domain separator and parameter caches.
                                   *
                                   * The meaning of `name` and `version` is specified in
                                   * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
                                   *
                                   * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
                                   * - `version`: the current major version of the signing domain.
                                   *
                                   * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
                                   * contract upgrade].
                                   */
                                  constructor(string memory name, string memory version) {
                                      _name = name.toShortStringWithFallback(_nameFallback);
                                      _version = version.toShortStringWithFallback(_versionFallback);
                                      _hashedName = keccak256(bytes(name));
                                      _hashedVersion = keccak256(bytes(version));
                                      _cachedChainId = block.chainid;
                                      _cachedDomainSeparator = _buildDomainSeparator();
                                      _cachedThis = address(this);
                                  }
                                  /**
                                   * @dev Returns the domain separator for the current chain.
                                   */
                                  function _domainSeparatorV4() internal view returns (bytes32) {
                                      if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
                                          return _cachedDomainSeparator;
                                      } else {
                                          return _buildDomainSeparator();
                                      }
                                  }
                                  function _buildDomainSeparator() private view returns (bytes32) {
                                      return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
                                  }
                                  /**
                                   * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
                                   * function returns the hash of the fully encoded EIP712 message for this domain.
                                   *
                                   * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
                                   *
                                   * ```solidity
                                   * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
                                   *     keccak256("Mail(address to,string contents)"),
                                   *     mailTo,
                                   *     keccak256(bytes(mailContents))
                                   * )));
                                   * address signer = ECDSA.recover(digest, signature);
                                   * ```
                                   */
                                  function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
                                      return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
                                  }
                                  /**
                                   * @dev See {IERC-5267}.
                                   */
                                  function eip712Domain()
                                      public
                                      view
                                      virtual
                                      returns (
                                          bytes1 fields,
                                          string memory name,
                                          string memory version,
                                          uint256 chainId,
                                          address verifyingContract,
                                          bytes32 salt,
                                          uint256[] memory extensions
                                      )
                                  {
                                      return (
                                          hex"0f", // 01111
                                          _EIP712Name(),
                                          _EIP712Version(),
                                          block.chainid,
                                          address(this),
                                          bytes32(0),
                                          new uint256[](0)
                                      );
                                  }
                                  /**
                                   * @dev The name parameter for the EIP712 domain.
                                   *
                                   * NOTE: By default this function reads _name which is an immutable value.
                                   * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
                                   */
                                  // solhint-disable-next-line func-name-mixedcase
                                  function _EIP712Name() internal view returns (string memory) {
                                      return _name.toStringWithFallback(_nameFallback);
                                  }
                                  /**
                                   * @dev The version parameter for the EIP712 domain.
                                   *
                                   * NOTE: By default this function reads _version which is an immutable value.
                                   * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
                                   */
                                  // solhint-disable-next-line func-name-mixedcase
                                  function _EIP712Version() internal view returns (string memory) {
                                      return _version.toStringWithFallback(_versionFallback);
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Provides tracking nonces for addresses. Nonces will only increment.
                               */
                              abstract contract Nonces {
                                  /**
                                   * @dev The nonce used for an `account` is not the expected current nonce.
                                   */
                                  error InvalidAccountNonce(address account, uint256 currentNonce);
                                  mapping(address account => uint256) private _nonces;
                                  /**
                                   * @dev Returns the next unused nonce for an address.
                                   */
                                  function nonces(address owner) public view virtual returns (uint256) {
                                      return _nonces[owner];
                                  }
                                  /**
                                   * @dev Consumes a nonce.
                                   *
                                   * Returns the current value and increments nonce.
                                   */
                                  function _useNonce(address owner) internal virtual returns (uint256) {
                                      // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be
                                      // decremented or reset. This guarantees that the nonce never overflows.
                                      unchecked {
                                          // It is important to do x++ and not ++x here.
                                          return _nonces[owner]++;
                                      }
                                  }
                                  /**
                                   * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.
                                   */
                                  function _useCheckedNonce(address owner, uint256 nonce) internal virtual {
                                      uint256 current = _useNonce(owner);
                                      if (nonce != current) {
                                          revert InvalidAccountNonce(owner, current);
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
                              pragma solidity ^0.8.20;
                              import {IERC20} from "../IERC20.sol";
                              import {IERC20Permit} from "../extensions/IERC20Permit.sol";
                              import {Address} from "../../../utils/Address.sol";
                              /**
                               * @title SafeERC20
                               * @dev Wrappers around ERC20 operations that throw on failure (when the token
                               * contract returns false). Tokens that return no value (and instead revert or
                               * throw on failure) are also supported, non-reverting calls are assumed to be
                               * successful.
                               * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                               * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                               */
                              library SafeERC20 {
                                  using Address for address;
                                  /**
                                   * @dev An operation with an ERC20 token failed.
                                   */
                                  error SafeERC20FailedOperation(address token);
                                  /**
                                   * @dev Indicates a failed `decreaseAllowance` request.
                                   */
                                  error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
                                  /**
                                   * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful.
                                   */
                                  function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
                                  }
                                  /**
                                   * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
                                   * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
                                   */
                                  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
                                  }
                                  /**
                                   * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful.
                                   */
                                  function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 oldAllowance = token.allowance(address(this), spender);
                                      forceApprove(token, spender, oldAllowance + value);
                                  }
                                  /**
                                   * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
                                   * value, non-reverting calls are assumed to be successful.
                                   */
                                  function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
                                      unchecked {
                                          uint256 currentAllowance = token.allowance(address(this), spender);
                                          if (currentAllowance < requestedDecrease) {
                                              revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
                                          }
                                          forceApprove(token, spender, currentAllowance - requestedDecrease);
                                      }
                                  }
                                  /**
                                   * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
                                   * to be set to zero before setting it to a non-zero value, such as USDT.
                                   */
                                  function forceApprove(IERC20 token, address spender, uint256 value) internal {
                                      bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
                                      if (!_callOptionalReturnBool(token, approvalCall)) {
                                          _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
                                          _callOptionalReturn(token, approvalCall);
                                      }
                                  }
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   */
                                  function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                      // the target address contains contract code and also asserts for success in the low-level call.
                                      bytes memory returndata = address(token).functionCall(data);
                                      if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
                                          revert SafeERC20FailedOperation(address(token));
                                      }
                                  }
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   *
                                   * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
                                   */
                                  function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                                      // and not revert is the subcall reverts.
                                      (bool success, bytes memory returndata) = address(token).call(data);
                                      return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Standard math utilities missing in the Solidity language.
                               */
                              library Math {
                                  /**
                                   * @dev Muldiv operation overflow.
                                   */
                                  error MathOverflowedMulDiv();
                                  enum Rounding {
                                      Floor, // Toward negative infinity
                                      Ceil, // Toward positive infinity
                                      Trunc, // Toward zero
                                      Expand // Away from zero
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      unchecked {
                                          uint256 c = a + b;
                                          if (c < a) return (false, 0);
                                          return (true, c);
                                      }
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      unchecked {
                                          if (b > a) return (false, 0);
                                          return (true, a - b);
                                      }
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      unchecked {
                                          // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                          // benefit is lost if 'b' is also tested.
                                          // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                          if (a == 0) return (true, 0);
                                          uint256 c = a * b;
                                          if (c / a != b) return (false, 0);
                                          return (true, c);
                                      }
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      unchecked {
                                          if (b == 0) return (false, 0);
                                          return (true, a / b);
                                      }
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      unchecked {
                                          if (b == 0) return (false, 0);
                                          return (true, a % b);
                                      }
                                  }
                                  /**
                                   * @dev Returns the largest of two numbers.
                                   */
                                  function max(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a > b ? a : b;
                                  }
                                  /**
                                   * @dev Returns the smallest of two numbers.
                                   */
                                  function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a < b ? a : b;
                                  }
                                  /**
                                   * @dev Returns the average of two numbers. The result is rounded towards
                                   * zero.
                                   */
                                  function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b) / 2 can overflow.
                                      return (a & b) + (a ^ b) / 2;
                                  }
                                  /**
                                   * @dev Returns the ceiling of the division of two numbers.
                                   *
                                   * This differs from standard division with `/` in that it rounds towards infinity instead
                                   * of rounding towards zero.
                                   */
                                  function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (b == 0) {
                                          // Guarantee the same behavior as in a regular Solidity division.
                                          return a / b;
                                      }
                                      // (a + b - 1) / b can overflow on addition, so we distribute.
                                      return a == 0 ? 0 : (a - 1) / b + 1;
                                  }
                                  /**
                                   * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
                                   * denominator == 0.
                                   * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
                                   * Uniswap Labs also under MIT license.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                                      unchecked {
                                          // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                          // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                          // variables such that product = prod1 * 2^256 + prod0.
                                          uint256 prod0 = x * y; // Least significant 256 bits of the product
                                          uint256 prod1; // Most significant 256 bits of the product
                                          assembly {
                                              let mm := mulmod(x, y, not(0))
                                              prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                          }
                                          // Handle non-overflow cases, 256 by 256 division.
                                          if (prod1 == 0) {
                                              // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                                              // The surrounding unchecked block does not change this fact.
                                              // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                                              return prod0 / denominator;
                                          }
                                          // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                          if (denominator <= prod1) {
                                              revert MathOverflowedMulDiv();
                                          }
                                          ///////////////////////////////////////////////
                                          // 512 by 256 division.
                                          ///////////////////////////////////////////////
                                          // Make division exact by subtracting the remainder from [prod1 prod0].
                                          uint256 remainder;
                                          assembly {
                                              // Compute remainder using mulmod.
                                              remainder := mulmod(x, y, denominator)
                                              // Subtract 256 bit number from 512 bit number.
                                              prod1 := sub(prod1, gt(remainder, prod0))
                                              prod0 := sub(prod0, remainder)
                                          }
                                          // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
                                          // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
                                          uint256 twos = denominator & (0 - denominator);
                                          assembly {
                                              // Divide denominator by twos.
                                              denominator := div(denominator, twos)
                                              // Divide [prod1 prod0] by twos.
                                              prod0 := div(prod0, twos)
                                              // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                              twos := add(div(sub(0, twos), twos), 1)
                                          }
                                          // Shift in bits from prod1 into prod0.
                                          prod0 |= prod1 * twos;
                                          // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                          // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                          // four bits. That is, denominator * inv = 1 mod 2^4.
                                          uint256 inverse = (3 * denominator) ^ 2;
                                          // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
                                          // works in modular arithmetic, doubling the correct bits in each step.
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^256
                                          // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                          // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                          // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                          // is no longer required.
                                          result = prod0 * inverse;
                                          return result;
                                      }
                                  }
                                  /**
                                   * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                                      uint256 result = mulDiv(x, y, denominator);
                                      if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
                                          result += 1;
                                      }
                                      return result;
                                  }
                                  /**
                                   * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
                                   * towards zero.
                                   *
                                   * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                                   */
                                  function sqrt(uint256 a) internal pure returns (uint256) {
                                      if (a == 0) {
                                          return 0;
                                      }
                                      // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                      //
                                      // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                      // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                      //
                                      // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                      // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                      // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                      //
                                      // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                      uint256 result = 1 << (log2(a) >> 1);
                                      // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                      // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                      // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                      // into the expected uint128 result.
                                      unchecked {
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          return min(result, a / result);
                                      }
                                  }
                                  /**
                                   * @notice Calculates sqrt(a), following the selected rounding direction.
                                   */
                                  function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = sqrt(a);
                                          return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
                                      }
                                  }
                                  /**
                                   * @dev Return the log in base 2 of a positive value rounded towards zero.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 128;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 64;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 32;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 16;
                                          }
                                          if (value >> 8 > 0) {
                                              value >>= 8;
                                              result += 8;
                                          }
                                          if (value >> 4 > 0) {
                                              value >>= 4;
                                              result += 4;
                                          }
                                          if (value >> 2 > 0) {
                                              value >>= 2;
                                              result += 2;
                                          }
                                          if (value >> 1 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                                  /**
                                   * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log2(value);
                                          return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
                                      }
                                  }
                                  /**
                                   * @dev Return the log in base 10 of a positive value rounded towards zero.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >= 10 ** 64) {
                                              value /= 10 ** 64;
                                              result += 64;
                                          }
                                          if (value >= 10 ** 32) {
                                              value /= 10 ** 32;
                                              result += 32;
                                          }
                                          if (value >= 10 ** 16) {
                                              value /= 10 ** 16;
                                              result += 16;
                                          }
                                          if (value >= 10 ** 8) {
                                              value /= 10 ** 8;
                                              result += 8;
                                          }
                                          if (value >= 10 ** 4) {
                                              value /= 10 ** 4;
                                              result += 4;
                                          }
                                          if (value >= 10 ** 2) {
                                              value /= 10 ** 2;
                                              result += 2;
                                          }
                                          if (value >= 10 ** 1) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                                  /**
                                   * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log10(value);
                                          return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
                                      }
                                  }
                                  /**
                                   * @dev Return the log in base 256 of a positive value rounded towards zero.
                                   * Returns 0 if given 0.
                                   *
                                   * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                                   */
                                  function log256(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 16;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 8;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 4;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 2;
                                          }
                                          if (value >> 8 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                                  /**
                                   * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log256(value);
                                          return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
                                      }
                                  }
                                  /**
                                   * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
                                   */
                                  function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
                                      return uint8(rounding) % 2 == 1;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Provides information about the current execution context, including the
                               * sender of the transaction and its data. While these are generally available
                               * via msg.sender and msg.data, they should not be accessed in such a direct
                               * manner, since when dealing with meta-transactions the account sending and
                               * paying for execution may not be the actual sender (as far as an application
                               * is concerned).
                               *
                               * This contract is only required for intermediate, library-like contracts.
                               */
                              abstract contract Context {
                                  function _msgSender() internal view virtual returns (address) {
                                      return msg.sender;
                                  }
                                  function _msgData() internal view virtual returns (bytes calldata) {
                                      return msg.data;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Standard ERC20 Errors
                               * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
                               */
                              interface IERC20Errors {
                                  /**
                                   * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
                                   * @param sender Address whose tokens are being transferred.
                                   * @param balance Current balance for the interacting account.
                                   * @param needed Minimum amount required to perform a transfer.
                                   */
                                  error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
                                  /**
                                   * @dev Indicates a failure with the token `sender`. Used in transfers.
                                   * @param sender Address whose tokens are being transferred.
                                   */
                                  error ERC20InvalidSender(address sender);
                                  /**
                                   * @dev Indicates a failure with the token `receiver`. Used in transfers.
                                   * @param receiver Address to which tokens are being transferred.
                                   */
                                  error ERC20InvalidReceiver(address receiver);
                                  /**
                                   * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
                                   * @param spender Address that may be allowed to operate on tokens without being their owner.
                                   * @param allowance Amount of tokens a `spender` is allowed to operate with.
                                   * @param needed Minimum amount required to perform a transfer.
                                   */
                                  error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
                                  /**
                                   * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
                                   * @param approver Address initiating an approval operation.
                                   */
                                  error ERC20InvalidApprover(address approver);
                                  /**
                                   * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
                                   * @param spender Address that may be allowed to operate on tokens without being their owner.
                                   */
                                  error ERC20InvalidSpender(address spender);
                              }
                              /**
                               * @dev Standard ERC721 Errors
                               * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
                               */
                              interface IERC721Errors {
                                  /**
                                   * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
                                   * Used in balance queries.
                                   * @param owner Address of the current owner of a token.
                                   */
                                  error ERC721InvalidOwner(address owner);
                                  /**
                                   * @dev Indicates a `tokenId` whose `owner` is the zero address.
                                   * @param tokenId Identifier number of a token.
                                   */
                                  error ERC721NonexistentToken(uint256 tokenId);
                                  /**
                                   * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
                                   * @param sender Address whose tokens are being transferred.
                                   * @param tokenId Identifier number of a token.
                                   * @param owner Address of the current owner of a token.
                                   */
                                  error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
                                  /**
                                   * @dev Indicates a failure with the token `sender`. Used in transfers.
                                   * @param sender Address whose tokens are being transferred.
                                   */
                                  error ERC721InvalidSender(address sender);
                                  /**
                                   * @dev Indicates a failure with the token `receiver`. Used in transfers.
                                   * @param receiver Address to which tokens are being transferred.
                                   */
                                  error ERC721InvalidReceiver(address receiver);
                                  /**
                                   * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
                                   * @param operator Address that may be allowed to operate on tokens without being their owner.
                                   * @param tokenId Identifier number of a token.
                                   */
                                  error ERC721InsufficientApproval(address operator, uint256 tokenId);
                                  /**
                                   * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
                                   * @param approver Address initiating an approval operation.
                                   */
                                  error ERC721InvalidApprover(address approver);
                                  /**
                                   * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
                                   * @param operator Address that may be allowed to operate on tokens without being their owner.
                                   */
                                  error ERC721InvalidOperator(address operator);
                              }
                              /**
                               * @dev Standard ERC1155 Errors
                               * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
                               */
                              interface IERC1155Errors {
                                  /**
                                   * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
                                   * @param sender Address whose tokens are being transferred.
                                   * @param balance Current balance for the interacting account.
                                   * @param needed Minimum amount required to perform a transfer.
                                   * @param tokenId Identifier number of a token.
                                   */
                                  error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
                                  /**
                                   * @dev Indicates a failure with the token `sender`. Used in transfers.
                                   * @param sender Address whose tokens are being transferred.
                                   */
                                  error ERC1155InvalidSender(address sender);
                                  /**
                                   * @dev Indicates a failure with the token `receiver`. Used in transfers.
                                   * @param receiver Address to which tokens are being transferred.
                                   */
                                  error ERC1155InvalidReceiver(address receiver);
                                  /**
                                   * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
                                   * @param operator Address that may be allowed to operate on tokens without being their owner.
                                   * @param owner Address of the current owner of a token.
                                   */
                                  error ERC1155MissingApprovalForAll(address operator, address owner);
                                  /**
                                   * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
                                   * @param approver Address initiating an approval operation.
                                   */
                                  error ERC1155InvalidApprover(address approver);
                                  /**
                                   * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
                                   * @param operator Address that may be allowed to operate on tokens without being their owner.
                                   */
                                  error ERC1155InvalidOperator(address operator);
                                  /**
                                   * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
                                   * Used in batch transfers.
                                   * @param idsLength Length of the array of token identifiers
                                   * @param valuesLength Length of the array of token amounts
                                   */
                                  error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol)
                              pragma solidity ^0.8.20;
                              import {Strings} from "../Strings.sol";
                              /**
                               * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
                               *
                               * The library provides methods for generating a hash of a message that conforms to the
                               * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
                               * specifications.
                               */
                              library MessageHashUtils {
                                  /**
                                   * @dev Returns the keccak256 digest of an EIP-191 signed data with version
                                   * `0x45` (`personal_sign` messages).
                                   *
                                   * The digest is calculated by prefixing a bytes32 `messageHash` with
                                   * `"\\x19Ethereum Signed Message:\
                              32"` and hashing the result. It corresponds with the
                                   * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
                                   *
                                   * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
                                   * keccak256, although any bytes32 value can be safely used because the final digest will
                                   * be re-hashed.
                                   *
                                   * See {ECDSA-recover}.
                                   */
                                  function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          mstore(0x00, "\\x19Ethereum Signed Message:\
                              32") // 32 is the bytes-length of messageHash
                                          mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
                                          digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
                                      }
                                  }
                                  /**
                                   * @dev Returns the keccak256 digest of an EIP-191 signed data with version
                                   * `0x45` (`personal_sign` messages).
                                   *
                                   * The digest is calculated by prefixing an arbitrary `message` with
                                   * `"\\x19Ethereum Signed Message:\
                              " + len(message)` and hashing the result. It corresponds with the
                                   * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.
                                   *
                                   * See {ECDSA-recover}.
                                   */
                                  function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
                                      return
                                          keccak256(bytes.concat("\\x19Ethereum Signed Message:\
                              ", bytes(Strings.toString(message.length)), message));
                                  }
                                  /**
                                   * @dev Returns the keccak256 digest of an EIP-191 signed data with version
                                   * `0x00` (data with intended validator).
                                   *
                                   * The digest is calculated by prefixing an arbitrary `data` with `"\\x19\\x00"` and the intended
                                   * `validator` address. Then hashing the result.
                                   *
                                   * See {ECDSA-recover}.
                                   */
                                  function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
                                      return keccak256(abi.encodePacked(hex"19_00", validator, data));
                                  }
                                  /**
                                   * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
                                   *
                                   * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
                                   * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the
                                   * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
                                   *
                                   * See {ECDSA-recover}.
                                   */
                                  function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          let ptr := mload(0x40)
                                          mstore(ptr, hex"19_01")
                                          mstore(add(ptr, 0x02), domainSeparator)
                                          mstore(add(ptr, 0x22), structHash)
                                          digest := keccak256(ptr, 0x42)
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol)
                              pragma solidity ^0.8.20;
                              import {StorageSlot} from "./StorageSlot.sol";
                              // | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
                              // | length  | 0x                                                              BB |
                              type ShortString is bytes32;
                              /**
                               * @dev This library provides functions to convert short memory strings
                               * into a `ShortString` type that can be used as an immutable variable.
                               *
                               * Strings of arbitrary length can be optimized using this library if
                               * they are short enough (up to 31 bytes) by packing them with their
                               * length (1 byte) in a single EVM word (32 bytes). Additionally, a
                               * fallback mechanism can be used for every other case.
                               *
                               * Usage example:
                               *
                               * ```solidity
                               * contract Named {
                               *     using ShortStrings for *;
                               *
                               *     ShortString private immutable _name;
                               *     string private _nameFallback;
                               *
                               *     constructor(string memory contractName) {
                               *         _name = contractName.toShortStringWithFallback(_nameFallback);
                               *     }
                               *
                               *     function name() external view returns (string memory) {
                               *         return _name.toStringWithFallback(_nameFallback);
                               *     }
                               * }
                               * ```
                               */
                              library ShortStrings {
                                  // Used as an identifier for strings longer than 31 bytes.
                                  bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
                                  error StringTooLong(string str);
                                  error InvalidShortString();
                                  /**
                                   * @dev Encode a string of at most 31 chars into a `ShortString`.
                                   *
                                   * This will trigger a `StringTooLong` error is the input string is too long.
                                   */
                                  function toShortString(string memory str) internal pure returns (ShortString) {
                                      bytes memory bstr = bytes(str);
                                      if (bstr.length > 31) {
                                          revert StringTooLong(str);
                                      }
                                      return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
                                  }
                                  /**
                                   * @dev Decode a `ShortString` back to a "normal" string.
                                   */
                                  function toString(ShortString sstr) internal pure returns (string memory) {
                                      uint256 len = byteLength(sstr);
                                      // using `new string(len)` would work locally but is not memory safe.
                                      string memory str = new string(32);
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          mstore(str, len)
                                          mstore(add(str, 0x20), sstr)
                                      }
                                      return str;
                                  }
                                  /**
                                   * @dev Return the length of a `ShortString`.
                                   */
                                  function byteLength(ShortString sstr) internal pure returns (uint256) {
                                      uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
                                      if (result > 31) {
                                          revert InvalidShortString();
                                      }
                                      return result;
                                  }
                                  /**
                                   * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
                                   */
                                  function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
                                      if (bytes(value).length < 32) {
                                          return toShortString(value);
                                      } else {
                                          StorageSlot.getStringSlot(store).value = value;
                                          return ShortString.wrap(FALLBACK_SENTINEL);
                                      }
                                  }
                                  /**
                                   * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
                                   */
                                  function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
                                      if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
                                          return toString(value);
                                      } else {
                                          return store;
                                      }
                                  }
                                  /**
                                   * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
                                   * {setWithFallback}.
                                   *
                                   * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
                                   * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
                                   */
                                  function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
                                      if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
                                          return byteLength(value);
                                      } else {
                                          return bytes(store).length;
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
                              pragma solidity ^0.8.20;
                              interface IERC5267 {
                                  /**
                                   * @dev MAY be emitted to signal that the domain could have changed.
                                   */
                                  event EIP712DomainChanged();
                                  /**
                                   * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
                                   * signature.
                                   */
                                  function eip712Domain()
                                      external
                                      view
                                      returns (
                                          bytes1 fields,
                                          string memory name,
                                          string memory version,
                                          uint256 chainId,
                                          address verifyingContract,
                                          bytes32 salt,
                                          uint256[] memory extensions
                                      );
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
                              pragma solidity ^0.8.20;
                              import {Math} from "./math/Math.sol";
                              import {SignedMath} from "./math/SignedMath.sol";
                              /**
                               * @dev String operations.
                               */
                              library Strings {
                                  bytes16 private constant HEX_DIGITS = "0123456789abcdef";
                                  uint8 private constant ADDRESS_LENGTH = 20;
                                  /**
                                   * @dev The `value` string doesn't fit in the specified `length`.
                                   */
                                  error StringsInsufficientHexLength(uint256 value, uint256 length);
                                  /**
                                   * @dev Converts a `uint256` to its ASCII `string` decimal representation.
                                   */
                                  function toString(uint256 value) internal pure returns (string memory) {
                                      unchecked {
                                          uint256 length = Math.log10(value) + 1;
                                          string memory buffer = new string(length);
                                          uint256 ptr;
                                          /// @solidity memory-safe-assembly
                                          assembly {
                                              ptr := add(buffer, add(32, length))
                                          }
                                          while (true) {
                                              ptr--;
                                              /// @solidity memory-safe-assembly
                                              assembly {
                                                  mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                                              }
                                              value /= 10;
                                              if (value == 0) break;
                                          }
                                          return buffer;
                                      }
                                  }
                                  /**
                                   * @dev Converts a `int256` to its ASCII `string` decimal representation.
                                   */
                                  function toStringSigned(int256 value) internal pure returns (string memory) {
                                      return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
                                  }
                                  /**
                                   * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
                                   */
                                  function toHexString(uint256 value) internal pure returns (string memory) {
                                      unchecked {
                                          return toHexString(value, Math.log256(value) + 1);
                                      }
                                  }
                                  /**
                                   * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
                                   */
                                  function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
                                      uint256 localValue = value;
                                      bytes memory buffer = new bytes(2 * length + 2);
                                      buffer[0] = "0";
                                      buffer[1] = "x";
                                      for (uint256 i = 2 * length + 1; i > 1; --i) {
                                          buffer[i] = HEX_DIGITS[localValue & 0xf];
                                          localValue >>= 4;
                                      }
                                      if (localValue != 0) {
                                          revert StringsInsufficientHexLength(value, length);
                                      }
                                      return string(buffer);
                                  }
                                  /**
                                   * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
                                   * representation.
                                   */
                                  function toHexString(address addr) internal pure returns (string memory) {
                                      return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
                                  }
                                  /**
                                   * @dev Returns true if the two strings are equal.
                                   */
                                  function equal(string memory a, string memory b) internal pure returns (bool) {
                                      return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
                              // This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Library for reading and writing primitive types to specific storage slots.
                               *
                               * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
                               * This library helps with reading and writing to such slots without the need for inline assembly.
                               *
                               * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
                               *
                               * Example usage to set ERC1967 implementation slot:
                               * ```solidity
                               * contract ERC1967 {
                               *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
                               *
                               *     function _getImplementation() internal view returns (address) {
                               *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
                               *     }
                               *
                               *     function _setImplementation(address newImplementation) internal {
                               *         require(newImplementation.code.length > 0);
                               *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
                               *     }
                               * }
                               * ```
                               */
                              library StorageSlot {
                                  struct AddressSlot {
                                      address value;
                                  }
                                  struct BooleanSlot {
                                      bool value;
                                  }
                                  struct Bytes32Slot {
                                      bytes32 value;
                                  }
                                  struct Uint256Slot {
                                      uint256 value;
                                  }
                                  struct StringSlot {
                                      string value;
                                  }
                                  struct BytesSlot {
                                      bytes value;
                                  }
                                  /**
                                   * @dev Returns an `AddressSlot` with member `value` located at `slot`.
                                   */
                                  function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
                                   */
                                  function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
                                   */
                                  function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
                                   */
                                  function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `StringSlot` with member `value` located at `slot`.
                                   */
                                  function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
                                   */
                                  function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := store.slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `BytesSlot` with member `value` located at `slot`.
                                   */
                                  function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := slot
                                      }
                                  }
                                  /**
                                   * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
                                   */
                                  function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r.slot := store.slot
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
                              pragma solidity ^0.8.20;
                              /**
                               * @dev Standard signed math utilities missing in the Solidity language.
                               */
                              library SignedMath {
                                  /**
                                   * @dev Returns the largest of two signed numbers.
                                   */
                                  function max(int256 a, int256 b) internal pure returns (int256) {
                                      return a > b ? a : b;
                                  }
                                  /**
                                   * @dev Returns the smallest of two signed numbers.
                                   */
                                  function min(int256 a, int256 b) internal pure returns (int256) {
                                      return a < b ? a : b;
                                  }
                                  /**
                                   * @dev Returns the average of two signed numbers without overflow.
                                   * The result is rounded towards zero.
                                   */
                                  function average(int256 a, int256 b) internal pure returns (int256) {
                                      // Formula from the book "Hacker's Delight"
                                      int256 x = (a & b) + ((a ^ b) >> 1);
                                      return x + (int256(uint256(x) >> 255) & (a ^ b));
                                  }
                                  /**
                                   * @dev Returns the absolute unsigned value of a signed value.
                                   */
                                  function abs(int256 n) internal pure returns (uint256) {
                                      unchecked {
                                          // must be unchecked in order to support `n = type(int256).min`
                                          return uint256(n >= 0 ? n : -n);
                                      }
                                  }
                              }
                              

                              File 3 of 11: AdaptiveCurveIrm
                              // SPDX-License-Identifier: MIT
                              pragma solidity 0.8.19;
                              import {IIrm} from "../lib/morpho-blue/src/interfaces/IIrm.sol";
                              import {IAdaptiveCurveIrm} from "./interfaces/IAdaptiveCurveIrm.sol";
                              import {UtilsLib} from "./libraries/UtilsLib.sol";
                              import {ErrorsLib} from "./libraries/ErrorsLib.sol";
                              import {ExpLib} from "./libraries/adaptive-curve/ExpLib.sol";
                              import {MathLib, WAD_INT as WAD} from "./libraries/MathLib.sol";
                              import {ConstantsLib} from "./libraries/adaptive-curve/ConstantsLib.sol";
                              import {MarketParamsLib} from "../lib/morpho-blue/src/libraries/MarketParamsLib.sol";
                              import {Id, MarketParams, Market} from "../lib/morpho-blue/src/interfaces/IMorpho.sol";
                              import {MathLib as MorphoMathLib} from "../lib/morpho-blue/src/libraries/MathLib.sol";
                              /// @title AdaptiveCurveIrm
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              contract AdaptiveCurveIrm is IAdaptiveCurveIrm {
                                  using MathLib for int256;
                                  using UtilsLib for int256;
                                  using MorphoMathLib for uint128;
                                  using MarketParamsLib for MarketParams;
                                  /* EVENTS */
                                  /// @notice Emitted when a borrow rate is updated.
                                  event BorrowRateUpdate(Id indexed id, uint256 avgBorrowRate, uint256 rateAtTarget);
                                  /* IMMUTABLES */
                                  /// @inheritdoc IAdaptiveCurveIrm
                                  address public immutable MORPHO;
                                  /* STORAGE */
                                  /// @inheritdoc IAdaptiveCurveIrm
                                  mapping(Id => int256) public rateAtTarget;
                                  /* CONSTRUCTOR */
                                  /// @notice Constructor.
                                  /// @param morpho The address of Morpho.
                                  constructor(address morpho) {
                                      require(morpho != address(0), ErrorsLib.ZERO_ADDRESS);
                                      MORPHO = morpho;
                                  }
                                  /* BORROW RATES */
                                  /// @inheritdoc IIrm
                                  function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256) {
                                      (uint256 avgRate,) = _borrowRate(marketParams.id(), market);
                                      return avgRate;
                                  }
                                  /// @inheritdoc IIrm
                                  function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256) {
                                      require(msg.sender == MORPHO, ErrorsLib.NOT_MORPHO);
                                      Id id = marketParams.id();
                                      (uint256 avgRate, int256 endRateAtTarget) = _borrowRate(id, market);
                                      rateAtTarget[id] = endRateAtTarget;
                                      // Safe "unchecked" cast because endRateAtTarget >= 0.
                                      emit BorrowRateUpdate(id, avgRate, uint256(endRateAtTarget));
                                      return avgRate;
                                  }
                                  /// @dev Returns avgRate and endRateAtTarget.
                                  /// @dev Assumes that the inputs `marketParams` and `id` match.
                                  function _borrowRate(Id id, Market memory market) private view returns (uint256, int256) {
                                      // Safe "unchecked" cast because the utilization is smaller than 1 (scaled by WAD).
                                      int256 utilization =
                                          int256(market.totalSupplyAssets > 0 ? market.totalBorrowAssets.wDivDown(market.totalSupplyAssets) : 0);
                                      int256 errNormFactor = utilization > ConstantsLib.TARGET_UTILIZATION
                                          ? WAD - ConstantsLib.TARGET_UTILIZATION
                                          : ConstantsLib.TARGET_UTILIZATION;
                                      int256 err = (utilization - ConstantsLib.TARGET_UTILIZATION).wDivToZero(errNormFactor);
                                      int256 startRateAtTarget = rateAtTarget[id];
                                      int256 avgRateAtTarget;
                                      int256 endRateAtTarget;
                                      if (startRateAtTarget == 0) {
                                          // First interaction.
                                          avgRateAtTarget = ConstantsLib.INITIAL_RATE_AT_TARGET;
                                          endRateAtTarget = ConstantsLib.INITIAL_RATE_AT_TARGET;
                                      } else {
                                          // The speed is assumed constant between two updates, but it is in fact not constant because of interest.
                                          // So the rate is always underestimated.
                                          int256 speed = ConstantsLib.ADJUSTMENT_SPEED.wMulToZero(err);
                                          // market.lastUpdate != 0 because it is not the first interaction with this market.
                                          // Safe "unchecked" cast because block.timestamp - market.lastUpdate <= block.timestamp <= type(int256).max.
                                          int256 elapsed = int256(block.timestamp - market.lastUpdate);
                                          int256 linearAdaptation = speed * elapsed;
                                          if (linearAdaptation == 0) {
                                              // If linearAdaptation == 0, avgRateAtTarget = endRateAtTarget = startRateAtTarget;
                                              avgRateAtTarget = startRateAtTarget;
                                              endRateAtTarget = startRateAtTarget;
                                          } else {
                                              // Formula of the average rate that should be returned to Morpho Blue:
                                              // avg = 1/T * ∫_0^T curve(startRateAtTarget*exp(speed*x), err) dx
                                              // The integral is approximated with the trapezoidal rule:
                                              // avg ~= 1/T * Σ_i=1^N [curve(f((i-1) * T/N), err) + curve(f(i * T/N), err)] / 2 * T/N
                                              // Where f(x) = startRateAtTarget*exp(speed*x)
                                              // avg ~= Σ_i=1^N [curve(f((i-1) * T/N), err) + curve(f(i * T/N), err)] / (2 * N)
                                              // As curve is linear in its first argument:
                                              // avg ~= curve([Σ_i=1^N [f((i-1) * T/N) + f(i * T/N)] / (2 * N), err)
                                              // avg ~= curve([(f(0) + f(T))/2 + Σ_i=1^(N-1) f(i * T/N)] / N, err)
                                              // avg ~= curve([(startRateAtTarget + endRateAtTarget)/2 + Σ_i=1^(N-1) f(i * T/N)] / N, err)
                                              // With N = 2:
                                              // avg ~= curve([(startRateAtTarget + endRateAtTarget)/2 + startRateAtTarget*exp(speed*T/2)] / 2, err)
                                              // avg ~= curve([startRateAtTarget + endRateAtTarget + 2*startRateAtTarget*exp(speed*T/2)] / 4, err)
                                              endRateAtTarget = _newRateAtTarget(startRateAtTarget, linearAdaptation);
                                              int256 midRateAtTarget = _newRateAtTarget(startRateAtTarget, linearAdaptation / 2);
                                              avgRateAtTarget = (startRateAtTarget + endRateAtTarget + 2 * midRateAtTarget) / 4;
                                          }
                                      }
                                      // Safe "unchecked" cast because avgRateAtTarget >= 0.
                                      return (uint256(_curve(avgRateAtTarget, err)), endRateAtTarget);
                                  }
                                  /// @dev Returns the rate for a given `_rateAtTarget` and an `err`.
                                  /// The formula of the curve is the following:
                                  /// r = ((1-1/C)*err + 1) * rateAtTarget if err < 0
                                  ///     ((C-1)*err + 1) * rateAtTarget else.
                                  function _curve(int256 _rateAtTarget, int256 err) private pure returns (int256) {
                                      // Non negative because 1 - 1/C >= 0, C - 1 >= 0.
                                      int256 coeff = err < 0 ? WAD - WAD.wDivToZero(ConstantsLib.CURVE_STEEPNESS) : ConstantsLib.CURVE_STEEPNESS - WAD;
                                      // Non negative if _rateAtTarget >= 0 because if err < 0, coeff <= 1.
                                      return (coeff.wMulToZero(err) + WAD).wMulToZero(int256(_rateAtTarget));
                                  }
                                  /// @dev Returns the new rate at target, for a given `startRateAtTarget` and a given `linearAdaptation`.
                                  /// The formula is: max(min(startRateAtTarget * exp(linearAdaptation), maxRateAtTarget), minRateAtTarget).
                                  function _newRateAtTarget(int256 startRateAtTarget, int256 linearAdaptation) private pure returns (int256) {
                                      // Non negative because MIN_RATE_AT_TARGET > 0.
                                      return startRateAtTarget.wMulToZero(ExpLib.wExp(linearAdaptation)).bound(
                                          ConstantsLib.MIN_RATE_AT_TARGET, ConstantsLib.MAX_RATE_AT_TARGET
                                      );
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              import {MarketParams, Market} from "./IMorpho.sol";
                              /// @title IIrm
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
                              interface IIrm {
                                  /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
                                  /// @dev Assumes that `market` corresponds to `marketParams`.
                                  function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);
                                  /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
                                  /// storage.
                                  /// @dev Assumes that `market` corresponds to `marketParams`.
                                  function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.5.0;
                              import {IIrm} from "../../lib/morpho-blue/src/interfaces/IIrm.sol";
                              import {Id} from "../../lib/morpho-blue/src/interfaces/IMorpho.sol";
                              /// @title IAdaptiveCurveIrm
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Interface exposed by the AdaptiveCurveIrm.
                              interface IAdaptiveCurveIrm is IIrm {
                                  /// @notice Address of Morpho.
                                  function MORPHO() external view returns (address);
                                  /// @notice Rate at target utilization.
                                  /// @dev Tells the height of the curve.
                                  function rateAtTarget(Id id) external view returns (int256);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              /// @title UtilsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing helpers.
                              library UtilsLib {
                                  /// @dev Bounds `x` between `low` and `high`.
                                  /// @dev Assumes that `low` <= `high`. If it is not the case it returns `low`.
                                  function bound(int256 x, int256 low, int256 high) internal pure returns (int256 z) {
                                      assembly {
                                          // z = min(x, high).
                                          z := xor(x, mul(xor(x, high), slt(high, x)))
                                          // z = max(z, low).
                                          z := xor(z, mul(xor(z, low), sgt(low, z)))
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              /// @title ErrorsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing error messages.
                              library ErrorsLib {
                                  /// @dev Thrown when passing the zero address.
                                  string internal constant ZERO_ADDRESS = "zero address";
                                  /// @dev Thrown when the caller is not Morpho.
                                  string internal constant NOT_MORPHO = "not Morpho";
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              import {WAD_INT} from "../MathLib.sol";
                              /// @title ExpLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to approximate the exponential function.
                              library ExpLib {
                                  /// @dev ln(2).
                                  int256 internal constant LN_2_INT = 0.693147180559945309 ether;
                                  /// @dev ln(1e-18).
                                  int256 internal constant LN_WEI_INT = -41.446531673892822312 ether;
                                  /// @dev Above this bound, `wExp` is clipped to avoid overflowing when multiplied with 1 ether.
                                  /// @dev This upper bound corresponds to: ln(type(int256).max / 1e36) (scaled by WAD, floored).
                                  int256 internal constant WEXP_UPPER_BOUND = 93.859467695000404319 ether;
                                  /// @dev The value of wExp(`WEXP_UPPER_BOUND`).
                                  int256 internal constant WEXP_UPPER_VALUE = 57716089161558943949701069502944508345128.422502756744429568 ether;
                                  /// @dev Returns an approximation of exp.
                                  function wExp(int256 x) internal pure returns (int256) {
                                      unchecked {
                                          // If x < ln(1e-18) then exp(x) < 1e-18 so it is rounded to zero.
                                          if (x < LN_WEI_INT) return 0;
                                          // `wExp` is clipped to avoid overflowing when multiplied with 1 ether.
                                          if (x >= WEXP_UPPER_BOUND) return WEXP_UPPER_VALUE;
                                          // Decompose x as x = q * ln(2) + r with q an integer and -ln(2)/2 <= r <= ln(2)/2.
                                          // q = x / ln(2) rounded half toward zero.
                                          int256 roundingAdjustment = (x < 0) ? -(LN_2_INT / 2) : (LN_2_INT / 2);
                                          // Safe unchecked because x is bounded.
                                          int256 q = (x + roundingAdjustment) / LN_2_INT;
                                          // Safe unchecked because |q * ln(2) - x| <= ln(2)/2.
                                          int256 r = x - q * LN_2_INT;
                                          // Compute e^r with a 2nd-order Taylor polynomial.
                                          // Safe unchecked because |r| < 1e18.
                                          int256 expR = WAD_INT + r + (r * r) / WAD_INT / 2;
                                          // Return e^x = 2^q * e^r.
                                          if (q >= 0) return expR << uint256(q);
                                          else return expR >> uint256(-q);
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              import {WAD} from "../../lib/morpho-blue/src/libraries/MathLib.sol";
                              int256 constant WAD_INT = int256(WAD);
                              /// @title MathLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to manage fixed-point arithmetic on signed integers.
                              library MathLib {
                                  /// @dev Returns the multiplication of `x` by `y` (in WAD) rounded towards 0.
                                  function wMulToZero(int256 x, int256 y) internal pure returns (int256) {
                                      return (x * y) / WAD_INT;
                                  }
                                  /// @dev Returns the division of `x` by `y` (in WAD) rounded towards 0.
                                  function wDivToZero(int256 x, int256 y) internal pure returns (int256) {
                                      return (x * WAD_INT) / y;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity ^0.8.0;
                              /// @title ConstantsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              library ConstantsLib {
                                  /// @notice Curve steepness (scaled by WAD).
                                  /// @dev Curve steepness = 4.
                                  int256 public constant CURVE_STEEPNESS = 4 ether;
                                  /// @notice Adjustment speed per second (scaled by WAD).
                                  /// @dev The speed is per second, so the rate moves at a speed of ADJUSTMENT_SPEED * err each second (while being
                                  /// continuously compounded).
                                  /// @dev Adjustment speed = 50/year.
                                  int256 public constant ADJUSTMENT_SPEED = 50 ether / int256(365 days);
                                  /// @notice Target utilization (scaled by WAD).
                                  /// @dev Target utilization = 90%.
                                  int256 public constant TARGET_UTILIZATION = 0.9 ether;
                                  /// @notice Initial rate at target per second (scaled by WAD).
                                  /// @dev Initial rate at target = 4% (rate between 1% and 16%).
                                  int256 public constant INITIAL_RATE_AT_TARGET = 0.04 ether / int256(365 days);
                                  /// @notice Minimum rate at target per second (scaled by WAD).
                                  /// @dev Minimum rate at target = 0.1% (minimum rate = 0.025%).
                                  int256 public constant MIN_RATE_AT_TARGET = 0.001 ether / int256(365 days);
                                  /// @notice Maximum rate at target per second (scaled by WAD).
                                  /// @dev Maximum rate at target = 200% (maximum rate = 800%).
                                  int256 public constant MAX_RATE_AT_TARGET = 2.0 ether / int256(365 days);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id, MarketParams} from "../interfaces/IMorpho.sol";
                              /// @title MarketParamsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to convert a market to its id.
                              library MarketParamsLib {
                                  /// @notice The length of the data used to compute the id of a market.
                                  /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
                                  uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;
                                  /// @notice Returns the id of the market `marketParams`.
                                  function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
                                      assembly ("memory-safe") {
                                          marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              type Id is bytes32;
                              struct MarketParams {
                                  address loanToken;
                                  address collateralToken;
                                  address oracle;
                                  address irm;
                                  uint256 lltv;
                              }
                              /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
                              /// accrual.
                              struct Position {
                                  uint256 supplyShares;
                                  uint128 borrowShares;
                                  uint128 collateral;
                              }
                              /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                              /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                              /// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
                              /// interest accrual.
                              struct Market {
                                  uint128 totalSupplyAssets;
                                  uint128 totalSupplyShares;
                                  uint128 totalBorrowAssets;
                                  uint128 totalBorrowShares;
                                  uint128 lastUpdate;
                                  uint128 fee;
                              }
                              struct Authorization {
                                  address authorizer;
                                  address authorized;
                                  bool isAuthorized;
                                  uint256 nonce;
                                  uint256 deadline;
                              }
                              struct Signature {
                                  uint8 v;
                                  bytes32 r;
                                  bytes32 s;
                              }
                              /// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
                              /// @dev Consider using the IMorpho interface instead of this one.
                              interface IMorphoBase {
                                  /// @notice The EIP-712 domain separator.
                                  /// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on another chain sharing
                                  /// the same chain id because the domain separator would be the same.
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                                  /// @notice The owner of the contract.
                                  /// @dev It has the power to change the owner.
                                  /// @dev It has the power to set fees on markets and set the fee recipient.
                                  /// @dev It has the power to enable but not disable IRMs and LLTVs.
                                  function owner() external view returns (address);
                                  /// @notice The fee recipient of all markets.
                                  /// @dev The recipient receives the fees of a given market through a supply position on that market.
                                  function feeRecipient() external view returns (address);
                                  /// @notice Whether the `irm` is enabled.
                                  function isIrmEnabled(address irm) external view returns (bool);
                                  /// @notice Whether the `lltv` is enabled.
                                  function isLltvEnabled(uint256 lltv) external view returns (bool);
                                  /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
                                  /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
                                  function isAuthorized(address authorizer, address authorized) external view returns (bool);
                                  /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
                                  function nonce(address authorizer) external view returns (uint256);
                                  /// @notice Sets `newOwner` as `owner` of the contract.
                                  /// @dev Warning: No two-step transfer ownership.
                                  /// @dev Warning: The owner can be set to the zero address.
                                  function setOwner(address newOwner) external;
                                  /// @notice Enables `irm` as a possible IRM for market creation.
                                  /// @dev Warning: It is not possible to disable an IRM.
                                  function enableIrm(address irm) external;
                                  /// @notice Enables `lltv` as a possible LLTV for market creation.
                                  /// @dev Warning: It is not possible to disable a LLTV.
                                  function enableLltv(uint256 lltv) external;
                                  /// @notice Sets the `newFee` for the given market `marketParams`.
                                  /// @param newFee The new fee, scaled by WAD.
                                  /// @dev Warning: The recipient can be the zero address.
                                  function setFee(MarketParams memory marketParams, uint256 newFee) external;
                                  /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
                                  /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
                                  /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
                                  /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
                                  function setFeeRecipient(address newFeeRecipient) external;
                                  /// @notice Creates the market `marketParams`.
                                  /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
                                  /// Morpho behaves as expected:
                                  /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
                                  /// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
                                  /// burn functions are not supported.
                                  /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
                                  /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
                                  /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
                                  /// - The IRM should not re-enter Morpho.
                                  /// - The oracle should return a price with the correct scaling.
                                  /// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties
                                  /// (funds could get stuck):
                                  /// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
                                  /// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
                                  /// `toSharesDown` overflow.
                                  /// - The IRM can revert on `borrowRate`.
                                  /// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
                                  /// overflow.
                                  /// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
                                  /// `liquidate` from being used under certain market conditions.
                                  /// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
                                  /// the computation of `assetsRepaid` in `liquidate` overflow.
                                  /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
                                  /// the point where `totalBorrowShares` is very large and borrowing overflows.
                                  function createMarket(MarketParams memory marketParams) external;
                                  /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoSupply` function with the given `data`.
                                  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
                                  /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
                                  /// amount of shares is given for full compatibility and precision.
                                  /// @dev Supplying a large amount can revert for overflow.
                                  /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
                                  /// Consider using the `assets` parameter to avoid this.
                                  /// @param marketParams The market to supply assets to.
                                  /// @param assets The amount of assets to supply.
                                  /// @param shares The amount of shares to mint.
                                  /// @param onBehalf The address that will own the increased supply position.
                                  /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
                                  /// @return assetsSupplied The amount of assets supplied.
                                  /// @return sharesSupplied The amount of shares minted.
                                  function supply(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes memory data
                                  ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
                                  /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
                                  /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
                                  /// conversion roundings between shares and assets.
                                  /// @param marketParams The market to withdraw assets from.
                                  /// @param assets The amount of assets to withdraw.
                                  /// @param shares The amount of shares to burn.
                                  /// @param onBehalf The address of the owner of the supply position.
                                  /// @param receiver The address that will receive the withdrawn assets.
                                  /// @return assetsWithdrawn The amount of assets withdrawn.
                                  /// @return sharesWithdrawn The amount of shares burned.
                                  function withdraw(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
                                  /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
                                  /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
                                  /// given for full compatibility and precision.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Borrowing a large amount can revert for overflow.
                                  /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
                                  /// Consider using the `assets` parameter to avoid this.
                                  /// @param marketParams The market to borrow assets from.
                                  /// @param assets The amount of assets to borrow.
                                  /// @param shares The amount of shares to mint.
                                  /// @param onBehalf The address that will own the increased borrow position.
                                  /// @param receiver The address that will receive the borrowed assets.
                                  /// @return assetsBorrowed The amount of assets borrowed.
                                  /// @return sharesBorrowed The amount of shares minted.
                                  function borrow(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
                                  /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoReplay` function with the given `data`.
                                  /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
                                  /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
                                  /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
                                  /// roundings between shares and assets.
                                  /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
                                  /// @param marketParams The market to repay assets to.
                                  /// @param assets The amount of assets to repay.
                                  /// @param shares The amount of shares to burn.
                                  /// @param onBehalf The address of the owner of the debt position.
                                  /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
                                  /// @return assetsRepaid The amount of assets repaid.
                                  /// @return sharesRepaid The amount of shares burned.
                                  function repay(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes memory data
                                  ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
                                  /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoSupplyCollateral` function with the given `data`.
                                  /// @dev Interest are not accrued since it's not required and it saves gas.
                                  /// @dev Supplying a large amount can revert for overflow.
                                  /// @param marketParams The market to supply collateral to.
                                  /// @param assets The amount of collateral to supply.
                                  /// @param onBehalf The address that will own the increased collateral position.
                                  /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
                                  function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
                                      external;
                                  /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
                                  /// @param marketParams The market to withdraw collateral from.
                                  /// @param assets The amount of collateral to withdraw.
                                  /// @param onBehalf The address of the owner of the collateral position.
                                  /// @param receiver The address that will receive the collateral assets.
                                  function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
                                      external;
                                  /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
                                  /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
                                  /// `onMorphoLiquidate` function with the given `data`.
                                  /// @dev Either `seizedAssets` or `repaidShares` should be zero.
                                  /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
                                  /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
                                  /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
                                  /// @param marketParams The market of the position.
                                  /// @param borrower The owner of the position.
                                  /// @param seizedAssets The amount of collateral to seize.
                                  /// @param repaidShares The amount of shares to repay.
                                  /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
                                  /// @return The amount of assets seized.
                                  /// @return The amount of assets repaid.
                                  function liquidate(
                                      MarketParams memory marketParams,
                                      address borrower,
                                      uint256 seizedAssets,
                                      uint256 repaidShares,
                                      bytes memory data
                                  ) external returns (uint256, uint256);
                                  /// @notice Executes a flash loan.
                                  /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
                                  /// markets combined, plus donations).
                                  /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
                                  /// - `flashFee` is zero.
                                  /// - `maxFlashLoan` is the token's balance of this contract.
                                  /// - The receiver of `assets` is the caller.
                                  /// @param token The token to flash loan.
                                  /// @param assets The amount of assets to flash loan.
                                  /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
                                  function flashLoan(address token, uint256 assets, bytes calldata data) external;
                                  /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
                                  /// @param authorized The authorized address.
                                  /// @param newIsAuthorized The new authorization status.
                                  function setAuthorization(address authorized, bool newIsAuthorized) external;
                                  /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
                                  /// @dev Warning: Reverts if the signature has already been submitted.
                                  /// @dev The signature is malleable, but it has no impact on the security here.
                                  /// @dev The nonce is passed as argument to be able to revert with a different error message.
                                  /// @param authorization The `Authorization` struct.
                                  /// @param signature The signature.
                                  function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
                                  /// @notice Accrues interest for the given market `marketParams`.
                                  function accrueInterest(MarketParams memory marketParams) external;
                                  /// @notice Returns the data stored on the different `slots`.
                                  function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
                              }
                              /// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
                              /// @dev Consider using the IMorpho interface instead of this one.
                              interface IMorphoStaticTyping is IMorphoBase {
                                  /// @notice The state of the position of `user` on the market corresponding to `id`.
                                  /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
                                  /// accrual.
                                  function position(Id id, address user)
                                      external
                                      view
                                      returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
                                  /// @notice The state of the market corresponding to `id`.
                                  /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
                                  /// accrual.
                                  function market(Id id)
                                      external
                                      view
                                      returns (
                                          uint128 totalSupplyAssets,
                                          uint128 totalSupplyShares,
                                          uint128 totalBorrowAssets,
                                          uint128 totalBorrowShares,
                                          uint128 lastUpdate,
                                          uint128 fee
                                      );
                                  /// @notice The market params corresponding to `id`.
                                  /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
                                  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
                                  function idToMarketParams(Id id)
                                      external
                                      view
                                      returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
                              }
                              /// @title IMorpho
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
                              interface IMorpho is IMorphoBase {
                                  /// @notice The state of the position of `user` on the market corresponding to `id`.
                                  /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
                                  /// accrual.
                                  function position(Id id, address user) external view returns (Position memory p);
                                  /// @notice The state of the market corresponding to `id`.
                                  /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
                                  /// interest accrual.
                                  function market(Id id) external view returns (Market memory m);
                                  /// @notice The market params corresponding to `id`.
                                  /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
                                  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
                                  function idToMarketParams(Id id) external view returns (MarketParams memory);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              uint256 constant WAD = 1e18;
                              /// @title MathLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to manage fixed-point arithmetic.
                              library MathLib {
                                  /// @dev Returns (`x` * `y`) / `WAD` rounded down.
                                  function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivDown(x, y, WAD);
                                  }
                                  /// @dev Returns (`x` * `WAD`) / `y` rounded down.
                                  function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivDown(x, WAD, y);
                                  }
                                  /// @dev Returns (`x` * `WAD`) / `y` rounded up.
                                  function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivUp(x, WAD, y);
                                  }
                                  /// @dev Returns (`x` * `y`) / `d` rounded down.
                                  function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
                                      return (x * y) / d;
                                  }
                                  /// @dev Returns (`x` * `y`) / `d` rounded up.
                                  function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
                                      return (x * y + (d - 1)) / d;
                                  }
                                  /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
                                  /// continuous compound interest rate.
                                  function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
                                      uint256 firstTerm = x * n;
                                      uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
                                      uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);
                                      return firstTerm + secondTerm + thirdTerm;
                                  }
                              }
                              

                              File 4 of 11: Morpho
                              // SPDX-License-Identifier: BUSL-1.1
                              pragma solidity 0.8.19;
                              import {
                                  Id,
                                  IMorphoStaticTyping,
                                  IMorphoBase,
                                  MarketParams,
                                  Position,
                                  Market,
                                  Authorization,
                                  Signature
                              } from "./interfaces/IMorpho.sol";
                              import {
                                  IMorphoLiquidateCallback,
                                  IMorphoRepayCallback,
                                  IMorphoSupplyCallback,
                                  IMorphoSupplyCollateralCallback,
                                  IMorphoFlashLoanCallback
                              } from "./interfaces/IMorphoCallbacks.sol";
                              import {IIrm} from "./interfaces/IIrm.sol";
                              import {IERC20} from "./interfaces/IERC20.sol";
                              import {IOracle} from "./interfaces/IOracle.sol";
                              import "./libraries/ConstantsLib.sol";
                              import {UtilsLib} from "./libraries/UtilsLib.sol";
                              import {EventsLib} from "./libraries/EventsLib.sol";
                              import {ErrorsLib} from "./libraries/ErrorsLib.sol";
                              import {MathLib, WAD} from "./libraries/MathLib.sol";
                              import {SharesMathLib} from "./libraries/SharesMathLib.sol";
                              import {MarketParamsLib} from "./libraries/MarketParamsLib.sol";
                              import {SafeTransferLib} from "./libraries/SafeTransferLib.sol";
                              /// @title Morpho
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice The Morpho contract.
                              contract Morpho is IMorphoStaticTyping {
                                  using MathLib for uint128;
                                  using MathLib for uint256;
                                  using UtilsLib for uint256;
                                  using SharesMathLib for uint256;
                                  using SafeTransferLib for IERC20;
                                  using MarketParamsLib for MarketParams;
                                  /* IMMUTABLES */
                                  /// @inheritdoc IMorphoBase
                                  bytes32 public immutable DOMAIN_SEPARATOR;
                                  /* STORAGE */
                                  /// @inheritdoc IMorphoBase
                                  address public owner;
                                  /// @inheritdoc IMorphoBase
                                  address public feeRecipient;
                                  /// @inheritdoc IMorphoStaticTyping
                                  mapping(Id => mapping(address => Position)) public position;
                                  /// @inheritdoc IMorphoStaticTyping
                                  mapping(Id => Market) public market;
                                  /// @inheritdoc IMorphoBase
                                  mapping(address => bool) public isIrmEnabled;
                                  /// @inheritdoc IMorphoBase
                                  mapping(uint256 => bool) public isLltvEnabled;
                                  /// @inheritdoc IMorphoBase
                                  mapping(address => mapping(address => bool)) public isAuthorized;
                                  /// @inheritdoc IMorphoBase
                                  mapping(address => uint256) public nonce;
                                  /// @inheritdoc IMorphoStaticTyping
                                  mapping(Id => MarketParams) public idToMarketParams;
                                  /* CONSTRUCTOR */
                                  /// @param newOwner The new owner of the contract.
                                  constructor(address newOwner) {
                                      require(newOwner != address(0), ErrorsLib.ZERO_ADDRESS);
                                      DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, block.chainid, address(this)));
                                      owner = newOwner;
                                      emit EventsLib.SetOwner(newOwner);
                                  }
                                  /* MODIFIERS */
                                  /// @dev Reverts if the caller is not the owner.
                                  modifier onlyOwner() {
                                      require(msg.sender == owner, ErrorsLib.NOT_OWNER);
                                      _;
                                  }
                                  /* ONLY OWNER FUNCTIONS */
                                  /// @inheritdoc IMorphoBase
                                  function setOwner(address newOwner) external onlyOwner {
                                      require(newOwner != owner, ErrorsLib.ALREADY_SET);
                                      owner = newOwner;
                                      emit EventsLib.SetOwner(newOwner);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function enableIrm(address irm) external onlyOwner {
                                      require(!isIrmEnabled[irm], ErrorsLib.ALREADY_SET);
                                      isIrmEnabled[irm] = true;
                                      emit EventsLib.EnableIrm(irm);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function enableLltv(uint256 lltv) external onlyOwner {
                                      require(!isLltvEnabled[lltv], ErrorsLib.ALREADY_SET);
                                      require(lltv < WAD, ErrorsLib.MAX_LLTV_EXCEEDED);
                                      isLltvEnabled[lltv] = true;
                                      emit EventsLib.EnableLltv(lltv);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function setFee(MarketParams memory marketParams, uint256 newFee) external onlyOwner {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(newFee != market[id].fee, ErrorsLib.ALREADY_SET);
                                      require(newFee <= MAX_FEE, ErrorsLib.MAX_FEE_EXCEEDED);
                                      // Accrue interest using the previous fee set before changing it.
                                      _accrueInterest(marketParams, id);
                                      // Safe "unchecked" cast.
                                      market[id].fee = uint128(newFee);
                                      emit EventsLib.SetFee(id, newFee);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function setFeeRecipient(address newFeeRecipient) external onlyOwner {
                                      require(newFeeRecipient != feeRecipient, ErrorsLib.ALREADY_SET);
                                      feeRecipient = newFeeRecipient;
                                      emit EventsLib.SetFeeRecipient(newFeeRecipient);
                                  }
                                  /* MARKET CREATION */
                                  /// @inheritdoc IMorphoBase
                                  function createMarket(MarketParams memory marketParams) external {
                                      Id id = marketParams.id();
                                      require(isIrmEnabled[marketParams.irm], ErrorsLib.IRM_NOT_ENABLED);
                                      require(isLltvEnabled[marketParams.lltv], ErrorsLib.LLTV_NOT_ENABLED);
                                      require(market[id].lastUpdate == 0, ErrorsLib.MARKET_ALREADY_CREATED);
                                      // Safe "unchecked" cast.
                                      market[id].lastUpdate = uint128(block.timestamp);
                                      idToMarketParams[id] = marketParams;
                                      emit EventsLib.CreateMarket(id, marketParams);
                                      // Call to initialize the IRM in case it is stateful.
                                      if (marketParams.irm != address(0)) IIrm(marketParams.irm).borrowRate(marketParams, market[id]);
                                  }
                                  /* SUPPLY MANAGEMENT */
                                  /// @inheritdoc IMorphoBase
                                  function supply(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes calldata data
                                  ) external returns (uint256, uint256) {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(UtilsLib.exactlyOneZero(assets, shares), ErrorsLib.INCONSISTENT_INPUT);
                                      require(onBehalf != address(0), ErrorsLib.ZERO_ADDRESS);
                                      _accrueInterest(marketParams, id);
                                      if (assets > 0) shares = assets.toSharesDown(market[id].totalSupplyAssets, market[id].totalSupplyShares);
                                      else assets = shares.toAssetsUp(market[id].totalSupplyAssets, market[id].totalSupplyShares);
                                      position[id][onBehalf].supplyShares += shares;
                                      market[id].totalSupplyShares += shares.toUint128();
                                      market[id].totalSupplyAssets += assets.toUint128();
                                      emit EventsLib.Supply(id, msg.sender, onBehalf, assets, shares);
                                      if (data.length > 0) IMorphoSupplyCallback(msg.sender).onMorphoSupply(assets, data);
                                      IERC20(marketParams.loanToken).safeTransferFrom(msg.sender, address(this), assets);
                                      return (assets, shares);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function withdraw(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256, uint256) {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(UtilsLib.exactlyOneZero(assets, shares), ErrorsLib.INCONSISTENT_INPUT);
                                      require(receiver != address(0), ErrorsLib.ZERO_ADDRESS);
                                      // No need to verify that onBehalf != address(0) thanks to the following authorization check.
                                      require(_isSenderAuthorized(onBehalf), ErrorsLib.UNAUTHORIZED);
                                      _accrueInterest(marketParams, id);
                                      if (assets > 0) shares = assets.toSharesUp(market[id].totalSupplyAssets, market[id].totalSupplyShares);
                                      else assets = shares.toAssetsDown(market[id].totalSupplyAssets, market[id].totalSupplyShares);
                                      position[id][onBehalf].supplyShares -= shares;
                                      market[id].totalSupplyShares -= shares.toUint128();
                                      market[id].totalSupplyAssets -= assets.toUint128();
                                      require(market[id].totalBorrowAssets <= market[id].totalSupplyAssets, ErrorsLib.INSUFFICIENT_LIQUIDITY);
                                      emit EventsLib.Withdraw(id, msg.sender, onBehalf, receiver, assets, shares);
                                      IERC20(marketParams.loanToken).safeTransfer(receiver, assets);
                                      return (assets, shares);
                                  }
                                  /* BORROW MANAGEMENT */
                                  /// @inheritdoc IMorphoBase
                                  function borrow(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256, uint256) {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(UtilsLib.exactlyOneZero(assets, shares), ErrorsLib.INCONSISTENT_INPUT);
                                      require(receiver != address(0), ErrorsLib.ZERO_ADDRESS);
                                      // No need to verify that onBehalf != address(0) thanks to the following authorization check.
                                      require(_isSenderAuthorized(onBehalf), ErrorsLib.UNAUTHORIZED);
                                      _accrueInterest(marketParams, id);
                                      if (assets > 0) shares = assets.toSharesUp(market[id].totalBorrowAssets, market[id].totalBorrowShares);
                                      else assets = shares.toAssetsDown(market[id].totalBorrowAssets, market[id].totalBorrowShares);
                                      position[id][onBehalf].borrowShares += shares.toUint128();
                                      market[id].totalBorrowShares += shares.toUint128();
                                      market[id].totalBorrowAssets += assets.toUint128();
                                      require(_isHealthy(marketParams, id, onBehalf), ErrorsLib.INSUFFICIENT_COLLATERAL);
                                      require(market[id].totalBorrowAssets <= market[id].totalSupplyAssets, ErrorsLib.INSUFFICIENT_LIQUIDITY);
                                      emit EventsLib.Borrow(id, msg.sender, onBehalf, receiver, assets, shares);
                                      IERC20(marketParams.loanToken).safeTransfer(receiver, assets);
                                      return (assets, shares);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function repay(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes calldata data
                                  ) external returns (uint256, uint256) {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(UtilsLib.exactlyOneZero(assets, shares), ErrorsLib.INCONSISTENT_INPUT);
                                      require(onBehalf != address(0), ErrorsLib.ZERO_ADDRESS);
                                      _accrueInterest(marketParams, id);
                                      if (assets > 0) shares = assets.toSharesDown(market[id].totalBorrowAssets, market[id].totalBorrowShares);
                                      else assets = shares.toAssetsUp(market[id].totalBorrowAssets, market[id].totalBorrowShares);
                                      position[id][onBehalf].borrowShares -= shares.toUint128();
                                      market[id].totalBorrowShares -= shares.toUint128();
                                      market[id].totalBorrowAssets = UtilsLib.zeroFloorSub(market[id].totalBorrowAssets, assets).toUint128();
                                      // `assets` may be greater than `totalBorrowAssets` by 1.
                                      emit EventsLib.Repay(id, msg.sender, onBehalf, assets, shares);
                                      if (data.length > 0) IMorphoRepayCallback(msg.sender).onMorphoRepay(assets, data);
                                      IERC20(marketParams.loanToken).safeTransferFrom(msg.sender, address(this), assets);
                                      return (assets, shares);
                                  }
                                  /* COLLATERAL MANAGEMENT */
                                  /// @inheritdoc IMorphoBase
                                  function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes calldata data)
                                      external
                                  {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(assets != 0, ErrorsLib.ZERO_ASSETS);
                                      require(onBehalf != address(0), ErrorsLib.ZERO_ADDRESS);
                                      // Don't accrue interest because it's not required and it saves gas.
                                      position[id][onBehalf].collateral += assets.toUint128();
                                      emit EventsLib.SupplyCollateral(id, msg.sender, onBehalf, assets);
                                      if (data.length > 0) IMorphoSupplyCollateralCallback(msg.sender).onMorphoSupplyCollateral(assets, data);
                                      IERC20(marketParams.collateralToken).safeTransferFrom(msg.sender, address(this), assets);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
                                      external
                                  {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(assets != 0, ErrorsLib.ZERO_ASSETS);
                                      require(receiver != address(0), ErrorsLib.ZERO_ADDRESS);
                                      // No need to verify that onBehalf != address(0) thanks to the following authorization check.
                                      require(_isSenderAuthorized(onBehalf), ErrorsLib.UNAUTHORIZED);
                                      _accrueInterest(marketParams, id);
                                      position[id][onBehalf].collateral -= assets.toUint128();
                                      require(_isHealthy(marketParams, id, onBehalf), ErrorsLib.INSUFFICIENT_COLLATERAL);
                                      emit EventsLib.WithdrawCollateral(id, msg.sender, onBehalf, receiver, assets);
                                      IERC20(marketParams.collateralToken).safeTransfer(receiver, assets);
                                  }
                                  /* LIQUIDATION */
                                  /// @inheritdoc IMorphoBase
                                  function liquidate(
                                      MarketParams memory marketParams,
                                      address borrower,
                                      uint256 seizedAssets,
                                      uint256 repaidShares,
                                      bytes calldata data
                                  ) external returns (uint256, uint256) {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      require(UtilsLib.exactlyOneZero(seizedAssets, repaidShares), ErrorsLib.INCONSISTENT_INPUT);
                                      _accrueInterest(marketParams, id);
                                      {
                                          uint256 collateralPrice = IOracle(marketParams.oracle).price();
                                          require(!_isHealthy(marketParams, id, borrower, collateralPrice), ErrorsLib.HEALTHY_POSITION);
                                          // The liquidation incentive factor is min(maxLiquidationIncentiveFactor, 1/(1 - cursor*(1 - lltv))).
                                          uint256 liquidationIncentiveFactor = UtilsLib.min(
                                              MAX_LIQUIDATION_INCENTIVE_FACTOR,
                                              WAD.wDivDown(WAD - LIQUIDATION_CURSOR.wMulDown(WAD - marketParams.lltv))
                                          );
                                          if (seizedAssets > 0) {
                                              uint256 seizedAssetsQuoted = seizedAssets.mulDivUp(collateralPrice, ORACLE_PRICE_SCALE);
                                              repaidShares = seizedAssetsQuoted.wDivUp(liquidationIncentiveFactor).toSharesUp(
                                                  market[id].totalBorrowAssets, market[id].totalBorrowShares
                                              );
                                          } else {
                                              seizedAssets = repaidShares.toAssetsDown(market[id].totalBorrowAssets, market[id].totalBorrowShares)
                                                  .wMulDown(liquidationIncentiveFactor).mulDivDown(ORACLE_PRICE_SCALE, collateralPrice);
                                          }
                                      }
                                      uint256 repaidAssets = repaidShares.toAssetsUp(market[id].totalBorrowAssets, market[id].totalBorrowShares);
                                      position[id][borrower].borrowShares -= repaidShares.toUint128();
                                      market[id].totalBorrowShares -= repaidShares.toUint128();
                                      market[id].totalBorrowAssets = UtilsLib.zeroFloorSub(market[id].totalBorrowAssets, repaidAssets).toUint128();
                                      position[id][borrower].collateral -= seizedAssets.toUint128();
                                      uint256 badDebtShares;
                                      uint256 badDebtAssets;
                                      if (position[id][borrower].collateral == 0) {
                                          badDebtShares = position[id][borrower].borrowShares;
                                          badDebtAssets = UtilsLib.min(
                                              market[id].totalBorrowAssets,
                                              badDebtShares.toAssetsUp(market[id].totalBorrowAssets, market[id].totalBorrowShares)
                                          );
                                          market[id].totalBorrowAssets -= badDebtAssets.toUint128();
                                          market[id].totalSupplyAssets -= badDebtAssets.toUint128();
                                          market[id].totalBorrowShares -= badDebtShares.toUint128();
                                          position[id][borrower].borrowShares = 0;
                                      }
                                      // `repaidAssets` may be greater than `totalBorrowAssets` by 1.
                                      emit EventsLib.Liquidate(
                                          id, msg.sender, borrower, repaidAssets, repaidShares, seizedAssets, badDebtAssets, badDebtShares
                                      );
                                      IERC20(marketParams.collateralToken).safeTransfer(msg.sender, seizedAssets);
                                      if (data.length > 0) IMorphoLiquidateCallback(msg.sender).onMorphoLiquidate(repaidAssets, data);
                                      IERC20(marketParams.loanToken).safeTransferFrom(msg.sender, address(this), repaidAssets);
                                      return (seizedAssets, repaidAssets);
                                  }
                                  /* FLASH LOANS */
                                  /// @inheritdoc IMorphoBase
                                  function flashLoan(address token, uint256 assets, bytes calldata data) external {
                                      require(assets != 0, ErrorsLib.ZERO_ASSETS);
                                      emit EventsLib.FlashLoan(msg.sender, token, assets);
                                      IERC20(token).safeTransfer(msg.sender, assets);
                                      IMorphoFlashLoanCallback(msg.sender).onMorphoFlashLoan(assets, data);
                                      IERC20(token).safeTransferFrom(msg.sender, address(this), assets);
                                  }
                                  /* AUTHORIZATION */
                                  /// @inheritdoc IMorphoBase
                                  function setAuthorization(address authorized, bool newIsAuthorized) external {
                                      require(newIsAuthorized != isAuthorized[msg.sender][authorized], ErrorsLib.ALREADY_SET);
                                      isAuthorized[msg.sender][authorized] = newIsAuthorized;
                                      emit EventsLib.SetAuthorization(msg.sender, msg.sender, authorized, newIsAuthorized);
                                  }
                                  /// @inheritdoc IMorphoBase
                                  function setAuthorizationWithSig(Authorization memory authorization, Signature calldata signature) external {
                                      /// Do not check whether authorization is already set because the nonce increment is a desired side effect.
                                      require(block.timestamp <= authorization.deadline, ErrorsLib.SIGNATURE_EXPIRED);
                                      require(authorization.nonce == nonce[authorization.authorizer]++, ErrorsLib.INVALID_NONCE);
                                      bytes32 hashStruct = keccak256(abi.encode(AUTHORIZATION_TYPEHASH, authorization));
                                      bytes32 digest = keccak256(bytes.concat("\\x19\\x01", DOMAIN_SEPARATOR, hashStruct));
                                      address signatory = ecrecover(digest, signature.v, signature.r, signature.s);
                                      require(signatory != address(0) && authorization.authorizer == signatory, ErrorsLib.INVALID_SIGNATURE);
                                      emit EventsLib.IncrementNonce(msg.sender, authorization.authorizer, authorization.nonce);
                                      isAuthorized[authorization.authorizer][authorization.authorized] = authorization.isAuthorized;
                                      emit EventsLib.SetAuthorization(
                                          msg.sender, authorization.authorizer, authorization.authorized, authorization.isAuthorized
                                      );
                                  }
                                  /// @dev Returns whether the sender is authorized to manage `onBehalf`'s positions.
                                  function _isSenderAuthorized(address onBehalf) internal view returns (bool) {
                                      return msg.sender == onBehalf || isAuthorized[onBehalf][msg.sender];
                                  }
                                  /* INTEREST MANAGEMENT */
                                  /// @inheritdoc IMorphoBase
                                  function accrueInterest(MarketParams memory marketParams) external {
                                      Id id = marketParams.id();
                                      require(market[id].lastUpdate != 0, ErrorsLib.MARKET_NOT_CREATED);
                                      _accrueInterest(marketParams, id);
                                  }
                                  /// @dev Accrues interest for the given market `marketParams`.
                                  /// @dev Assumes that the inputs `marketParams` and `id` match.
                                  function _accrueInterest(MarketParams memory marketParams, Id id) internal {
                                      uint256 elapsed = block.timestamp - market[id].lastUpdate;
                                      if (elapsed == 0) return;
                                      if (marketParams.irm != address(0)) {
                                          uint256 borrowRate = IIrm(marketParams.irm).borrowRate(marketParams, market[id]);
                                          uint256 interest = market[id].totalBorrowAssets.wMulDown(borrowRate.wTaylorCompounded(elapsed));
                                          market[id].totalBorrowAssets += interest.toUint128();
                                          market[id].totalSupplyAssets += interest.toUint128();
                                          uint256 feeShares;
                                          if (market[id].fee != 0) {
                                              uint256 feeAmount = interest.wMulDown(market[id].fee);
                                              // The fee amount is subtracted from the total supply in this calculation to compensate for the fact
                                              // that total supply is already increased by the full interest (including the fee amount).
                                              feeShares =
                                                  feeAmount.toSharesDown(market[id].totalSupplyAssets - feeAmount, market[id].totalSupplyShares);
                                              position[id][feeRecipient].supplyShares += feeShares;
                                              market[id].totalSupplyShares += feeShares.toUint128();
                                          }
                                          emit EventsLib.AccrueInterest(id, borrowRate, interest, feeShares);
                                      }
                                      // Safe "unchecked" cast.
                                      market[id].lastUpdate = uint128(block.timestamp);
                                  }
                                  /* HEALTH CHECK */
                                  /// @dev Returns whether the position of `borrower` in the given market `marketParams` is healthy.
                                  /// @dev Assumes that the inputs `marketParams` and `id` match.
                                  function _isHealthy(MarketParams memory marketParams, Id id, address borrower) internal view returns (bool) {
                                      if (position[id][borrower].borrowShares == 0) return true;
                                      uint256 collateralPrice = IOracle(marketParams.oracle).price();
                                      return _isHealthy(marketParams, id, borrower, collateralPrice);
                                  }
                                  /// @dev Returns whether the position of `borrower` in the given market `marketParams` with the given
                                  /// `collateralPrice` is healthy.
                                  /// @dev Assumes that the inputs `marketParams` and `id` match.
                                  /// @dev Rounds in favor of the protocol, so one might not be able to borrow exactly `maxBorrow` but one unit less.
                                  function _isHealthy(MarketParams memory marketParams, Id id, address borrower, uint256 collateralPrice)
                                      internal
                                      view
                                      returns (bool)
                                  {
                                      uint256 borrowed = uint256(position[id][borrower].borrowShares).toAssetsUp(
                                          market[id].totalBorrowAssets, market[id].totalBorrowShares
                                      );
                                      uint256 maxBorrow = uint256(position[id][borrower].collateral).mulDivDown(collateralPrice, ORACLE_PRICE_SCALE)
                                          .wMulDown(marketParams.lltv);
                                      return maxBorrow >= borrowed;
                                  }
                                  /* STORAGE VIEW */
                                  /// @inheritdoc IMorphoBase
                                  function extSloads(bytes32[] calldata slots) external view returns (bytes32[] memory res) {
                                      uint256 nSlots = slots.length;
                                      res = new bytes32[](nSlots);
                                      for (uint256 i; i < nSlots;) {
                                          bytes32 slot = slots[i++];
                                          assembly ("memory-safe") {
                                              mstore(add(res, mul(i, 32)), sload(slot))
                                          }
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              type Id is bytes32;
                              struct MarketParams {
                                  address loanToken;
                                  address collateralToken;
                                  address oracle;
                                  address irm;
                                  uint256 lltv;
                              }
                              /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
                              /// accrual.
                              struct Position {
                                  uint256 supplyShares;
                                  uint128 borrowShares;
                                  uint128 collateral;
                              }
                              /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                              /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                              /// @dev Warning: `totalSupplyShares` does not contain the additional shares accrued by `feeRecipient` since the last
                              /// interest accrual.
                              struct Market {
                                  uint128 totalSupplyAssets;
                                  uint128 totalSupplyShares;
                                  uint128 totalBorrowAssets;
                                  uint128 totalBorrowShares;
                                  uint128 lastUpdate;
                                  uint128 fee;
                              }
                              struct Authorization {
                                  address authorizer;
                                  address authorized;
                                  bool isAuthorized;
                                  uint256 nonce;
                                  uint256 deadline;
                              }
                              struct Signature {
                                  uint8 v;
                                  bytes32 r;
                                  bytes32 s;
                              }
                              /// @dev This interface is used for factorizing IMorphoStaticTyping and IMorpho.
                              /// @dev Consider using the IMorpho interface instead of this one.
                              interface IMorphoBase {
                                  /// @notice The EIP-712 domain separator.
                                  /// @dev Warning: Every EIP-712 signed message based on this domain separator can be reused on another chain sharing
                                  /// the same chain id because the domain separator would be the same.
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                                  /// @notice The owner of the contract.
                                  /// @dev It has the power to change the owner.
                                  /// @dev It has the power to set fees on markets and set the fee recipient.
                                  /// @dev It has the power to enable but not disable IRMs and LLTVs.
                                  function owner() external view returns (address);
                                  /// @notice The fee recipient of all markets.
                                  /// @dev The recipient receives the fees of a given market through a supply position on that market.
                                  function feeRecipient() external view returns (address);
                                  /// @notice Whether the `irm` is enabled.
                                  function isIrmEnabled(address irm) external view returns (bool);
                                  /// @notice Whether the `lltv` is enabled.
                                  function isLltvEnabled(uint256 lltv) external view returns (bool);
                                  /// @notice Whether `authorized` is authorized to modify `authorizer`'s position on all markets.
                                  /// @dev Anyone is authorized to modify their own positions, regardless of this variable.
                                  function isAuthorized(address authorizer, address authorized) external view returns (bool);
                                  /// @notice The `authorizer`'s current nonce. Used to prevent replay attacks with EIP-712 signatures.
                                  function nonce(address authorizer) external view returns (uint256);
                                  /// @notice Sets `newOwner` as `owner` of the contract.
                                  /// @dev Warning: No two-step transfer ownership.
                                  /// @dev Warning: The owner can be set to the zero address.
                                  function setOwner(address newOwner) external;
                                  /// @notice Enables `irm` as a possible IRM for market creation.
                                  /// @dev Warning: It is not possible to disable an IRM.
                                  function enableIrm(address irm) external;
                                  /// @notice Enables `lltv` as a possible LLTV for market creation.
                                  /// @dev Warning: It is not possible to disable a LLTV.
                                  function enableLltv(uint256 lltv) external;
                                  /// @notice Sets the `newFee` for the given market `marketParams`.
                                  /// @param newFee The new fee, scaled by WAD.
                                  /// @dev Warning: The recipient can be the zero address.
                                  function setFee(MarketParams memory marketParams, uint256 newFee) external;
                                  /// @notice Sets `newFeeRecipient` as `feeRecipient` of the fee.
                                  /// @dev Warning: If the fee recipient is set to the zero address, fees will accrue there and will be lost.
                                  /// @dev Modifying the fee recipient will allow the new recipient to claim any pending fees not yet accrued. To
                                  /// ensure that the current recipient receives all due fees, accrue interest manually prior to making any changes.
                                  function setFeeRecipient(address newFeeRecipient) external;
                                  /// @notice Creates the market `marketParams`.
                                  /// @dev Here is the list of assumptions on the market's dependencies (tokens, IRM and oracle) that guarantees
                                  /// Morpho behaves as expected:
                                  /// - The token should be ERC-20 compliant, except that it can omit return values on `transfer` and `transferFrom`.
                                  /// - The token balance of Morpho should only decrease on `transfer` and `transferFrom`. In particular, tokens with
                                  /// burn functions are not supported.
                                  /// - The token should not re-enter Morpho on `transfer` nor `transferFrom`.
                                  /// - The token balance of the sender (resp. receiver) should decrease (resp. increase) by exactly the given amount
                                  /// on `transfer` and `transferFrom`. In particular, tokens with fees on transfer are not supported.
                                  /// - The IRM should not re-enter Morpho.
                                  /// - The oracle should return a price with the correct scaling.
                                  /// @dev Here is a list of properties on the market's dependencies that could break Morpho's liveness properties
                                  /// (funds could get stuck):
                                  /// - The token can revert on `transfer` and `transferFrom` for a reason other than an approval or balance issue.
                                  /// - A very high amount of assets (~1e35) supplied or borrowed can make the computation of `toSharesUp` and
                                  /// `toSharesDown` overflow.
                                  /// - The IRM can revert on `borrowRate`.
                                  /// - A very high borrow rate returned by the IRM can make the computation of `interest` in `_accrueInterest`
                                  /// overflow.
                                  /// - The oracle can revert on `price`. Note that this can be used to prevent `borrow`, `withdrawCollateral` and
                                  /// `liquidate` from being used under certain market conditions.
                                  /// - A very high price returned by the oracle can make the computation of `maxBorrow` in `_isHealthy` overflow, or
                                  /// the computation of `assetsRepaid` in `liquidate` overflow.
                                  /// @dev The borrow share price of a market with less than 1e4 assets borrowed can be decreased by manipulations, to
                                  /// the point where `totalBorrowShares` is very large and borrowing overflows.
                                  function createMarket(MarketParams memory marketParams) external;
                                  /// @notice Supplies `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoSupply` function with the given `data`.
                                  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
                                  /// caller is guaranteed to have `assets` tokens pulled from their balance, but the possibility to mint a specific
                                  /// amount of shares is given for full compatibility and precision.
                                  /// @dev Supplying a large amount can revert for overflow.
                                  /// @dev Supplying an amount of shares may lead to supply more or fewer assets than expected due to slippage.
                                  /// Consider using the `assets` parameter to avoid this.
                                  /// @param marketParams The market to supply assets to.
                                  /// @param assets The amount of assets to supply.
                                  /// @param shares The amount of shares to mint.
                                  /// @param onBehalf The address that will own the increased supply position.
                                  /// @param data Arbitrary data to pass to the `onMorphoSupply` callback. Pass empty data if not needed.
                                  /// @return assetsSupplied The amount of assets supplied.
                                  /// @return sharesSupplied The amount of shares minted.
                                  function supply(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes memory data
                                  ) external returns (uint256 assetsSupplied, uint256 sharesSupplied);
                                  /// @notice Withdraws `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev Either `assets` or `shares` should be zero. To withdraw max, pass the `shares`'s balance of `onBehalf`.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Withdrawing an amount corresponding to more shares than supplied will revert for underflow.
                                  /// @dev It is advised to use the `shares` input when withdrawing the full position to avoid reverts due to
                                  /// conversion roundings between shares and assets.
                                  /// @param marketParams The market to withdraw assets from.
                                  /// @param assets The amount of assets to withdraw.
                                  /// @param shares The amount of shares to burn.
                                  /// @param onBehalf The address of the owner of the supply position.
                                  /// @param receiver The address that will receive the withdrawn assets.
                                  /// @return assetsWithdrawn The amount of assets withdrawn.
                                  /// @return sharesWithdrawn The amount of shares burned.
                                  function withdraw(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256 assetsWithdrawn, uint256 sharesWithdrawn);
                                  /// @notice Borrows `assets` or `shares` on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev Either `assets` or `shares` should be zero. Most use cases should rely on `assets` as an input so the
                                  /// caller is guaranteed to borrow `assets` of tokens, but the possibility to mint a specific amount of shares is
                                  /// given for full compatibility and precision.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Borrowing a large amount can revert for overflow.
                                  /// @dev Borrowing an amount of shares may lead to borrow fewer assets than expected due to slippage.
                                  /// Consider using the `assets` parameter to avoid this.
                                  /// @param marketParams The market to borrow assets from.
                                  /// @param assets The amount of assets to borrow.
                                  /// @param shares The amount of shares to mint.
                                  /// @param onBehalf The address that will own the increased borrow position.
                                  /// @param receiver The address that will receive the borrowed assets.
                                  /// @return assetsBorrowed The amount of assets borrowed.
                                  /// @return sharesBorrowed The amount of shares minted.
                                  function borrow(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      address receiver
                                  ) external returns (uint256 assetsBorrowed, uint256 sharesBorrowed);
                                  /// @notice Repays `assets` or `shares` on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoReplay` function with the given `data`.
                                  /// @dev Either `assets` or `shares` should be zero. To repay max, pass the `shares`'s balance of `onBehalf`.
                                  /// @dev Repaying an amount corresponding to more shares than borrowed will revert for underflow.
                                  /// @dev It is advised to use the `shares` input when repaying the full position to avoid reverts due to conversion
                                  /// roundings between shares and assets.
                                  /// @dev An attacker can front-run a repay with a small repay making the transaction revert for underflow.
                                  /// @param marketParams The market to repay assets to.
                                  /// @param assets The amount of assets to repay.
                                  /// @param shares The amount of shares to burn.
                                  /// @param onBehalf The address of the owner of the debt position.
                                  /// @param data Arbitrary data to pass to the `onMorphoRepay` callback. Pass empty data if not needed.
                                  /// @return assetsRepaid The amount of assets repaid.
                                  /// @return sharesRepaid The amount of shares burned.
                                  function repay(
                                      MarketParams memory marketParams,
                                      uint256 assets,
                                      uint256 shares,
                                      address onBehalf,
                                      bytes memory data
                                  ) external returns (uint256 assetsRepaid, uint256 sharesRepaid);
                                  /// @notice Supplies `assets` of collateral on behalf of `onBehalf`, optionally calling back the caller's
                                  /// `onMorphoSupplyCollateral` function with the given `data`.
                                  /// @dev Interest are not accrued since it's not required and it saves gas.
                                  /// @dev Supplying a large amount can revert for overflow.
                                  /// @param marketParams The market to supply collateral to.
                                  /// @param assets The amount of collateral to supply.
                                  /// @param onBehalf The address that will own the increased collateral position.
                                  /// @param data Arbitrary data to pass to the `onMorphoSupplyCollateral` callback. Pass empty data if not needed.
                                  function supplyCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, bytes memory data)
                                      external;
                                  /// @notice Withdraws `assets` of collateral on behalf of `onBehalf` and sends the assets to `receiver`.
                                  /// @dev `msg.sender` must be authorized to manage `onBehalf`'s positions.
                                  /// @dev Withdrawing an amount corresponding to more collateral than supplied will revert for underflow.
                                  /// @param marketParams The market to withdraw collateral from.
                                  /// @param assets The amount of collateral to withdraw.
                                  /// @param onBehalf The address of the owner of the collateral position.
                                  /// @param receiver The address that will receive the collateral assets.
                                  function withdrawCollateral(MarketParams memory marketParams, uint256 assets, address onBehalf, address receiver)
                                      external;
                                  /// @notice Liquidates the given `repaidShares` of debt asset or seize the given `seizedAssets` of collateral on the
                                  /// given market `marketParams` of the given `borrower`'s position, optionally calling back the caller's
                                  /// `onMorphoLiquidate` function with the given `data`.
                                  /// @dev Either `seizedAssets` or `repaidShares` should be zero.
                                  /// @dev Seizing more than the collateral balance will underflow and revert without any error message.
                                  /// @dev Repaying more than the borrow balance will underflow and revert without any error message.
                                  /// @dev An attacker can front-run a liquidation with a small repay making the transaction revert for underflow.
                                  /// @param marketParams The market of the position.
                                  /// @param borrower The owner of the position.
                                  /// @param seizedAssets The amount of collateral to seize.
                                  /// @param repaidShares The amount of shares to repay.
                                  /// @param data Arbitrary data to pass to the `onMorphoLiquidate` callback. Pass empty data if not needed.
                                  /// @return The amount of assets seized.
                                  /// @return The amount of assets repaid.
                                  function liquidate(
                                      MarketParams memory marketParams,
                                      address borrower,
                                      uint256 seizedAssets,
                                      uint256 repaidShares,
                                      bytes memory data
                                  ) external returns (uint256, uint256);
                                  /// @notice Executes a flash loan.
                                  /// @dev Flash loans have access to the whole balance of the contract (the liquidity and deposited collateral of all
                                  /// markets combined, plus donations).
                                  /// @dev Warning: Not ERC-3156 compliant but compatibility is easily reached:
                                  /// - `flashFee` is zero.
                                  /// - `maxFlashLoan` is the token's balance of this contract.
                                  /// - The receiver of `assets` is the caller.
                                  /// @param token The token to flash loan.
                                  /// @param assets The amount of assets to flash loan.
                                  /// @param data Arbitrary data to pass to the `onMorphoFlashLoan` callback.
                                  function flashLoan(address token, uint256 assets, bytes calldata data) external;
                                  /// @notice Sets the authorization for `authorized` to manage `msg.sender`'s positions.
                                  /// @param authorized The authorized address.
                                  /// @param newIsAuthorized The new authorization status.
                                  function setAuthorization(address authorized, bool newIsAuthorized) external;
                                  /// @notice Sets the authorization for `authorization.authorized` to manage `authorization.authorizer`'s positions.
                                  /// @dev Warning: Reverts if the signature has already been submitted.
                                  /// @dev The signature is malleable, but it has no impact on the security here.
                                  /// @dev The nonce is passed as argument to be able to revert with a different error message.
                                  /// @param authorization The `Authorization` struct.
                                  /// @param signature The signature.
                                  function setAuthorizationWithSig(Authorization calldata authorization, Signature calldata signature) external;
                                  /// @notice Accrues interest for the given market `marketParams`.
                                  function accrueInterest(MarketParams memory marketParams) external;
                                  /// @notice Returns the data stored on the different `slots`.
                                  function extSloads(bytes32[] memory slots) external view returns (bytes32[] memory);
                              }
                              /// @dev This interface is inherited by Morpho so that function signatures are checked by the compiler.
                              /// @dev Consider using the IMorpho interface instead of this one.
                              interface IMorphoStaticTyping is IMorphoBase {
                                  /// @notice The state of the position of `user` on the market corresponding to `id`.
                                  /// @dev Warning: For `feeRecipient`, `supplyShares` does not contain the accrued shares since the last interest
                                  /// accrual.
                                  function position(Id id, address user)
                                      external
                                      view
                                      returns (uint256 supplyShares, uint128 borrowShares, uint128 collateral);
                                  /// @notice The state of the market corresponding to `id`.
                                  /// @dev Warning: `totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last interest
                                  /// accrual.
                                  function market(Id id)
                                      external
                                      view
                                      returns (
                                          uint128 totalSupplyAssets,
                                          uint128 totalSupplyShares,
                                          uint128 totalBorrowAssets,
                                          uint128 totalBorrowShares,
                                          uint128 lastUpdate,
                                          uint128 fee
                                      );
                                  /// @notice The market params corresponding to `id`.
                                  /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
                                  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
                                  function idToMarketParams(Id id)
                                      external
                                      view
                                      returns (address loanToken, address collateralToken, address oracle, address irm, uint256 lltv);
                              }
                              /// @title IMorpho
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @dev Use this interface for Morpho to have access to all the functions with the appropriate function signatures.
                              interface IMorpho is IMorphoBase {
                                  /// @notice The state of the position of `user` on the market corresponding to `id`.
                                  /// @dev Warning: For `feeRecipient`, `p.supplyShares` does not contain the accrued shares since the last interest
                                  /// accrual.
                                  function position(Id id, address user) external view returns (Position memory p);
                                  /// @notice The state of the market corresponding to `id`.
                                  /// @dev Warning: `m.totalSupplyAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `m.totalBorrowAssets` does not contain the accrued interest since the last interest accrual.
                                  /// @dev Warning: `m.totalSupplyShares` does not contain the accrued shares by `feeRecipient` since the last
                                  /// interest accrual.
                                  function market(Id id) external view returns (Market memory m);
                                  /// @notice The market params corresponding to `id`.
                                  /// @dev This mapping is not used in Morpho. It is there to enable reducing the cost associated to calldata on layer
                                  /// 2s by creating a wrapper contract with functions that take `id` as input instead of `marketParams`.
                                  function idToMarketParams(Id id) external view returns (MarketParams memory);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              /// @title IMorphoLiquidateCallback
                              /// @notice Interface that liquidators willing to use `liquidate`'s callback must implement.
                              interface IMorphoLiquidateCallback {
                                  /// @notice Callback called when a liquidation occurs.
                                  /// @dev The callback is called only if data is not empty.
                                  /// @param repaidAssets The amount of repaid assets.
                                  /// @param data Arbitrary data passed to the `liquidate` function.
                                  function onMorphoLiquidate(uint256 repaidAssets, bytes calldata data) external;
                              }
                              /// @title IMorphoRepayCallback
                              /// @notice Interface that users willing to use `repay`'s callback must implement.
                              interface IMorphoRepayCallback {
                                  /// @notice Callback called when a repayment occurs.
                                  /// @dev The callback is called only if data is not empty.
                                  /// @param assets The amount of repaid assets.
                                  /// @param data Arbitrary data passed to the `repay` function.
                                  function onMorphoRepay(uint256 assets, bytes calldata data) external;
                              }
                              /// @title IMorphoSupplyCallback
                              /// @notice Interface that users willing to use `supply`'s callback must implement.
                              interface IMorphoSupplyCallback {
                                  /// @notice Callback called when a supply occurs.
                                  /// @dev The callback is called only if data is not empty.
                                  /// @param assets The amount of supplied assets.
                                  /// @param data Arbitrary data passed to the `supply` function.
                                  function onMorphoSupply(uint256 assets, bytes calldata data) external;
                              }
                              /// @title IMorphoSupplyCollateralCallback
                              /// @notice Interface that users willing to use `supplyCollateral`'s callback must implement.
                              interface IMorphoSupplyCollateralCallback {
                                  /// @notice Callback called when a supply of collateral occurs.
                                  /// @dev The callback is called only if data is not empty.
                                  /// @param assets The amount of supplied collateral.
                                  /// @param data Arbitrary data passed to the `supplyCollateral` function.
                                  function onMorphoSupplyCollateral(uint256 assets, bytes calldata data) external;
                              }
                              /// @title IMorphoFlashLoanCallback
                              /// @notice Interface that users willing to use `flashLoan`'s callback must implement.
                              interface IMorphoFlashLoanCallback {
                                  /// @notice Callback called when a flash loan occurs.
                                  /// @dev The callback is called only if data is not empty.
                                  /// @param assets The amount of assets that was flash loaned.
                                  /// @param data Arbitrary data passed to the `flashLoan` function.
                                  function onMorphoFlashLoan(uint256 assets, bytes calldata data) external;
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              import {MarketParams, Market} from "./IMorpho.sol";
                              /// @title IIrm
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Interface that Interest Rate Models (IRMs) used by Morpho must implement.
                              interface IIrm {
                                  /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams`.
                                  /// @dev Assumes that `market` corresponds to `marketParams`.
                                  function borrowRate(MarketParams memory marketParams, Market memory market) external returns (uint256);
                                  /// @notice Returns the borrow rate per second (scaled by WAD) of the market `marketParams` without modifying any
                                  /// storage.
                                  /// @dev Assumes that `market` corresponds to `marketParams`.
                                  function borrowRateView(MarketParams memory marketParams, Market memory market) external view returns (uint256);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              /// @title IERC20
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @dev Empty because we only call library functions. It prevents calling transfer (transferFrom) instead of
                              /// safeTransfer (safeTransferFrom).
                              interface IERC20 {}
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity >=0.5.0;
                              /// @title IOracle
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Interface that oracles used by Morpho must implement.
                              /// @dev It is the user's responsibility to select markets with safe oracles.
                              interface IOracle {
                                  /// @notice Returns the price of 1 asset of collateral token quoted in 1 asset of loan token, scaled by 1e36.
                                  /// @dev It corresponds to the price of 10**(collateral token decimals) assets of collateral token quoted in
                                  /// 10**(loan token decimals) assets of loan token with `36 + loan token decimals - collateral token decimals`
                                  /// decimals of precision.
                                  function price() external view returns (uint256);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              /// @dev The maximum fee a market can have (25%).
                              uint256 constant MAX_FEE = 0.25e18;
                              /// @dev Oracle price scale.
                              uint256 constant ORACLE_PRICE_SCALE = 1e36;
                              /// @dev Liquidation cursor.
                              uint256 constant LIQUIDATION_CURSOR = 0.3e18;
                              /// @dev Max liquidation incentive factor.
                              uint256 constant MAX_LIQUIDATION_INCENTIVE_FACTOR = 1.15e18;
                              /// @dev The EIP-712 typeHash for EIP712Domain.
                              bytes32 constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
                              /// @dev The EIP-712 typeHash for Authorization.
                              bytes32 constant AUTHORIZATION_TYPEHASH =
                                  keccak256("Authorization(address authorizer,address authorized,bool isAuthorized,uint256 nonce,uint256 deadline)");
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {ErrorsLib} from "../libraries/ErrorsLib.sol";
                              /// @title UtilsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing helpers.
                              /// @dev Inspired by https://github.com/morpho-org/morpho-utils.
                              library UtilsLib {
                                  /// @dev Returns true if there is exactly one zero among `x` and `y`.
                                  function exactlyOneZero(uint256 x, uint256 y) internal pure returns (bool z) {
                                      assembly {
                                          z := xor(iszero(x), iszero(y))
                                      }
                                  }
                                  /// @dev Returns the min of `x` and `y`.
                                  function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                      assembly {
                                          z := xor(x, mul(xor(x, y), lt(y, x)))
                                      }
                                  }
                                  /// @dev Returns `x` safely cast to uint128.
                                  function toUint128(uint256 x) internal pure returns (uint128) {
                                      require(x <= type(uint128).max, ErrorsLib.MAX_UINT128_EXCEEDED);
                                      return uint128(x);
                                  }
                                  /// @dev Returns max(0, x - y).
                                  function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
                                      assembly {
                                          z := mul(gt(x, y), sub(x, y))
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id, MarketParams} from "../interfaces/IMorpho.sol";
                              /// @title EventsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing events.
                              library EventsLib {
                                  /// @notice Emitted when setting a new owner.
                                  /// @param newOwner The new owner of the contract.
                                  event SetOwner(address indexed newOwner);
                                  /// @notice Emitted when setting a new fee.
                                  /// @param id The market id.
                                  /// @param newFee The new fee.
                                  event SetFee(Id indexed id, uint256 newFee);
                                  /// @notice Emitted when setting a new fee recipient.
                                  /// @param newFeeRecipient The new fee recipient.
                                  event SetFeeRecipient(address indexed newFeeRecipient);
                                  /// @notice Emitted when enabling an IRM.
                                  /// @param irm The IRM that was enabled.
                                  event EnableIrm(address indexed irm);
                                  /// @notice Emitted when enabling an LLTV.
                                  /// @param lltv The LLTV that was enabled.
                                  event EnableLltv(uint256 lltv);
                                  /// @notice Emitted when creating a market.
                                  /// @param id The market id.
                                  /// @param marketParams The market that was created.
                                  event CreateMarket(Id indexed id, MarketParams marketParams);
                                  /// @notice Emitted on supply of assets.
                                  /// @dev Warning: `feeRecipient` receives some shares during interest accrual without any supply event emitted.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param onBehalf The owner of the modified position.
                                  /// @param assets The amount of assets supplied.
                                  /// @param shares The amount of shares minted.
                                  event Supply(Id indexed id, address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);
                                  /// @notice Emitted on withdrawal of assets.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param onBehalf The owner of the modified position.
                                  /// @param receiver The address that received the withdrawn assets.
                                  /// @param assets The amount of assets withdrawn.
                                  /// @param shares The amount of shares burned.
                                  event Withdraw(
                                      Id indexed id,
                                      address caller,
                                      address indexed onBehalf,
                                      address indexed receiver,
                                      uint256 assets,
                                      uint256 shares
                                  );
                                  /// @notice Emitted on borrow of assets.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param onBehalf The owner of the modified position.
                                  /// @param receiver The address that received the borrowed assets.
                                  /// @param assets The amount of assets borrowed.
                                  /// @param shares The amount of shares minted.
                                  event Borrow(
                                      Id indexed id,
                                      address caller,
                                      address indexed onBehalf,
                                      address indexed receiver,
                                      uint256 assets,
                                      uint256 shares
                                  );
                                  /// @notice Emitted on repayment of assets.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param onBehalf The owner of the modified position.
                                  /// @param assets The amount of assets repaid. May be 1 over the corresponding market's `totalBorrowAssets`.
                                  /// @param shares The amount of shares burned.
                                  event Repay(Id indexed id, address indexed caller, address indexed onBehalf, uint256 assets, uint256 shares);
                                  /// @notice Emitted on supply of collateral.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param onBehalf The owner of the modified position.
                                  /// @param assets The amount of collateral supplied.
                                  event SupplyCollateral(Id indexed id, address indexed caller, address indexed onBehalf, uint256 assets);
                                  /// @notice Emitted on withdrawal of collateral.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param onBehalf The owner of the modified position.
                                  /// @param receiver The address that received the withdrawn collateral.
                                  /// @param assets The amount of collateral withdrawn.
                                  event WithdrawCollateral(
                                      Id indexed id, address caller, address indexed onBehalf, address indexed receiver, uint256 assets
                                  );
                                  /// @notice Emitted on liquidation of a position.
                                  /// @param id The market id.
                                  /// @param caller The caller.
                                  /// @param borrower The borrower of the position.
                                  /// @param repaidAssets The amount of assets repaid. May be 1 over the corresponding market's `totalBorrowAssets`.
                                  /// @param repaidShares The amount of shares burned.
                                  /// @param seizedAssets The amount of collateral seized.
                                  /// @param badDebtAssets The amount of assets of bad debt realized.
                                  /// @param badDebtShares The amount of borrow shares of bad debt realized.
                                  event Liquidate(
                                      Id indexed id,
                                      address indexed caller,
                                      address indexed borrower,
                                      uint256 repaidAssets,
                                      uint256 repaidShares,
                                      uint256 seizedAssets,
                                      uint256 badDebtAssets,
                                      uint256 badDebtShares
                                  );
                                  /// @notice Emitted on flash loan.
                                  /// @param caller The caller.
                                  /// @param token The token that was flash loaned.
                                  /// @param assets The amount that was flash loaned.
                                  event FlashLoan(address indexed caller, address indexed token, uint256 assets);
                                  /// @notice Emitted when setting an authorization.
                                  /// @param caller The caller.
                                  /// @param authorizer The authorizer address.
                                  /// @param authorized The authorized address.
                                  /// @param newIsAuthorized The new authorization status.
                                  event SetAuthorization(
                                      address indexed caller, address indexed authorizer, address indexed authorized, bool newIsAuthorized
                                  );
                                  /// @notice Emitted when setting an authorization with a signature.
                                  /// @param caller The caller.
                                  /// @param authorizer The authorizer address.
                                  /// @param usedNonce The nonce that was used.
                                  event IncrementNonce(address indexed caller, address indexed authorizer, uint256 usedNonce);
                                  /// @notice Emitted when accruing interest.
                                  /// @param id The market id.
                                  /// @param prevBorrowRate The previous borrow rate.
                                  /// @param interest The amount of interest accrued.
                                  /// @param feeShares The amount of shares minted as fee.
                                  event AccrueInterest(Id indexed id, uint256 prevBorrowRate, uint256 interest, uint256 feeShares);
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              /// @title ErrorsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library exposing error messages.
                              library ErrorsLib {
                                  /// @notice Thrown when the caller is not the owner.
                                  string internal constant NOT_OWNER = "not owner";
                                  /// @notice Thrown when the LLTV to enable exceeds the maximum LLTV.
                                  string internal constant MAX_LLTV_EXCEEDED = "max LLTV exceeded";
                                  /// @notice Thrown when the fee to set exceeds the maximum fee.
                                  string internal constant MAX_FEE_EXCEEDED = "max fee exceeded";
                                  /// @notice Thrown when the value is already set.
                                  string internal constant ALREADY_SET = "already set";
                                  /// @notice Thrown when the IRM is not enabled at market creation.
                                  string internal constant IRM_NOT_ENABLED = "IRM not enabled";
                                  /// @notice Thrown when the LLTV is not enabled at market creation.
                                  string internal constant LLTV_NOT_ENABLED = "LLTV not enabled";
                                  /// @notice Thrown when the market is already created.
                                  string internal constant MARKET_ALREADY_CREATED = "market already created";
                                  /// @notice Thrown when a token to transfer doesn't have code.
                                  string internal constant NO_CODE = "no code";
                                  /// @notice Thrown when the market is not created.
                                  string internal constant MARKET_NOT_CREATED = "market not created";
                                  /// @notice Thrown when not exactly one of the input amount is zero.
                                  string internal constant INCONSISTENT_INPUT = "inconsistent input";
                                  /// @notice Thrown when zero assets is passed as input.
                                  string internal constant ZERO_ASSETS = "zero assets";
                                  /// @notice Thrown when a zero address is passed as input.
                                  string internal constant ZERO_ADDRESS = "zero address";
                                  /// @notice Thrown when the caller is not authorized to conduct an action.
                                  string internal constant UNAUTHORIZED = "unauthorized";
                                  /// @notice Thrown when the collateral is insufficient to `borrow` or `withdrawCollateral`.
                                  string internal constant INSUFFICIENT_COLLATERAL = "insufficient collateral";
                                  /// @notice Thrown when the liquidity is insufficient to `withdraw` or `borrow`.
                                  string internal constant INSUFFICIENT_LIQUIDITY = "insufficient liquidity";
                                  /// @notice Thrown when the position to liquidate is healthy.
                                  string internal constant HEALTHY_POSITION = "position is healthy";
                                  /// @notice Thrown when the authorization signature is invalid.
                                  string internal constant INVALID_SIGNATURE = "invalid signature";
                                  /// @notice Thrown when the authorization signature is expired.
                                  string internal constant SIGNATURE_EXPIRED = "signature expired";
                                  /// @notice Thrown when the nonce is invalid.
                                  string internal constant INVALID_NONCE = "invalid nonce";
                                  /// @notice Thrown when a token transfer reverted.
                                  string internal constant TRANSFER_REVERTED = "transfer reverted";
                                  /// @notice Thrown when a token transfer returned false.
                                  string internal constant TRANSFER_RETURNED_FALSE = "transfer returned false";
                                  /// @notice Thrown when a token transferFrom reverted.
                                  string internal constant TRANSFER_FROM_REVERTED = "transferFrom reverted";
                                  /// @notice Thrown when a token transferFrom returned false
                                  string internal constant TRANSFER_FROM_RETURNED_FALSE = "transferFrom returned false";
                                  /// @notice Thrown when the maximum uint128 is exceeded.
                                  string internal constant MAX_UINT128_EXCEEDED = "max uint128 exceeded";
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              uint256 constant WAD = 1e18;
                              /// @title MathLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to manage fixed-point arithmetic.
                              library MathLib {
                                  /// @dev Returns (`x` * `y`) / `WAD` rounded down.
                                  function wMulDown(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivDown(x, y, WAD);
                                  }
                                  /// @dev Returns (`x` * `WAD`) / `y` rounded down.
                                  function wDivDown(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivDown(x, WAD, y);
                                  }
                                  /// @dev Returns (`x` * `WAD`) / `y` rounded up.
                                  function wDivUp(uint256 x, uint256 y) internal pure returns (uint256) {
                                      return mulDivUp(x, WAD, y);
                                  }
                                  /// @dev Returns (`x` * `y`) / `d` rounded down.
                                  function mulDivDown(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
                                      return (x * y) / d;
                                  }
                                  /// @dev Returns (`x` * `y`) / `d` rounded up.
                                  function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256) {
                                      return (x * y + (d - 1)) / d;
                                  }
                                  /// @dev Returns the sum of the first three non-zero terms of a Taylor expansion of e^(nx) - 1, to approximate a
                                  /// continuous compound interest rate.
                                  function wTaylorCompounded(uint256 x, uint256 n) internal pure returns (uint256) {
                                      uint256 firstTerm = x * n;
                                      uint256 secondTerm = mulDivDown(firstTerm, firstTerm, 2 * WAD);
                                      uint256 thirdTerm = mulDivDown(secondTerm, firstTerm, 3 * WAD);
                                      return firstTerm + secondTerm + thirdTerm;
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {MathLib} from "./MathLib.sol";
                              /// @title SharesMathLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Shares management library.
                              /// @dev This implementation mitigates share price manipulations, using OpenZeppelin's method of virtual shares:
                              /// https://docs.openzeppelin.com/contracts/4.x/erc4626#inflation-attack.
                              library SharesMathLib {
                                  using MathLib for uint256;
                                  /// @dev The number of virtual shares has been chosen low enough to prevent overflows, and high enough to ensure
                                  /// high precision computations.
                                  /// @dev Virtual shares can never be redeemed for the assets they are entitled to, but it is assumed the share price
                                  /// stays low enough not to inflate these assets to a significant value.
                                  /// @dev Warning: The assets to which virtual borrow shares are entitled behave like unrealizable bad debt.
                                  uint256 internal constant VIRTUAL_SHARES = 1e6;
                                  /// @dev A number of virtual assets of 1 enforces a conversion rate between shares and assets when a market is
                                  /// empty.
                                  uint256 internal constant VIRTUAL_ASSETS = 1;
                                  /// @dev Calculates the value of `assets` quoted in shares, rounding down.
                                  function toSharesDown(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return assets.mulDivDown(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
                                  }
                                  /// @dev Calculates the value of `shares` quoted in assets, rounding down.
                                  function toAssetsDown(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return shares.mulDivDown(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
                                  }
                                  /// @dev Calculates the value of `assets` quoted in shares, rounding up.
                                  function toSharesUp(uint256 assets, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return assets.mulDivUp(totalShares + VIRTUAL_SHARES, totalAssets + VIRTUAL_ASSETS);
                                  }
                                  /// @dev Calculates the value of `shares` quoted in assets, rounding up.
                                  function toAssetsUp(uint256 shares, uint256 totalAssets, uint256 totalShares) internal pure returns (uint256) {
                                      return shares.mulDivUp(totalAssets + VIRTUAL_ASSETS, totalShares + VIRTUAL_SHARES);
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {Id, MarketParams} from "../interfaces/IMorpho.sol";
                              /// @title MarketParamsLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to convert a market to its id.
                              library MarketParamsLib {
                                  /// @notice The length of the data used to compute the id of a market.
                                  /// @dev The length is 5 * 32 because `MarketParams` has 5 variables of 32 bytes each.
                                  uint256 internal constant MARKET_PARAMS_BYTES_LENGTH = 5 * 32;
                                  /// @notice Returns the id of the market `marketParams`.
                                  function id(MarketParams memory marketParams) internal pure returns (Id marketParamsId) {
                                      assembly ("memory-safe") {
                                          marketParamsId := keccak256(marketParams, MARKET_PARAMS_BYTES_LENGTH)
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: GPL-2.0-or-later
                              pragma solidity ^0.8.0;
                              import {IERC20} from "../interfaces/IERC20.sol";
                              import {ErrorsLib} from "../libraries/ErrorsLib.sol";
                              interface IERC20Internal {
                                  function transfer(address to, uint256 value) external returns (bool);
                                  function transferFrom(address from, address to, uint256 value) external returns (bool);
                              }
                              /// @title SafeTransferLib
                              /// @author Morpho Labs
                              /// @custom:contact security@morpho.org
                              /// @notice Library to manage transfers of tokens, even if calls to the transfer or transferFrom functions are not
                              /// returning a boolean.
                              library SafeTransferLib {
                                  function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                      require(address(token).code.length > 0, ErrorsLib.NO_CODE);
                                      (bool success, bytes memory returndata) =
                                          address(token).call(abi.encodeCall(IERC20Internal.transfer, (to, value)));
                                      require(success, ErrorsLib.TRANSFER_REVERTED);
                                      require(returndata.length == 0 || abi.decode(returndata, (bool)), ErrorsLib.TRANSFER_RETURNED_FALSE);
                                  }
                                  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                      require(address(token).code.length > 0, ErrorsLib.NO_CODE);
                                      (bool success, bytes memory returndata) =
                                          address(token).call(abi.encodeCall(IERC20Internal.transferFrom, (from, to, value)));
                                      require(success, ErrorsLib.TRANSFER_FROM_REVERTED);
                                      require(returndata.length == 0 || abi.decode(returndata, (bool)), ErrorsLib.TRANSFER_FROM_RETURNED_FALSE);
                                  }
                              }
                              

                              File 5 of 11: FiatTokenProxy
                              pragma solidity ^0.4.24;
                              
                              // File: zos-lib/contracts/upgradeability/Proxy.sol
                              
                              /**
                               * @title Proxy
                               * @dev Implements delegation of calls to other contracts, with proper
                               * forwarding of return values and bubbling of failures.
                               * It defines a fallback function that delegates all calls to the address
                               * returned by the abstract _implementation() internal function.
                               */
                              contract Proxy {
                                /**
                                 * @dev Fallback function.
                                 * Implemented entirely in `_fallback`.
                                 */
                                function () payable external {
                                  _fallback();
                                }
                              
                                /**
                                 * @return The Address of the implementation.
                                 */
                                function _implementation() internal view returns (address);
                              
                                /**
                                 * @dev Delegates execution to an implementation contract.
                                 * This is a low level function that doesn't return to its internal call site.
                                 * It will return to the external caller whatever the implementation returns.
                                 * @param implementation Address to delegate.
                                 */
                                function _delegate(address implementation) internal {
                                  assembly {
                                    // Copy msg.data. We take full control of memory in this inline assembly
                                    // block because it will not return to Solidity code. We overwrite the
                                    // Solidity scratch pad at memory position 0.
                                    calldatacopy(0, 0, calldatasize)
                              
                                    // Call the implementation.
                                    // out and outsize are 0 because we don't know the size yet.
                                    let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
                              
                                    // Copy the returned data.
                                    returndatacopy(0, 0, returndatasize)
                              
                                    switch result
                                    // delegatecall returns 0 on error.
                                    case 0 { revert(0, returndatasize) }
                                    default { return(0, returndatasize) }
                                  }
                                }
                              
                                /**
                                 * @dev Function that is run as the first thing in the fallback function.
                                 * Can be redefined in derived contracts to add functionality.
                                 * Redefinitions must call super._willFallback().
                                 */
                                function _willFallback() internal {
                                }
                              
                                /**
                                 * @dev fallback implementation.
                                 * Extracted to enable manual triggering.
                                 */
                                function _fallback() internal {
                                  _willFallback();
                                  _delegate(_implementation());
                                }
                              }
                              
                              // File: openzeppelin-solidity/contracts/AddressUtils.sol
                              
                              /**
                               * Utility library of inline functions on addresses
                               */
                              library AddressUtils {
                              
                                /**
                                 * Returns whether the target address is a contract
                                 * @dev This function will return false if invoked during the constructor of a contract,
                                 * as the code is not actually created until after the constructor finishes.
                                 * @param addr address to check
                                 * @return whether the target address is a contract
                                 */
                                function isContract(address addr) internal view returns (bool) {
                                  uint256 size;
                                  // XXX Currently there is no better way to check if there is a contract in an address
                                  // than to check the size of the code at that address.
                                  // See https://ethereum.stackexchange.com/a/14016/36603
                                  // for more details about how this works.
                                  // TODO Check this again before the Serenity release, because all addresses will be
                                  // contracts then.
                                  // solium-disable-next-line security/no-inline-assembly
                                  assembly { size := extcodesize(addr) }
                                  return size > 0;
                                }
                              
                              }
                              
                              // File: zos-lib/contracts/upgradeability/UpgradeabilityProxy.sol
                              
                              /**
                               * @title UpgradeabilityProxy
                               * @dev This contract implements a proxy that allows to change the
                               * implementation address to which it will delegate.
                               * Such a change is called an implementation upgrade.
                               */
                              contract UpgradeabilityProxy is Proxy {
                                /**
                                 * @dev Emitted when the implementation is upgraded.
                                 * @param implementation Address of the new implementation.
                                 */
                                event Upgraded(address implementation);
                              
                                /**
                                 * @dev Storage slot with the address of the current implementation.
                                 * This is the keccak-256 hash of "org.zeppelinos.proxy.implementation", and is
                                 * validated in the constructor.
                                 */
                                bytes32 private constant IMPLEMENTATION_SLOT = 0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3;
                              
                                /**
                                 * @dev Contract constructor.
                                 * @param _implementation Address of the initial implementation.
                                 */
                                constructor(address _implementation) public {
                                  assert(IMPLEMENTATION_SLOT == keccak256("org.zeppelinos.proxy.implementation"));
                              
                                  _setImplementation(_implementation);
                                }
                              
                                /**
                                 * @dev Returns the current implementation.
                                 * @return Address of the current implementation
                                 */
                                function _implementation() internal view returns (address impl) {
                                  bytes32 slot = IMPLEMENTATION_SLOT;
                                  assembly {
                                    impl := sload(slot)
                                  }
                                }
                              
                                /**
                                 * @dev Upgrades the proxy to a new implementation.
                                 * @param newImplementation Address of the new implementation.
                                 */
                                function _upgradeTo(address newImplementation) internal {
                                  _setImplementation(newImplementation);
                                  emit Upgraded(newImplementation);
                                }
                              
                                /**
                                 * @dev Sets the implementation address of the proxy.
                                 * @param newImplementation Address of the new implementation.
                                 */
                                function _setImplementation(address newImplementation) private {
                                  require(AddressUtils.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
                              
                                  bytes32 slot = IMPLEMENTATION_SLOT;
                              
                                  assembly {
                                    sstore(slot, newImplementation)
                                  }
                                }
                              }
                              
                              // File: zos-lib/contracts/upgradeability/AdminUpgradeabilityProxy.sol
                              
                              /**
                               * @title AdminUpgradeabilityProxy
                               * @dev This contract combines an upgradeability proxy with an authorization
                               * mechanism for administrative tasks.
                               * All external functions in this contract must be guarded by the
                               * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
                               * feature proposal that would enable this to be done automatically.
                               */
                              contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
                                /**
                                 * @dev Emitted when the administration has been transferred.
                                 * @param previousAdmin Address of the previous admin.
                                 * @param newAdmin Address of the new admin.
                                 */
                                event AdminChanged(address previousAdmin, address newAdmin);
                              
                                /**
                                 * @dev Storage slot with the admin of the contract.
                                 * This is the keccak-256 hash of "org.zeppelinos.proxy.admin", and is
                                 * validated in the constructor.
                                 */
                                bytes32 private constant ADMIN_SLOT = 0x10d6a54a4754c8869d6886b5f5d7fbfa5b4522237ea5c60d11bc4e7a1ff9390b;
                              
                                /**
                                 * @dev Modifier to check whether the `msg.sender` is the admin.
                                 * If it is, it will run the function. Otherwise, it will delegate the call
                                 * to the implementation.
                                 */
                                modifier ifAdmin() {
                                  if (msg.sender == _admin()) {
                                    _;
                                  } else {
                                    _fallback();
                                  }
                                }
                              
                                /**
                                 * Contract constructor.
                                 * It sets the `msg.sender` as the proxy administrator.
                                 * @param _implementation address of the initial implementation.
                                 */
                                constructor(address _implementation) UpgradeabilityProxy(_implementation) public {
                                  assert(ADMIN_SLOT == keccak256("org.zeppelinos.proxy.admin"));
                              
                                  _setAdmin(msg.sender);
                                }
                              
                                /**
                                 * @return The address of the proxy admin.
                                 */
                                function admin() external view ifAdmin returns (address) {
                                  return _admin();
                                }
                              
                                /**
                                 * @return The address of the implementation.
                                 */
                                function implementation() external view ifAdmin returns (address) {
                                  return _implementation();
                                }
                              
                                /**
                                 * @dev Changes the admin of the proxy.
                                 * Only the current admin can call this function.
                                 * @param newAdmin Address to transfer proxy administration to.
                                 */
                                function changeAdmin(address newAdmin) external ifAdmin {
                                  require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
                                  emit AdminChanged(_admin(), newAdmin);
                                  _setAdmin(newAdmin);
                                }
                              
                                /**
                                 * @dev Upgrade the backing implementation of the proxy.
                                 * Only the admin can call this function.
                                 * @param newImplementation Address of the new implementation.
                                 */
                                function upgradeTo(address newImplementation) external ifAdmin {
                                  _upgradeTo(newImplementation);
                                }
                              
                                /**
                                 * @dev Upgrade the backing implementation of the proxy and call a function
                                 * on the new implementation.
                                 * This is useful to initialize the proxied contract.
                                 * @param newImplementation Address of the new implementation.
                                 * @param data Data to send as msg.data in the low level call.
                                 * It should include the signature and the parameters of the function to be
                                 * called, as described in
                                 * https://solidity.readthedocs.io/en/develop/abi-spec.html#function-selector-and-argument-encoding.
                                 */
                                function upgradeToAndCall(address newImplementation, bytes data) payable external ifAdmin {
                                  _upgradeTo(newImplementation);
                                  require(address(this).call.value(msg.value)(data));
                                }
                              
                                /**
                                 * @return The admin slot.
                                 */
                                function _admin() internal view returns (address adm) {
                                  bytes32 slot = ADMIN_SLOT;
                                  assembly {
                                    adm := sload(slot)
                                  }
                                }
                              
                                /**
                                 * @dev Sets the address of the proxy admin.
                                 * @param newAdmin Address of the new proxy admin.
                                 */
                                function _setAdmin(address newAdmin) internal {
                                  bytes32 slot = ADMIN_SLOT;
                              
                                  assembly {
                                    sstore(slot, newAdmin)
                                  }
                                }
                              
                                /**
                                 * @dev Only fall back when the sender is not the admin.
                                 */
                                function _willFallback() internal {
                                  require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
                                  super._willFallback();
                                }
                              }
                              
                              // File: contracts/FiatTokenProxy.sol
                              
                              /**
                              * Copyright CENTRE SECZ 2018
                              *
                              * Permission is hereby granted, free of charge, to any person obtaining a copy 
                              * of this software and associated documentation files (the "Software"), to deal 
                              * in the Software without restriction, including without limitation the rights 
                              * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
                              * copies of the Software, and to permit persons to whom the Software is furnished to 
                              * do so, subject to the following conditions:
                              *
                              * The above copyright notice and this permission notice shall be included in all 
                              * copies or substantial portions of the Software.
                              *
                              * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
                              * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
                              * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
                              * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
                              * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
                              * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
                              */
                              
                              pragma solidity ^0.4.24;
                              
                              
                              /**
                               * @title FiatTokenProxy
                               * @dev This contract proxies FiatToken calls and enables FiatToken upgrades
                              */ 
                              contract FiatTokenProxy is AdminUpgradeabilityProxy {
                                  constructor(address _implementation) public AdminUpgradeabilityProxy(_implementation) {
                                  }
                              }

                              File 6 of 11: Yearn V3 Vault
                              # @version 0.3.7
                              
                              """
                              @title Yearn V3 Vault
                              @license GNU AGPLv3
                              @author yearn.finance
                              @notice
                                  The Yearn VaultV3 is designed as a non-opinionated system to distribute funds of 
                                  depositors for a specific `asset` into different opportunities (aka Strategies)
                                  and manage accounting in a robust way.
                              
                                  Depositors receive shares (aka vaults tokens) proportional to their deposit amount. 
                                  Vault tokens are yield-bearing and can be redeemed at any time to get back deposit 
                                  plus any yield generated.
                              
                                  Addresses that are given different permissioned roles by the `role_manager` 
                                  are then able to allocate funds as they best see fit to different strategies 
                                  and adjust the strategies and allocations as needed, as well as reporting realized
                                  profits or losses.
                              
                                  Strategies are any ERC-4626 compliant contracts that use the same underlying `asset` 
                                  as the vault. The vault provides no assurances as to the safety of any strategy
                                  and it is the responsibility of those that hold the corresponding roles to choose
                                  and fund strategies that best fit their desired specifications.
                              
                                  Those holding vault tokens are able to redeem the tokens for the corresponding
                                  amount of underlying asset based on any reported profits or losses since their
                                  initial deposit.
                              
                                  The vault is built to be customized by the management to be able to fit their
                                  specific desired needs. Including the customization of strategies, accountants, 
                                  ownership etc.
                              """
                              
                              # INTERFACES #
                              
                              from vyper.interfaces import ERC20
                              from vyper.interfaces import ERC20Detailed
                              
                              interface IStrategy:
                                  def asset() -> address: view
                                  def balanceOf(owner: address) -> uint256: view
                                  def convertToAssets(shares: uint256) -> uint256: view
                                  def convertToShares(assets: uint256) -> uint256: view
                                  def previewWithdraw(assets: uint256) -> uint256: view
                                  def maxDeposit(receiver: address) -> uint256: view
                                  def deposit(assets: uint256, receiver: address) -> uint256: nonpayable
                                  def maxRedeem(owner: address) -> uint256: view
                                  def redeem(shares: uint256, receiver: address, owner: address) -> uint256: nonpayable
                                  
                              interface IAccountant:
                                  def report(strategy: address, gain: uint256, loss: uint256) -> (uint256, uint256): nonpayable
                              
                              interface IDepositLimitModule:
                                  def available_deposit_limit(receiver: address) -> uint256: view
                                  
                              interface IWithdrawLimitModule:
                                  def available_withdraw_limit(owner: address, max_loss: uint256, strategies: DynArray[address, MAX_QUEUE]) -> uint256: view
                              
                              interface IFactory:
                                  def protocol_fee_config() -> (uint16, address): view
                              
                              # EVENTS #
                              # ERC4626 EVENTS
                              event Deposit:
                                  sender: indexed(address)
                                  owner: indexed(address)
                                  assets: uint256
                                  shares: uint256
                              
                              event Withdraw:
                                  sender: indexed(address)
                                  receiver: indexed(address)
                                  owner: indexed(address)
                                  assets: uint256
                                  shares: uint256
                              
                              # ERC20 EVENTS
                              event Transfer:
                                  sender: indexed(address)
                                  receiver: indexed(address)
                                  value: uint256
                              
                              event Approval:
                                  owner: indexed(address)
                                  spender: indexed(address)
                                  value: uint256
                              
                              # STRATEGY EVENTS
                              event StrategyChanged:
                                  strategy: indexed(address)
                                  change_type: indexed(StrategyChangeType)
                                  
                              event StrategyReported:
                                  strategy: indexed(address)
                                  gain: uint256
                                  loss: uint256
                                  current_debt: uint256
                                  protocol_fees: uint256
                                  total_fees: uint256
                                  total_refunds: uint256
                              
                              # DEBT MANAGEMENT EVENTS
                              event DebtUpdated:
                                  strategy: indexed(address)
                                  current_debt: uint256
                                  new_debt: uint256
                              
                              # ROLE UPDATES
                              event RoleSet:
                                  account: indexed(address)
                                  role: indexed(Roles)
                              
                              # STORAGE MANAGEMENT EVENTS
                              event UpdateRoleManager:
                                  role_manager: indexed(address)
                              
                              event UpdateAccountant:
                                  accountant: indexed(address)
                              
                              event UpdateDepositLimitModule:
                                  deposit_limit_module: indexed(address)
                              
                              event UpdateWithdrawLimitModule:
                                  withdraw_limit_module: indexed(address)
                              
                              event UpdateDefaultQueue:
                                  new_default_queue: DynArray[address, MAX_QUEUE]
                              
                              event UpdateUseDefaultQueue:
                                  use_default_queue: bool
                              
                              event UpdatedMaxDebtForStrategy:
                                  sender: indexed(address)
                                  strategy: indexed(address)
                                  new_debt: uint256
                              
                              event UpdateDepositLimit:
                                  deposit_limit: uint256
                              
                              event UpdateMinimumTotalIdle:
                                  minimum_total_idle: uint256
                              
                              event UpdateProfitMaxUnlockTime:
                                  profit_max_unlock_time: uint256
                              
                              event DebtPurchased:
                                  strategy: indexed(address)
                                  amount: uint256
                              
                              event Shutdown:
                                  pass
                              
                              # STRUCTS #
                              struct StrategyParams:
                                  # Timestamp when the strategy was added.
                                  activation: uint256 
                                  # Timestamp of the strategies last report.
                                  last_report: uint256
                                  # The current assets the strategy holds.
                                  current_debt: uint256
                                  # The max assets the strategy can hold. 
                                  max_debt: uint256
                              
                              # CONSTANTS #
                              # The max length the withdrawal queue can be.
                              MAX_QUEUE: constant(uint256) = 10
                              # 100% in Basis Points.
                              MAX_BPS: constant(uint256) = 10_000
                              # Extended for profit locking calculations.
                              MAX_BPS_EXTENDED: constant(uint256) = 1_000_000_000_000
                              # The version of this vault.
                              API_VERSION: constant(String[28]) = "3.0.2"
                              
                              # ENUMS #
                              # Each permissioned function has its own Role.
                              # Roles can be combined in any combination or all kept separate.
                              # Follows python Enum patterns so the first Enum == 1 and doubles each time.
                              enum Roles:
                                  ADD_STRATEGY_MANAGER # Can add strategies to the vault.
                                  REVOKE_STRATEGY_MANAGER # Can remove strategies from the vault.
                                  FORCE_REVOKE_MANAGER # Can force remove a strategy causing a loss.
                                  ACCOUNTANT_MANAGER # Can set the accountant that assess fees.
                                  QUEUE_MANAGER # Can set the default withdrawal queue.
                                  REPORTING_MANAGER # Calls report for strategies.
                                  DEBT_MANAGER # Adds and removes debt from strategies.
                                  MAX_DEBT_MANAGER # Can set the max debt for a strategy.
                                  DEPOSIT_LIMIT_MANAGER # Sets deposit limit and module for the vault.
                                  WITHDRAW_LIMIT_MANAGER # Sets the withdraw limit module.
                                  MINIMUM_IDLE_MANAGER # Sets the minimum total idle the vault should keep.
                                  PROFIT_UNLOCK_MANAGER # Sets the profit_max_unlock_time.
                                  DEBT_PURCHASER # Can purchase bad debt from the vault.
                                  EMERGENCY_MANAGER # Can shutdown vault in an emergency.
                              
                              enum StrategyChangeType:
                                  ADDED
                                  REVOKED
                              
                              enum Rounding:
                                  ROUND_DOWN
                                  ROUND_UP
                              
                              # STORAGE #
                              # Underlying token used by the vault.
                              asset: public(address)
                              # Based off the `asset` decimals.
                              decimals: public(uint8)
                              # Deployer contract used to retrieve the protocol fee config.
                              factory: address
                              
                              # HashMap that records all the strategies that are allowed to receive assets from the vault.
                              strategies: public(HashMap[address, StrategyParams])
                              # The current default withdrawal queue.
                              default_queue: public(DynArray[address, MAX_QUEUE])
                              # Should the vault use the default_queue regardless whats passed in.
                              use_default_queue: public(bool)
                              
                              ### ACCOUNTING ###
                              # ERC20 - amount of shares per account
                              balance_of: HashMap[address, uint256]
                              # ERC20 - owner -> (spender -> amount)
                              allowance: public(HashMap[address, HashMap[address, uint256]])
                              # Total amount of shares that are currently minted including those locked.
                              total_supply: uint256
                              # Total amount of assets that has been deposited in strategies.
                              total_debt: uint256
                              # Current assets held in the vault contract. Replacing balanceOf(this) to avoid price_per_share manipulation.
                              total_idle: uint256
                              # Minimum amount of assets that should be kept in the vault contract to allow for fast, cheap redeems.
                              minimum_total_idle: public(uint256)
                              # Maximum amount of tokens that the vault can accept. If totalAssets > deposit_limit, deposits will revert.
                              deposit_limit: public(uint256)
                              
                              ### PERIPHERY ###
                              # Contract that charges fees and can give refunds.
                              accountant: public(address)
                              # Contract to control the deposit limit.
                              deposit_limit_module: public(address)
                              # Contract to control the withdraw limit.
                              withdraw_limit_module: public(address)
                              
                              ### ROLES ###
                              # HashMap mapping addresses to their roles
                              roles: public(HashMap[address, Roles])
                              # Address that can add and remove roles to addresses.
                              role_manager: public(address)
                              # Temporary variable to store the address of the next role_manager until the role is accepted.
                              future_role_manager: public(address)
                              
                              # ERC20 - name of the vaults token.
                              name: public(String[64])
                              # ERC20 - symbol of the vaults token.
                              symbol: public(String[32])
                              
                              # State of the vault - if set to true, only withdrawals will be available. It can't be reverted.
                              shutdown: bool
                              # The amount of time profits will unlock over.
                              profit_max_unlock_time: uint256
                              # The timestamp of when the current unlocking period ends.
                              full_profit_unlock_date: uint256
                              # The per second rate at which profit will unlock.
                              profit_unlocking_rate: uint256
                              # Last timestamp of the most recent profitable report.
                              last_profit_update: uint256
                              
                              # `nonces` track `permit` approvals with signature.
                              nonces: public(HashMap[address, uint256])
                              DOMAIN_TYPE_HASH: constant(bytes32) = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
                              PERMIT_TYPE_HASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                              
                              # Constructor
                              @external
                              def __init__():
                                  # Set `asset` so it cannot be re-initialized.
                                  self.asset = self
                                  
                              @external
                              def initialize(
                                  asset: address, 
                                  name: String[64], 
                                  symbol: String[32], 
                                  role_manager: address, 
                                  profit_max_unlock_time: uint256
                              ):
                                  """
                                  @notice
                                      Initialize a new vault. Sets the asset, name, symbol, and role manager.
                                  @param asset
                                      The address of the asset that the vault will accept.
                                  @param name
                                      The name of the vault token.
                                  @param symbol
                                      The symbol of the vault token.
                                  @param role_manager 
                                      The address that can add and remove roles to addresses
                                  @param profit_max_unlock_time
                                      The amount of time that the profit will be locked for
                                  """
                                  assert self.asset == empty(address), "initialized"
                                  assert asset != empty(address), "ZERO ADDRESS"
                                  assert role_manager != empty(address), "ZERO ADDRESS"
                              
                                  self.asset = asset
                                  # Get the decimals for the vault to use.
                                  self.decimals = ERC20Detailed(asset).decimals()
                                  
                                  # Set the factory as the deployer address.
                                  self.factory = msg.sender
                              
                                  # Must be less than one year for report cycles
                                  assert profit_max_unlock_time <= 31_556_952 # dev: profit unlock time too long
                                  self.profit_max_unlock_time = profit_max_unlock_time
                              
                                  self.name = name
                                  self.symbol = symbol
                                  self.role_manager = role_manager
                              
                              ## SHARE MANAGEMENT ##
                              ## ERC20 ##
                              @internal
                              def _spend_allowance(owner: address, spender: address, amount: uint256):
                                  # Unlimited approval does nothing (saves an SSTORE)
                                  current_allowance: uint256 = self.allowance[owner][spender]
                                  if (current_allowance < max_value(uint256)):
                                      assert current_allowance >= amount, "insufficient allowance"
                                      self._approve(owner, spender, unsafe_sub(current_allowance, amount))
                              
                              @internal
                              def _transfer(sender: address, receiver: address, amount: uint256):
                                  sender_balance: uint256 = self.balance_of[sender]
                                  assert sender_balance >= amount, "insufficient funds"
                                  self.balance_of[sender] = unsafe_sub(sender_balance, amount)
                                  self.balance_of[receiver] = unsafe_add(self.balance_of[receiver], amount)
                                  log Transfer(sender, receiver, amount)
                              
                              @internal
                              def _transfer_from(sender: address, receiver: address, amount: uint256) -> bool:
                                  self._spend_allowance(sender, msg.sender, amount)
                                  self._transfer(sender, receiver, amount)
                                  return True
                              
                              @internal
                              def _approve(owner: address, spender: address, amount: uint256) -> bool:
                                  self.allowance[owner][spender] = amount
                                  log Approval(owner, spender, amount)
                                  return True
                              
                              @internal
                              def _permit(
                                  owner: address, 
                                  spender: address, 
                                  amount: uint256, 
                                  deadline: uint256, 
                                  v: uint8, 
                                  r: bytes32, 
                                  s: bytes32
                              ) -> bool:
                                  assert owner != empty(address), "invalid owner"
                                  assert deadline >= block.timestamp, "permit expired"
                                  nonce: uint256 = self.nonces[owner]
                                  digest: bytes32 = keccak256(
                                      concat(
                                          b'\x19\x01',
                                          self.domain_separator(),
                                          keccak256(
                                              concat(
                                                  PERMIT_TYPE_HASH,
                                                  convert(owner, bytes32),
                                                  convert(spender, bytes32),
                                                  convert(amount, bytes32),
                                                  convert(nonce, bytes32),
                                                  convert(deadline, bytes32),
                                              )
                                          )
                                      )
                                  )
                                  assert ecrecover(
                                      digest, v, r, s
                                  ) == owner, "invalid signature"
                              
                                  self.allowance[owner][spender] = amount
                                  self.nonces[owner] = nonce + 1
                                  log Approval(owner, spender, amount)
                                  return True
                              
                              @internal
                              def _burn_shares(shares: uint256, owner: address):
                                  self.balance_of[owner] -= shares
                                  self.total_supply = unsafe_sub(self.total_supply, shares)
                                  log Transfer(owner, empty(address), shares)
                              
                              @view
                              @internal
                              def _unlocked_shares() -> uint256:
                                  """
                                  Returns the amount of shares that have been unlocked.
                                  To avoid sudden price_per_share spikes, profits can be processed 
                                  through an unlocking period. The mechanism involves shares to be 
                                  minted to the vault which are unlocked gradually over time. Shares 
                                  that have been locked are gradually unlocked over profit_max_unlock_time.
                                  """
                                  _full_profit_unlock_date: uint256 = self.full_profit_unlock_date
                                  unlocked_shares: uint256 = 0
                                  if _full_profit_unlock_date > block.timestamp:
                                      # If we have not fully unlocked, we need to calculate how much has been.
                                      unlocked_shares = self.profit_unlocking_rate * (block.timestamp - self.last_profit_update) / MAX_BPS_EXTENDED
                              
                                  elif _full_profit_unlock_date != 0:
                                      # All shares have been unlocked
                                      unlocked_shares = self.balance_of[self]
                              
                                  return unlocked_shares
                              
                              
                              @view
                              @internal
                              def _total_supply() -> uint256:
                                  # Need to account for the shares issued to the vault that have unlocked.
                                  return self.total_supply - self._unlocked_shares()
                              
                              @view
                              @internal
                              def _total_assets() -> uint256:
                                  """
                                  Total amount of assets that are in the vault and in the strategies. 
                                  """
                                  return self.total_idle + self.total_debt
                              
                              @view
                              @internal
                              def _convert_to_assets(shares: uint256, rounding: Rounding) -> uint256:
                                  """ 
                                  assets = shares * (total_assets / total_supply) --- (== price_per_share * shares)
                                  """
                                  if shares == max_value(uint256) or shares == 0:
                                      return shares
                              
                                  total_supply: uint256 = self._total_supply()
                                  # if total_supply is 0, price_per_share is 1
                                  if total_supply == 0: 
                                      return shares
                              
                                  numerator: uint256 = shares * self._total_assets()
                                  amount: uint256 = numerator / total_supply
                                  if rounding == Rounding.ROUND_UP and numerator % total_supply != 0:
                                      amount += 1
                              
                                  return amount
                              
                              @view
                              @internal
                              def _convert_to_shares(assets: uint256, rounding: Rounding) -> uint256:
                                  """
                                  shares = amount * (total_supply / total_assets) --- (== amount / price_per_share)
                                  """
                                  if assets == max_value(uint256) or assets == 0:
                                      return assets
                              
                                  total_supply: uint256 = self._total_supply()
                                  total_assets: uint256 = self._total_assets()
                              
                                  if total_assets == 0:
                                      # if total_assets and total_supply is 0, price_per_share is 1
                                      if total_supply == 0:
                                          return assets
                                      else:
                                          # Else if total_supply > 0 price_per_share is 0
                                          return 0
                              
                                  numerator: uint256 = assets * total_supply
                                  shares: uint256 = numerator / total_assets
                                  if rounding == Rounding.ROUND_UP and numerator % total_assets != 0:
                                      shares += 1
                              
                                  return shares
                              
                              @internal
                              def _erc20_safe_approve(token: address, spender: address, amount: uint256):
                                  # Used only to approve tokens that are not the type managed by this Vault.
                                  # Used to handle non-compliant tokens like USDT
                                  assert ERC20(token).approve(spender, amount, default_return_value=True), "approval failed"
                              
                              @internal
                              def _erc20_safe_transfer_from(token: address, sender: address, receiver: address, amount: uint256):
                                  # Used only to transfer tokens that are not the type managed by this Vault.
                                  # Used to handle non-compliant tokens like USDT
                                  assert ERC20(token).transferFrom(sender, receiver, amount, default_return_value=True), "transfer failed"
                              
                              @internal
                              def _erc20_safe_transfer(token: address, receiver: address, amount: uint256):
                                  # Used only to send tokens that are not the type managed by this Vault.
                                  # Used to handle non-compliant tokens like USDT
                                  assert ERC20(token).transfer(receiver, amount, default_return_value=True), "transfer failed"
                              
                              @internal
                              def _issue_shares(shares: uint256, recipient: address):
                                  self.balance_of[recipient] = unsafe_add(self.balance_of[recipient], shares)
                                  self.total_supply += shares
                              
                                  log Transfer(empty(address), recipient, shares)
                              
                              @internal
                              def _issue_shares_for_amount(amount: uint256, recipient: address) -> uint256:
                                  """
                                  Issues shares that are worth 'amount' in the underlying token (asset).
                                  WARNING: this takes into account that any new assets have been summed 
                                  to total_assets (otherwise pps will go down).
                                  """
                                  total_supply: uint256 = self._total_supply()
                                  total_assets: uint256 = self._total_assets()
                                  new_shares: uint256 = 0
                                  
                                  # If no supply PPS = 1.
                                  if total_supply == 0:
                                      new_shares = amount
                                  elif total_assets > amount:
                                      new_shares = amount * total_supply / (total_assets - amount)
                              
                                  # We don't make the function revert
                                  if new_shares == 0:
                                     return 0
                              
                                  self._issue_shares(new_shares, recipient)
                              
                                  return new_shares
                              
                              ## ERC4626 ##
                              @view
                              @internal
                              def _max_deposit(receiver: address) -> uint256: 
                                  if receiver in [empty(address), self]:
                                      return 0
                              
                                  # If there is a deposit limit module set use that.
                                  deposit_limit_module: address = self.deposit_limit_module
                                  if deposit_limit_module != empty(address):
                                      return IDepositLimitModule(deposit_limit_module).available_deposit_limit(receiver)
                                  
                                  # Else use the standard flow.
                                  _deposit_limit: uint256 = self.deposit_limit
                                  if (_deposit_limit == max_value(uint256)):
                                      return _deposit_limit
                              
                                  _total_assets: uint256 = self._total_assets()
                                  if (_total_assets >= _deposit_limit):
                                      return 0
                              
                                  return unsafe_sub(_deposit_limit, _total_assets)
                              
                              @view
                              @internal
                              def _max_withdraw(
                                  owner: address,
                                  max_loss: uint256,
                                  strategies: DynArray[address, MAX_QUEUE]
                              ) -> uint256:
                                  """
                                  @dev Returns the max amount of `asset` an `owner` can withdraw.
                              
                                  This will do a full simulation of the withdraw in order to determine
                                  how much is currently liquid and if the `max_loss` would allow for the 
                                  tx to not revert.
                              
                                  This will track any expected loss to check if the tx will revert, but
                                  not account for it in the amount returned since it is unrealised and 
                                  therefore will not be accounted for in the conversion rates.
                              
                                  i.e. If we have 100 debt and 10 of unrealised loss, the max we can get
                                  out is 90, but a user of the vault will need to call withdraw with 100
                                  in order to get the full 90 out.
                                  """
                              
                                  # Get the max amount for the owner if fully liquid.
                                  max_assets: uint256 = self._convert_to_assets(self.balance_of[owner], Rounding.ROUND_DOWN)
                              
                                  # If there is a withdraw limit module use that.
                                  withdraw_limit_module: address = self.withdraw_limit_module
                                  if withdraw_limit_module != empty(address):
                                      return min(
                                          # Use the min between the returned value and the max.
                                          # Means the limit module doesn't need to account for balances or conversions.
                                          IWithdrawLimitModule(withdraw_limit_module).available_withdraw_limit(owner, max_loss, strategies),
                                          max_assets
                                      )
                                  
                                  # See if we have enough idle to service the withdraw.
                                  current_idle: uint256 = self.total_idle
                                  if max_assets > current_idle:
                                      # Track how much we can pull.
                                      have: uint256 = current_idle
                                      loss: uint256 = 0
                              
                                      # Cache the default queue.
                                      _strategies: DynArray[address, MAX_QUEUE] = self.default_queue
                              
                                      # If a custom queue was passed, and we don't force the default queue.
                                      if len(strategies) != 0 and not self.use_default_queue:
                                          # Use the custom queue.
                                          _strategies = strategies
                              
                                      for strategy in _strategies:
                                          # Can't use an invalid strategy.
                                          assert self.strategies[strategy].activation != 0, "inactive strategy"
                              
                                          # Get the maximum amount the vault would withdraw from the strategy.
                                          to_withdraw: uint256 = min(
                                              # What we still need for the full withdraw.
                                              max_assets - have, 
                                              # The current debt the strategy has.
                                              self.strategies[strategy].current_debt
                                          )
                              
                                          # Get any unrealised loss for the strategy.
                                          unrealised_loss: uint256 = self._assess_share_of_unrealised_losses(strategy, to_withdraw)
                              
                                          # See if any limit is enforced by the strategy.
                                          strategy_limit: uint256 = IStrategy(strategy).convertToAssets(
                                              IStrategy(strategy).maxRedeem(self)
                                          )
                              
                                          # Adjust accordingly if there is a max withdraw limit.
                                          realizable_withdraw: uint256 = to_withdraw - unrealised_loss
                                          if strategy_limit < realizable_withdraw:
                                              if unrealised_loss != 0:
                                                  # lower unrealised loss proportional to the limit.
                                                  unrealised_loss = unrealised_loss * strategy_limit / realizable_withdraw
                              
                                              # Still count the unrealised loss as withdrawable.
                                              to_withdraw = strategy_limit + unrealised_loss
                                              
                                          # If 0 move on to the next strategy.
                                          if to_withdraw == 0:
                                              continue
                              
                                          # If there would be a loss with a non-maximum `max_loss` value.
                                          if unrealised_loss > 0 and max_loss < MAX_BPS:
                                              # Check if the loss is greater than the allowed range.
                                              if loss + unrealised_loss > (have + to_withdraw) * max_loss / MAX_BPS:
                                                  # If so use the amounts up till now.
                                                  break
                              
                                          # Add to what we can pull.
                                          have += to_withdraw
                              
                                          # If we have all we need break.
                                          if have >= max_assets:
                                              break
                              
                                          # Add any unrealised loss to the total
                                          loss += unrealised_loss
                              
                                      # Update the max after going through the queue.
                                      # In case we broke early or exhausted the queue.
                                      max_assets = have
                              
                                  return max_assets
                              
                              @internal
                              def _deposit(sender: address, recipient: address, assets: uint256) -> uint256:
                                  """
                                  Used for `deposit` calls to transfer the amount of `asset` to the vault, 
                                  issue the corresponding shares to the `recipient` and update all needed 
                                  vault accounting.
                                  """
                                  assert self.shutdown == False # dev: shutdown
                                  assert assets <= self._max_deposit(recipient), "exceed deposit limit"
                               
                                  # Transfer the tokens to the vault first.
                                  self._erc20_safe_transfer_from(self.asset, msg.sender, self, assets)
                                  # Record the change in total assets.
                                  self.total_idle += assets
                                  
                                  # Issue the corresponding shares for assets.
                                  shares: uint256 = self._issue_shares_for_amount(assets, recipient)
                              
                                  assert shares > 0, "cannot mint zero"
                              
                                  log Deposit(sender, recipient, assets, shares)
                                  return shares
                              
                              @internal
                              def _mint(sender: address, recipient: address, shares: uint256) -> uint256:
                                  """
                                  Used for `mint` calls to issue the corresponding shares to the `recipient`,
                                  transfer the amount of `asset` to the vault, and update all needed vault 
                                  accounting.
                                  """
                                  assert self.shutdown == False # dev: shutdown
                                  # Get corresponding amount of assets.
                                  assets: uint256 = self._convert_to_assets(shares, Rounding.ROUND_UP)
                              
                                  assert assets > 0, "cannot deposit zero"
                                  assert assets <= self._max_deposit(recipient), "exceed deposit limit"
                              
                                  # Transfer the tokens to the vault first.
                                  self._erc20_safe_transfer_from(self.asset, msg.sender, self, assets)
                                  # Record the change in total assets.
                                  self.total_idle += assets
                                  
                                  # Issue the corresponding shares for assets.
                                  self._issue_shares(shares, recipient)
                              
                                  log Deposit(sender, recipient, assets, shares)
                                  return assets
                              
                              @view
                              @internal
                              def _assess_share_of_unrealised_losses(strategy: address, assets_needed: uint256) -> uint256:
                                  """
                                  Returns the share of losses that a user would take if withdrawing from this strategy
                                  This accounts for losses that have been realized at the strategy level but not yet
                                  realized at the vault level.
                              
                                  e.g. if the strategy has unrealised losses for 10% of its current debt and the user 
                                  wants to withdraw 1_000 tokens, the losses that they will take is 100 token
                                  """
                                  # Minimum of how much debt the debt should be worth.
                                  strategy_current_debt: uint256 = self.strategies[strategy].current_debt
                                  # The actual amount that the debt is currently worth.
                                  vault_shares: uint256 = IStrategy(strategy).balanceOf(self)
                                  strategy_assets: uint256 = IStrategy(strategy).convertToAssets(vault_shares)
                                  
                                  # If no losses, return 0
                                  if strategy_assets >= strategy_current_debt or strategy_current_debt == 0:
                                      return 0
                              
                                  # Users will withdraw assets_needed divided by loss ratio (strategy_assets / strategy_current_debt - 1).
                                  # NOTE: If there are unrealised losses, the user will take his share.
                                  numerator: uint256 = assets_needed * strategy_assets
                                  users_share_of_loss: uint256 = assets_needed - numerator / strategy_current_debt
                                  # Always round up.
                                  if numerator % strategy_current_debt != 0:
                                      users_share_of_loss += 1
                              
                                  return users_share_of_loss
                              
                              @internal
                              def _withdraw_from_strategy(strategy: address, assets_to_withdraw: uint256):
                                  """
                                  This takes the amount denominated in asset and performs a {redeem}
                                  with the corresponding amount of shares.
                              
                                  We use {redeem} to natively take on losses without additional non-4626 standard parameters.
                                  """
                                  # Need to get shares since we use redeem to be able to take on losses.
                                  shares_to_redeem: uint256 = min(
                                      # Use previewWithdraw since it should round up.
                                      IStrategy(strategy).previewWithdraw(assets_to_withdraw), 
                                      # And check against our actual balance.
                                      IStrategy(strategy).balanceOf(self)
                                  )
                                  # Redeem the shares.
                                  IStrategy(strategy).redeem(shares_to_redeem, self, self)
                              
                              @internal
                              def _redeem(
                                  sender: address, 
                                  receiver: address, 
                                  owner: address,
                                  assets: uint256,
                                  shares: uint256, 
                                  max_loss: uint256,
                                  strategies: DynArray[address, MAX_QUEUE]
                              ) -> uint256:
                                  """
                                  This will attempt to free up the full amount of assets equivalent to
                                  `shares` and transfer them to the `receiver`. If the vault does
                                  not have enough idle funds it will go through any strategies provided by
                                  either the withdrawer or the default_queue to free up enough funds to 
                                  service the request.
                              
                                  The vault will attempt to account for any unrealized losses taken on from
                                  strategies since their respective last reports.
                              
                                  Any losses realized during the withdraw from a strategy will be passed on
                                  to the user that is redeeming their vault shares unless it exceeds the given
                                  `max_loss`.
                                  """
                                  assert receiver != empty(address), "ZERO ADDRESS"
                                  assert shares > 0, "no shares to redeem"
                                  assert assets > 0, "no assets to withdraw"
                                  assert max_loss <= MAX_BPS, "max loss"
                                  
                                  # If there is a withdraw limit module, check the max.
                                  withdraw_limit_module: address = self.withdraw_limit_module
                                  if withdraw_limit_module != empty(address):
                                      assert assets <= IWithdrawLimitModule(withdraw_limit_module).available_withdraw_limit(owner, max_loss, strategies), "exceed withdraw limit"
                              
                                  assert self.balance_of[owner] >= shares, "insufficient shares to redeem"
                                  
                                  if sender != owner:
                                      self._spend_allowance(owner, sender, shares)
                              
                                  # The amount of the underlying token to withdraw.
                                  requested_assets: uint256 = assets
                              
                                  # load to memory to save gas
                                  current_total_idle: uint256 = self.total_idle
                                  _asset: address = self.asset
                              
                                  # If there are not enough assets in the Vault contract, we try to free
                                  # funds from strategies.
                                  if requested_assets > current_total_idle:
                              
                                      # Cache the default queue.
                                      _strategies: DynArray[address, MAX_QUEUE] = self.default_queue
                              
                                      # If a custom queue was passed, and we don't force the default queue.
                                      if len(strategies) != 0 and not self.use_default_queue:
                                          # Use the custom queue.
                                          _strategies = strategies
                              
                                      # load to memory to save gas
                                      current_total_debt: uint256 = self.total_debt
                              
                                      # Withdraw from strategies only what idle doesn't cover.
                                      # `assets_needed` is the total amount we need to fill the request.
                                      assets_needed: uint256 = unsafe_sub(requested_assets, current_total_idle)
                                      # `assets_to_withdraw` is the amount to request from the current strategy.
                                      assets_to_withdraw: uint256 = 0
                              
                                      # To compare against real withdrawals from strategies
                                      previous_balance: uint256 = ERC20(_asset).balanceOf(self)
                              
                                      for strategy in _strategies:
                                          # Make sure we have a valid strategy.
                                          assert self.strategies[strategy].activation != 0, "inactive strategy"
                              
                                          # How much should the strategy have.
                                          current_debt: uint256 = self.strategies[strategy].current_debt
                              
                                          # What is the max amount to withdraw from this strategy.
                                          assets_to_withdraw = min(assets_needed, current_debt)
                              
                                          # Cache max_withdraw now for use if unrealized loss > 0
                                          # Use maxRedeem and convert it since we use redeem.
                                          max_withdraw: uint256 = IStrategy(strategy).convertToAssets(
                                              IStrategy(strategy).maxRedeem(self)
                                          )
                              
                                          # CHECK FOR UNREALISED LOSSES
                                          # If unrealised losses > 0, then the user will take the proportional share 
                                          # and realize it (required to avoid users withdrawing from lossy strategies).
                                          # NOTE: strategies need to manage the fact that realising part of the loss can 
                                          # mean the realisation of 100% of the loss!! (i.e. if for withdrawing 10% of the
                                          # strategy it needs to unwind the whole position, generated losses might be bigger)
                                          unrealised_losses_share: uint256 = self._assess_share_of_unrealised_losses(strategy, assets_to_withdraw)
                                          if unrealised_losses_share > 0:
                                              # If max withdraw is limiting the amount to pull, we need to adjust the portion of 
                                              # the unrealized loss the user should take.
                                              if max_withdraw < assets_to_withdraw - unrealised_losses_share:
                                                  # How much would we want to withdraw
                                                  wanted: uint256 = assets_to_withdraw - unrealised_losses_share
                                                  # Get the proportion of unrealised comparing what we want vs. what we can get
                                                  unrealised_losses_share = unrealised_losses_share * max_withdraw / wanted
                                                  # Adjust assets_to_withdraw so all future calculations work correctly
                                                  assets_to_withdraw = max_withdraw + unrealised_losses_share
                                              
                                              # User now "needs" less assets to be unlocked (as he took some as losses)
                                              assets_to_withdraw -= unrealised_losses_share
                                              requested_assets -= unrealised_losses_share
                                              # NOTE: done here instead of waiting for regular update of these values 
                                              # because it's a rare case (so we can save minor amounts of gas)
                                              assets_needed -= unrealised_losses_share
                                              current_total_debt -= unrealised_losses_share
                              
                                              # If max withdraw is 0 and unrealised loss is still > 0 then the strategy likely
                                              # realized a 100% loss and we will need to realize that loss before moving on.
                                              if max_withdraw == 0 and unrealised_losses_share > 0:
                                                  # Adjust the strategy debt accordingly.
                                                  new_debt: uint256 = current_debt - unrealised_losses_share
                                      
                                                  # Update strategies storage
                                                  self.strategies[strategy].current_debt = new_debt
                                                  # Log the debt update
                                                  log DebtUpdated(strategy, current_debt, new_debt)
                              
                                          # Adjust based on the max withdraw of the strategy.
                                          assets_to_withdraw = min(assets_to_withdraw, max_withdraw)
                              
                                          # Can't withdraw 0.
                                          if assets_to_withdraw == 0:
                                              continue
                                          
                                          # WITHDRAW FROM STRATEGY
                                          self._withdraw_from_strategy(strategy, assets_to_withdraw)
                                          post_balance: uint256 = ERC20(_asset).balanceOf(self)
                                          
                                          # Always check against the real amounts.
                                          withdrawn: uint256 = post_balance - previous_balance
                                          loss: uint256 = 0
                                          # Check if we redeemed too much.
                                          if withdrawn > assets_to_withdraw:
                                              # Make sure we don't underflow in debt updates.
                                              if withdrawn > current_debt:
                                                  # Can't withdraw more than our debt.
                                                  assets_to_withdraw = current_debt
                                              else:
                                                  # Add the extra to how much we withdrew.
                                                  assets_to_withdraw += (unsafe_sub(withdrawn, assets_to_withdraw))
                              
                                          # If we have not received what we expected, we consider the difference a loss.
                                          elif withdrawn < assets_to_withdraw:
                                              loss = unsafe_sub(assets_to_withdraw, withdrawn)
                              
                                          # NOTE: strategy's debt decreases by the full amount but the total idle increases 
                                          # by the actual amount only (as the difference is considered lost).
                                          current_total_idle += (assets_to_withdraw - loss)
                                          requested_assets -= loss
                                          current_total_debt -= assets_to_withdraw
                              
                                          # Vault will reduce debt because the unrealised loss has been taken by user
                                          new_debt: uint256 = current_debt - (assets_to_withdraw + unrealised_losses_share)
                                      
                                          # Update strategies storage
                                          self.strategies[strategy].current_debt = new_debt
                                          # Log the debt update
                                          log DebtUpdated(strategy, current_debt, new_debt)
                              
                                          # Break if we have enough total idle to serve initial request.
                                          if requested_assets <= current_total_idle:
                                              break
                              
                                          # We update the previous_balance variable here to save gas in next iteration.
                                          previous_balance = post_balance
                              
                                          # Reduce what we still need. Safe to use assets_to_withdraw 
                                          # here since it has been checked against requested_assets
                                          assets_needed -= assets_to_withdraw
                              
                                      # If we exhaust the queue and still have insufficient total idle, revert.
                                      assert current_total_idle >= requested_assets, "insufficient assets in vault"
                                      # Commit memory to storage.
                                      self.total_debt = current_total_debt
                              
                                  # Check if there is a loss and a non-default value was set.
                                  if assets > requested_assets and max_loss < MAX_BPS:
                                      # Assure the loss is within the allowed range.
                                      assert assets - requested_assets <= assets * max_loss / MAX_BPS, "too much loss"
                              
                                  # First burn the corresponding shares from the redeemer.
                                  self._burn_shares(shares, owner)
                                  # Commit memory to storage.
                                  self.total_idle = current_total_idle - requested_assets
                                  # Transfer the requested amount to the receiver.
                                  self._erc20_safe_transfer(_asset, receiver, requested_assets)
                              
                                  log Withdraw(sender, receiver, owner, requested_assets, shares)
                                  return requested_assets
                              
                              ## STRATEGY MANAGEMENT ##
                              @internal
                              def _add_strategy(new_strategy: address, add_to_queue: bool):
                                  assert new_strategy not in [self, empty(address)], "strategy cannot be zero address"
                                  assert IStrategy(new_strategy).asset() == self.asset, "invalid asset"
                                  assert self.strategies[new_strategy].activation == 0, "strategy already active"
                              
                                  # Add the new strategy to the mapping.
                                  self.strategies[new_strategy] = StrategyParams({
                                      activation: block.timestamp,
                                      last_report: block.timestamp,
                                      current_debt: 0,
                                      max_debt: 0
                                  })
                              
                                  # If we are adding to the queue and the default queue has space, add the strategy.
                                  if add_to_queue and len(self.default_queue) < MAX_QUEUE:
                                      self.default_queue.append(new_strategy)        
                                      
                                  log StrategyChanged(new_strategy, StrategyChangeType.ADDED)
                              
                              @internal
                              def _revoke_strategy(strategy: address, force: bool=False):
                                  assert self.strategies[strategy].activation != 0, "strategy not active"
                              
                                  # If force revoking a strategy, it will cause a loss.
                                  loss: uint256 = 0
                                  
                                  if self.strategies[strategy].current_debt != 0:
                                      assert force, "strategy has debt"
                                      # Vault realizes the full loss of outstanding debt.
                                      loss = self.strategies[strategy].current_debt
                                      # Adjust total vault debt.
                                      self.total_debt -= loss
                              
                                      log StrategyReported(strategy, 0, loss, 0, 0, 0, 0)
                              
                                  # Set strategy params all back to 0 (WARNING: it can be re-added).
                                  self.strategies[strategy] = StrategyParams({
                                    activation: 0,
                                    last_report: 0,
                                    current_debt: 0,
                                    max_debt: 0
                                  })
                              
                                  # Remove strategy if it is in the default queue.
                                  new_queue: DynArray[address, MAX_QUEUE] = []
                                  for _strategy in self.default_queue:
                                      # Add all strategies to the new queue besides the one revoked.
                                      if _strategy != strategy:
                                          new_queue.append(_strategy)
                                      
                                  # Set the default queue to our updated queue.
                                  self.default_queue = new_queue
                              
                                  log StrategyChanged(strategy, StrategyChangeType.REVOKED)
                              
                              # DEBT MANAGEMENT #
                              @internal
                              def _update_debt(strategy: address, target_debt: uint256, max_loss: uint256) -> uint256:
                                  """
                                  The vault will re-balance the debt vs target debt. Target debt must be
                                  smaller or equal to strategy's max_debt. This function will compare the 
                                  current debt with the target debt and will take funds or deposit new 
                                  funds to the strategy. 
                              
                                  The strategy can require a maximum amount of funds that it wants to receive
                                  to invest. The strategy can also reject freeing funds if they are locked.
                                  """
                                  # How much we want the strategy to have.
                                  new_debt: uint256 = target_debt
                                  # How much the strategy currently has.
                                  current_debt: uint256 = self.strategies[strategy].current_debt
                              
                                  # If the vault is shutdown we can only pull funds.
                                  if self.shutdown:
                                      new_debt = 0
                              
                                  assert new_debt != current_debt, "new debt equals current debt"
                              
                                  if current_debt > new_debt:
                                      # Reduce debt.
                                      assets_to_withdraw: uint256 = unsafe_sub(current_debt, new_debt)
                              
                                      # Ensure we always have minimum_total_idle when updating debt.
                                      minimum_total_idle: uint256 = self.minimum_total_idle
                                      total_idle: uint256 = self.total_idle
                                      
                                      # Respect minimum total idle in vault
                                      if total_idle + assets_to_withdraw < minimum_total_idle:
                                          assets_to_withdraw = unsafe_sub(minimum_total_idle, total_idle)
                                          # Cant withdraw more than the strategy has.
                                          if assets_to_withdraw > current_debt:
                                              assets_to_withdraw = current_debt
                              
                                      # Check how much we are able to withdraw.
                                      # Use maxRedeem and convert since we use redeem.
                                      withdrawable: uint256 = IStrategy(strategy).convertToAssets(
                                          IStrategy(strategy).maxRedeem(self)
                                      )
                                      assert withdrawable != 0, "nothing to withdraw"
                              
                                      # If insufficient withdrawable, withdraw what we can.
                                      if withdrawable < assets_to_withdraw:
                                          assets_to_withdraw = withdrawable
                              
                                      # If there are unrealised losses we don't let the vault reduce its debt until there is a new report
                                      unrealised_losses_share: uint256 = self._assess_share_of_unrealised_losses(strategy, assets_to_withdraw)
                                      assert unrealised_losses_share == 0, "strategy has unrealised losses"
                                      
                                      # Cache for repeated use.
                                      _asset: address = self.asset
                              
                                      # Always check the actual amount withdrawn.
                                      pre_balance: uint256 = ERC20(_asset).balanceOf(self)
                                      self._withdraw_from_strategy(strategy, assets_to_withdraw)
                                      post_balance: uint256 = ERC20(_asset).balanceOf(self)
                                      
                                      # making sure we are changing idle according to the real result no matter what. 
                                      # We pull funds with {redeem} so there can be losses or rounding differences.
                                      withdrawn: uint256 = min(post_balance - pre_balance, current_debt)
                              
                                      # If we didn't get the amount we asked for and there is a max loss.
                                      if withdrawn < assets_to_withdraw and max_loss < MAX_BPS:
                                          # Make sure the loss is within the allowed range.
                                          assert assets_to_withdraw - withdrawn <= assets_to_withdraw * max_loss / MAX_BPS, "too much loss"
                              
                                      # If we got too much make sure not to increase PPS.
                                      elif withdrawn > assets_to_withdraw:
                                          assets_to_withdraw = withdrawn
                              
                                      # Update storage.
                                      self.total_idle += withdrawn # actual amount we got.
                                      # Amount we tried to withdraw in case of losses
                                      self.total_debt -= assets_to_withdraw 
                              
                                      new_debt = current_debt - assets_to_withdraw
                                  else: 
                                      # We are increasing the strategies debt
                              
                                      # Revert if target_debt cannot be achieved due to configured max_debt for given strategy
                                      assert new_debt <= self.strategies[strategy].max_debt, "target debt higher than max debt"
                              
                                      # Vault is increasing debt with the strategy by sending more funds.
                                      max_deposit: uint256 = IStrategy(strategy).maxDeposit(self)
                                      assert max_deposit != 0, "nothing to deposit"
                              
                                      # Deposit the difference between desired and current.
                                      assets_to_deposit: uint256 = new_debt - current_debt
                                      if assets_to_deposit > max_deposit:
                                          # Deposit as much as possible.
                                          assets_to_deposit = max_deposit
                                      
                                      # Ensure we always have minimum_total_idle when updating debt.
                                      minimum_total_idle: uint256 = self.minimum_total_idle
                                      total_idle: uint256 = self.total_idle
                              
                                      assert total_idle > minimum_total_idle, "no funds to deposit"
                                      available_idle: uint256 = unsafe_sub(total_idle, minimum_total_idle)
                              
                                      # If insufficient funds to deposit, transfer only what is free.
                                      if assets_to_deposit > available_idle:
                                          assets_to_deposit = available_idle
                              
                                      # Can't Deposit 0.
                                      if assets_to_deposit > 0:
                                          # Cache for repeated use.
                                          _asset: address = self.asset
                              
                                          # Approve the strategy to pull only what we are giving it.
                                          self._erc20_safe_approve(_asset, strategy, assets_to_deposit)
                              
                                          # Always update based on actual amounts deposited.
                                          pre_balance: uint256 = ERC20(_asset).balanceOf(self)
                                          IStrategy(strategy).deposit(assets_to_deposit, self)
                                          post_balance: uint256 = ERC20(_asset).balanceOf(self)
                              
                                          # Make sure our approval is always back to 0.
                                          self._erc20_safe_approve(_asset, strategy, 0)
                              
                                          # Making sure we are changing according to the real result no 
                                          # matter what. This will spend more gas but makes it more robust.
                                          assets_to_deposit = pre_balance - post_balance
                              
                                          # Update storage.
                                          self.total_idle -= assets_to_deposit
                                          self.total_debt += assets_to_deposit
                              
                                      new_debt = current_debt + assets_to_deposit
                              
                                  # Commit memory to storage.
                                  self.strategies[strategy].current_debt = new_debt
                              
                                  log DebtUpdated(strategy, current_debt, new_debt)
                                  return new_debt
                              
                              ## ACCOUNTING MANAGEMENT ##
                              @internal
                              def _process_report(strategy: address) -> (uint256, uint256):
                                  """
                                  Processing a report means comparing the debt that the strategy has taken 
                                  with the current amount of funds it is reporting. If the strategy owes 
                                  less than it currently has, it means it has had a profit, else (assets < debt) 
                                  it has had a loss.
                              
                                  Different strategies might choose different reporting strategies: pessimistic, 
                                  only realised P&L, ... The best way to report depends on the strategy.
                              
                                  The profit will be distributed following a smooth curve over the vaults 
                                  profit_max_unlock_time seconds. Losses will be taken immediately, first from the 
                                  profit buffer (avoiding an impact in pps), then will reduce pps.
                              
                                  Any applicable fees are charged and distributed during the report as well
                                  to the specified recipients.
                                  """
                                  # Make sure we have a valid strategy.
                                  assert self.strategies[strategy].activation != 0, "inactive strategy"
                              
                                  # Vault assesses profits using 4626 compliant interface. 
                                  # NOTE: It is important that a strategies `convertToAssets` implementation
                                  # cannot be manipulated or else the vault could report incorrect gains/losses.
                                  strategy_shares: uint256 = IStrategy(strategy).balanceOf(self)
                                  # How much the vaults position is worth.
                                  total_assets: uint256 = IStrategy(strategy).convertToAssets(strategy_shares)
                                  # How much the vault had deposited to the strategy.
                                  current_debt: uint256 = self.strategies[strategy].current_debt
                              
                                  gain: uint256 = 0
                                  loss: uint256 = 0
                              
                                  ### Asses Gain or Loss ###
                              
                                  # Compare reported assets vs. the current debt.
                                  if total_assets > current_debt:
                                      # We have a gain.
                                      gain = unsafe_sub(total_assets, current_debt)
                                  else:
                                      # We have a loss.
                                      loss = unsafe_sub(current_debt, total_assets)
                                  
                                  # Cache `asset` for repeated use.
                                  _asset: address = self.asset
                              
                                  ### Asses Fees and Refunds ###
                              
                                  # For Accountant fee assessment.
                                  total_fees: uint256 = 0
                                  total_refunds: uint256 = 0
                                  # If accountant is not set, fees and refunds remain unchanged.
                                  accountant: address = self.accountant
                                  if accountant != empty(address):
                                      total_fees, total_refunds = IAccountant(accountant).report(strategy, gain, loss)
                              
                                      if total_refunds > 0:
                                          # Make sure we have enough approval and enough asset to pull.
                                          total_refunds = min(total_refunds, min(ERC20(_asset).balanceOf(accountant), ERC20(_asset).allowance(accountant, self)))
                              
                                  # Total fees to charge in shares.
                                  total_fees_shares: uint256 = 0
                                  # For Protocol fee assessment.
                                  protocol_fee_bps: uint16 = 0
                                  protocol_fees_shares: uint256 = 0
                                  protocol_fee_recipient: address = empty(address)
                                  # `shares_to_burn` is derived from amounts that would reduce the vaults PPS.
                                  # NOTE: this needs to be done before any pps changes
                                  shares_to_burn: uint256 = 0
                                  # Only need to burn shares if there is a loss or fees.
                                  if loss + total_fees > 0:
                                      # The amount of shares we will want to burn to offset losses and fees.
                                      shares_to_burn = self._convert_to_shares(loss + total_fees, Rounding.ROUND_UP)
                              
                                      # If we have fees then get the proportional amount of shares to issue.
                                      if total_fees > 0:
                                          # Get the total amount shares to issue for the fees.
                                          total_fees_shares = shares_to_burn * total_fees / (loss + total_fees)
                              
                                          # Get the protocol fee config for this vault.
                                          protocol_fee_bps, protocol_fee_recipient = IFactory(self.factory).protocol_fee_config()
                              
                                          # If there is a protocol fee.
                                          if protocol_fee_bps > 0:
                                              # Get the percent of fees to go to protocol fees.
                                              protocol_fees_shares = total_fees_shares * convert(protocol_fee_bps, uint256) / MAX_BPS
                              
                              
                                  # Shares to lock is any amount that would otherwise increase the vaults PPS.
                                  shares_to_lock: uint256 = 0
                                  profit_max_unlock_time: uint256 = self.profit_max_unlock_time
                                  # Get the amount we will lock to avoid a PPS increase.
                                  if gain + total_refunds > 0 and profit_max_unlock_time != 0:
                                      shares_to_lock = self._convert_to_shares(gain + total_refunds, Rounding.ROUND_DOWN)
                              
                                  # The total current supply including locked shares.
                                  total_supply: uint256 = self.total_supply
                                  # The total shares the vault currently owns. Both locked and unlocked.
                                  total_locked_shares: uint256 = self.balance_of[self]
                                  # Get the desired end amount of shares after all accounting.
                                  ending_supply: uint256 = total_supply + shares_to_lock - shares_to_burn - self._unlocked_shares()
                                  
                                  # If we will end with more shares than we have now.
                                  if ending_supply > total_supply:
                                      # Issue the difference.
                                      self._issue_shares(unsafe_sub(ending_supply, total_supply), self)
                              
                                  # Else we need to burn shares.
                                  elif total_supply > ending_supply:
                                      # Can't burn more than the vault owns.
                                      to_burn: uint256 = min(unsafe_sub(total_supply, ending_supply), total_locked_shares)
                                      self._burn_shares(to_burn, self)
                              
                                  # Adjust the amount to lock for this period.
                                  if shares_to_lock > shares_to_burn:
                                      # Don't lock fees or losses.
                                      shares_to_lock = unsafe_sub(shares_to_lock, shares_to_burn)
                                  else:
                                      shares_to_lock = 0
                              
                                  # Pull refunds
                                  if total_refunds > 0:
                                      # Transfer the refunded amount of asset to the vault.
                                      self._erc20_safe_transfer_from(_asset, accountant, self, total_refunds)
                                      # Update storage to increase total assets.
                                      self.total_idle += total_refunds
                              
                                  # Record any reported gains.
                                  if gain > 0:
                                      # NOTE: this will increase total_assets
                                      current_debt = unsafe_add(current_debt, gain)
                                      self.strategies[strategy].current_debt = current_debt
                                      self.total_debt += gain
                              
                                  # Or record any reported loss
                                  elif loss > 0:
                                      current_debt = unsafe_sub(current_debt, loss)
                                      self.strategies[strategy].current_debt = current_debt
                                      self.total_debt -= loss
                              
                                  # Issue shares for fees that were calculated above if applicable.
                                  if total_fees_shares > 0:
                                      # Accountant fees are (total_fees - protocol_fees).
                                      self._issue_shares(total_fees_shares - protocol_fees_shares, accountant)
                              
                                      # If we also have protocol fees.
                                      if protocol_fees_shares > 0:
                                          self._issue_shares(protocol_fees_shares, protocol_fee_recipient)
                              
                                  # Update unlocking rate and time to fully unlocked.
                                  total_locked_shares = self.balance_of[self]
                                  if total_locked_shares > 0:
                                      previously_locked_time: uint256 = 0
                                      _full_profit_unlock_date: uint256 = self.full_profit_unlock_date
                                      # Check if we need to account for shares still unlocking.
                                      if _full_profit_unlock_date > block.timestamp: 
                                          # There will only be previously locked shares if time remains.
                                          # We calculate this here since it will not occur every time we lock shares.
                                          previously_locked_time = (total_locked_shares - shares_to_lock) * (_full_profit_unlock_date - block.timestamp)
                              
                                      # new_profit_locking_period is a weighted average between the remaining time of the previously locked shares and the profit_max_unlock_time
                                      new_profit_locking_period: uint256 = (previously_locked_time + shares_to_lock * profit_max_unlock_time) / total_locked_shares
                                      # Calculate how many shares unlock per second.
                                      self.profit_unlocking_rate = total_locked_shares * MAX_BPS_EXTENDED / new_profit_locking_period
                                      # Calculate how long until the full amount of shares is unlocked.
                                      self.full_profit_unlock_date = block.timestamp + new_profit_locking_period
                                      # Update the last profitable report timestamp.
                                      self.last_profit_update = block.timestamp
                                  else:
                                      # NOTE: only setting this to the 0 will turn in the desired effect, 
                                      # no need to update profit_unlocking_rate
                                      self.full_profit_unlock_date = 0
                                  
                                  # Record the report of profit timestamp.
                                  self.strategies[strategy].last_report = block.timestamp
                              
                                  # We have to recalculate the fees paid for cases with an overall loss or no profit locking
                                  if loss + total_fees > gain + total_refunds or profit_max_unlock_time == 0:
                                      total_fees = self._convert_to_assets(total_fees_shares, Rounding.ROUND_DOWN)
                              
                                  log StrategyReported(
                                      strategy,
                                      gain,
                                      loss,
                                      current_debt,
                                      total_fees * convert(protocol_fee_bps, uint256) / MAX_BPS, # Protocol Fees
                                      total_fees,
                                      total_refunds
                                  )
                              
                                  return (gain, loss)
                              
                              # SETTERS #
                              @external
                              def set_accountant(new_accountant: address):
                                  """
                                  @notice Set the new accountant address.
                                  @param new_accountant The new accountant address.
                                  """
                                  self._enforce_role(msg.sender, Roles.ACCOUNTANT_MANAGER)
                                  self.accountant = new_accountant
                              
                                  log UpdateAccountant(new_accountant)
                              
                              @external
                              def set_default_queue(new_default_queue: DynArray[address, MAX_QUEUE]):
                                  """
                                  @notice Set the new default queue array.
                                  @dev Will check each strategy to make sure it is active. But will not
                                      check that the same strategy is not added twice. maxRedeem and maxWithdraw
                                      return values may be inaccurate if a strategy is added twice.
                                  @param new_default_queue The new default queue array.
                                  """
                                  self._enforce_role(msg.sender, Roles.QUEUE_MANAGER)
                              
                                  # Make sure every strategy in the new queue is active.
                                  for strategy in new_default_queue:
                                      assert self.strategies[strategy].activation != 0, "!inactive"
                              
                                  # Save the new queue.
                                  self.default_queue = new_default_queue
                              
                                  log UpdateDefaultQueue(new_default_queue)
                              
                              @external
                              def set_use_default_queue(use_default_queue: bool):
                                  """
                                  @notice Set a new value for `use_default_queue`.
                                  @dev If set `True` the default queue will always be
                                      used no matter whats passed in.
                                  @param use_default_queue new value.
                                  """
                                  self._enforce_role(msg.sender, Roles.QUEUE_MANAGER)
                                  self.use_default_queue = use_default_queue
                              
                                  log UpdateUseDefaultQueue(use_default_queue)
                              
                              @external
                              def set_deposit_limit(deposit_limit: uint256, override: bool = False):
                                  """
                                  @notice Set the new deposit limit.
                                  @dev Can not be changed if a deposit_limit_module
                                  is set unless the override flag is true or if shutdown.
                                  @param deposit_limit The new deposit limit.
                                  @param override If a `deposit_limit_module` already set should be overridden.
                                  """
                                  assert self.shutdown == False # Dev: shutdown
                                  self._enforce_role(msg.sender, Roles.DEPOSIT_LIMIT_MANAGER)
                              
                                  # If we are overriding the deposit limit module.
                                  if override:
                                      # Make sure it is set to address 0 if not already.
                                      if self.deposit_limit_module != empty(address):
                              
                                          self.deposit_limit_module = empty(address)
                                          log UpdateDepositLimitModule(empty(address))
                                  else:  
                                      # Make sure the deposit_limit_module has been set to address(0).
                                      assert self.deposit_limit_module == empty(address), "using module"
                              
                                  self.deposit_limit = deposit_limit
                              
                                  log UpdateDepositLimit(deposit_limit)
                              
                              @external
                              def set_deposit_limit_module(deposit_limit_module: address, override: bool = False):
                                  """
                                  @notice Set a contract to handle the deposit limit.
                                  @dev The default `deposit_limit` will need to be set to
                                  max uint256 since the module will override it or the override flag
                                  must be set to true to set it to max in 1 tx..
                                  @param deposit_limit_module Address of the module.
                                  @param override If a `deposit_limit` already set should be overridden.
                                  """
                                  assert self.shutdown == False # Dev: shutdown
                                  self._enforce_role(msg.sender, Roles.DEPOSIT_LIMIT_MANAGER)
                              
                                  # If we are overriding the deposit limit
                                  if override:
                                      # Make sure it is max uint256 if not already.
                                      if self.deposit_limit != max_value(uint256):
                              
                                          self.deposit_limit = max_value(uint256)
                                          log UpdateDepositLimit(max_value(uint256))
                                  else:
                                      # Make sure the deposit_limit has been set to uint max.
                                      assert self.deposit_limit == max_value(uint256), "using deposit limit"
                              
                                  self.deposit_limit_module = deposit_limit_module
                              
                                  log UpdateDepositLimitModule(deposit_limit_module)
                              
                              @external
                              def set_withdraw_limit_module(withdraw_limit_module: address):
                                  """
                                  @notice Set a contract to handle the withdraw limit.
                                  @dev This will override the default `max_withdraw`.
                                  @param withdraw_limit_module Address of the module.
                                  """
                                  self._enforce_role(msg.sender, Roles.WITHDRAW_LIMIT_MANAGER)
                              
                                  self.withdraw_limit_module = withdraw_limit_module
                              
                                  log UpdateWithdrawLimitModule(withdraw_limit_module)
                              
                              @external
                              def set_minimum_total_idle(minimum_total_idle: uint256):
                                  """
                                  @notice Set the new minimum total idle.
                                  @param minimum_total_idle The new minimum total idle.
                                  """
                                  self._enforce_role(msg.sender, Roles.MINIMUM_IDLE_MANAGER)
                                  self.minimum_total_idle = minimum_total_idle
                              
                                  log UpdateMinimumTotalIdle(minimum_total_idle)
                              
                              @external
                              def setProfitMaxUnlockTime(new_profit_max_unlock_time: uint256):
                                  """
                                  @notice Set the new profit max unlock time.
                                  @dev The time is denominated in seconds and must be less than 1 year.
                                      We only need to update locking period if setting to 0,
                                      since the current period will use the old rate and on the next
                                      report it will be reset with the new unlocking time.
                                  
                                      Setting to 0 will cause any currently locked profit to instantly
                                      unlock and an immediate increase in the vaults Price Per Share.
                              
                                  @param new_profit_max_unlock_time The new profit max unlock time.
                                  """
                                  self._enforce_role(msg.sender, Roles.PROFIT_UNLOCK_MANAGER)
                                  # Must be less than one year for report cycles
                                  assert new_profit_max_unlock_time <= 31_556_952, "profit unlock time too long"
                              
                                  # If setting to 0 we need to reset any locked values.
                                  if (new_profit_max_unlock_time == 0):
                              
                                      share_balance: uint256 = self.balance_of[self]
                                      if share_balance > 0:
                                          # Burn any shares the vault still has.
                                          self._burn_shares(share_balance, self)
                              
                                      # Reset unlocking variables to 0.
                                      self.profit_unlocking_rate = 0
                                      self.full_profit_unlock_date = 0
                              
                                  self.profit_max_unlock_time = new_profit_max_unlock_time
                              
                                  log UpdateProfitMaxUnlockTime(new_profit_max_unlock_time)
                              
                              # ROLE MANAGEMENT #
                              @internal
                              def _enforce_role(account: address, role: Roles):
                                  # Make sure the sender holds the role.
                                  assert role in self.roles[account], "not allowed"
                              
                              @external
                              def set_role(account: address, role: Roles):
                                  """
                                  @notice Set the roles for an account.
                                  @dev This will fully override an accounts current roles
                                   so it should include all roles the account should hold.
                                  @param account The account to set the role for.
                                  @param role The roles the account should hold.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.roles[account] = role
                              
                                  log RoleSet(account, role)
                              
                              @external
                              def add_role(account: address, role: Roles):
                                  """
                                  @notice Add a new role to an address.
                                  @dev This will add a new role to the account
                                   without effecting any of the previously held roles.
                                  @param account The account to add a role to.
                                  @param role The new role to add to account.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.roles[account] = self.roles[account] | role
                              
                                  log RoleSet(account, self.roles[account])
                              
                              @external
                              def remove_role(account: address, role: Roles):
                                  """
                                  @notice Remove a single role from an account.
                                  @dev This will leave all other roles for the 
                                   account unchanged.
                                  @param account The account to remove a Role from.
                                  @param role The Role to remove.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.roles[account] = self.roles[account] & ~role
                              
                                  log RoleSet(account, self.roles[account])
                                  
                              @external
                              def transfer_role_manager(role_manager: address):
                                  """
                                  @notice Step 1 of 2 in order to transfer the 
                                      role manager to a new address. This will set
                                      the future_role_manager. Which will then need
                                      to be accepted by the new manager.
                                  @param role_manager The new role manager address.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.future_role_manager = role_manager
                              
                              @external
                              def accept_role_manager():
                                  """
                                  @notice Accept the role manager transfer.
                                  """
                                  assert msg.sender == self.future_role_manager
                                  self.role_manager = msg.sender
                                  self.future_role_manager = empty(address)
                              
                                  log UpdateRoleManager(msg.sender)
                              
                              # VAULT STATUS VIEWS
                              
                              @view
                              @external
                              def isShutdown() -> bool:
                                  """
                                  @notice Get if the vault is shutdown.
                                  @return Bool representing the shutdown status
                                  """
                                  return self.shutdown
                              @view
                              @external
                              def unlockedShares() -> uint256:
                                  """
                                  @notice Get the amount of shares that have been unlocked.
                                  @return The amount of shares that are have been unlocked.
                                  """
                                  return self._unlocked_shares()
                              
                              @view
                              @external
                              def pricePerShare() -> uint256:
                                  """
                                  @notice Get the price per share (pps) of the vault.
                                  @dev This value offers limited precision. Integrations that require 
                                      exact precision should use convertToAssets or convertToShares instead.
                                  @return The price per share.
                                  """
                                  return self._convert_to_assets(10 ** convert(self.decimals, uint256), Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def get_default_queue() -> DynArray[address, MAX_QUEUE]:
                                  """
                                  @notice Get the full default queue currently set.
                                  @return The current default withdrawal queue.
                                  """
                                  return self.default_queue
                              
                              ## REPORTING MANAGEMENT ##
                              @external
                              @nonreentrant("lock")
                              def process_report(strategy: address) -> (uint256, uint256):
                                  """
                                  @notice Process the report of a strategy.
                                  @param strategy The strategy to process the report for.
                                  @return The gain and loss of the strategy.
                                  """
                                  self._enforce_role(msg.sender, Roles.REPORTING_MANAGER)
                                  return self._process_report(strategy)
                              
                              @external
                              @nonreentrant("lock")
                              def buy_debt(strategy: address, amount: uint256):
                                  """
                                  @notice Used for governance to buy bad debt from the vault.
                                  @dev This should only ever be used in an emergency in place
                                  of force revoking a strategy in order to not report a loss.
                                  It allows the DEBT_PURCHASER role to buy the strategies debt
                                  for an equal amount of `asset`. 
                              
                                  @param strategy The strategy to buy the debt for
                                  @param amount The amount of debt to buy from the vault.
                                  """
                                  self._enforce_role(msg.sender, Roles.DEBT_PURCHASER)
                                  assert self.strategies[strategy].activation != 0, "not active"
                                  
                                  # Cache the current debt.
                                  current_debt: uint256 = self.strategies[strategy].current_debt
                                  _amount: uint256 = amount
                              
                                  assert current_debt > 0, "nothing to buy"
                                  assert _amount > 0, "nothing to buy with"
                                  
                                  if _amount > current_debt:
                                      _amount = current_debt
                              
                                  # We get the proportion of the debt that is being bought and
                                  # transfer the equivalent shares. We assume this is being used
                                  # due to strategy issues so won't rely on its conversion rates.
                                  shares: uint256 = IStrategy(strategy).balanceOf(self) * _amount / current_debt
                              
                                  assert shares > 0, "cannot buy zero"
                              
                                  self._erc20_safe_transfer_from(self.asset, msg.sender, self, _amount)
                              
                                  # Lower strategy debt
                                  self.strategies[strategy].current_debt -= _amount
                                  # lower total debt
                                  self.total_debt -= _amount
                                  # Increase total idle
                                  self.total_idle += _amount
                              
                                  # log debt change
                                  log DebtUpdated(strategy, current_debt, current_debt - _amount)
                              
                                  # Transfer the strategies shares out.
                                  self._erc20_safe_transfer(strategy, msg.sender, shares)
                              
                                  log DebtPurchased(strategy, _amount)
                              
                              ## STRATEGY MANAGEMENT ##
                              @external
                              def add_strategy(new_strategy: address, add_to_queue: bool=True):
                                  """
                                  @notice Add a new strategy.
                                  @param new_strategy The new strategy to add.
                                  """
                                  self._enforce_role(msg.sender, Roles.ADD_STRATEGY_MANAGER)
                                  self._add_strategy(new_strategy, add_to_queue)
                              
                              @external
                              def revoke_strategy(strategy: address):
                                  """
                                  @notice Revoke a strategy.
                                  @param strategy The strategy to revoke.
                                  """
                                  self._enforce_role(msg.sender, Roles.REVOKE_STRATEGY_MANAGER)
                                  self._revoke_strategy(strategy)
                              
                              @external
                              def force_revoke_strategy(strategy: address):
                                  """
                                  @notice Force revoke a strategy.
                                  @dev The vault will remove the strategy and write off any debt left 
                                      in it as a loss. This function is a dangerous function as it can force a 
                                      strategy to take a loss. All possible assets should be removed from the 
                                      strategy first via update_debt. If a strategy is removed erroneously it 
                                      can be re-added and the loss will be credited as profit. Fees will apply.
                                  @param strategy The strategy to force revoke.
                                  """
                                  self._enforce_role(msg.sender, Roles.FORCE_REVOKE_MANAGER)
                                  self._revoke_strategy(strategy, True)
                              
                              ## DEBT MANAGEMENT ##
                              @external
                              def update_max_debt_for_strategy(strategy: address, new_max_debt: uint256):
                                  """
                                  @notice Update the max debt for a strategy.
                                  @param strategy The strategy to update the max debt for.
                                  @param new_max_debt The new max debt for the strategy.
                                  """
                                  self._enforce_role(msg.sender, Roles.MAX_DEBT_MANAGER)
                                  assert self.strategies[strategy].activation != 0, "inactive strategy"
                                  self.strategies[strategy].max_debt = new_max_debt
                              
                                  log UpdatedMaxDebtForStrategy(msg.sender, strategy, new_max_debt)
                              
                              @external
                              @nonreentrant("lock")
                              def update_debt(
                                  strategy: address, 
                                  target_debt: uint256, 
                                  max_loss: uint256 = MAX_BPS
                              ) -> uint256:
                                  """
                                  @notice Update the debt for a strategy.
                                  @param strategy The strategy to update the debt for.
                                  @param target_debt The target debt for the strategy.
                                  @param max_loss Optional to check realized losses on debt decreases.
                                  @return The amount of debt added or removed.
                                  """
                                  self._enforce_role(msg.sender, Roles.DEBT_MANAGER)
                                  return self._update_debt(strategy, target_debt, max_loss)
                              
                              ## EMERGENCY MANAGEMENT ##
                              @external
                              def shutdown_vault():
                                  """
                                  @notice Shutdown the vault.
                                  """
                                  self._enforce_role(msg.sender, Roles.EMERGENCY_MANAGER)
                                  assert self.shutdown == False
                                  
                                  # Shutdown the vault.
                                  self.shutdown = True
                              
                                  # Set deposit limit to 0.
                                  if self.deposit_limit_module != empty(address):
                                      self.deposit_limit_module = empty(address)
                              
                                      log UpdateDepositLimitModule(empty(address))
                              
                                  self.deposit_limit = 0
                                  log UpdateDepositLimit(0)
                              
                                  self.roles[msg.sender] = self.roles[msg.sender] | Roles.DEBT_MANAGER
                                  log Shutdown()
                              
                              
                              ## SHARE MANAGEMENT ##
                              ## ERC20 + ERC4626 ##
                              @external
                              @nonreentrant("lock")
                              def deposit(assets: uint256, receiver: address) -> uint256:
                                  """
                                  @notice Deposit assets into the vault.
                                  @param assets The amount of assets to deposit.
                                  @param receiver The address to receive the shares.
                                  @return The amount of shares minted.
                                  """
                                  return self._deposit(msg.sender, receiver, assets)
                              
                              @external
                              @nonreentrant("lock")
                              def mint(shares: uint256, receiver: address) -> uint256:
                                  """
                                  @notice Mint shares for the receiver.
                                  @param shares The amount of shares to mint.
                                  @param receiver The address to receive the shares.
                                  @return The amount of assets deposited.
                                  """
                                  return self._mint(msg.sender, receiver, shares)
                              
                              @external
                              @nonreentrant("lock")
                              def withdraw(
                                  assets: uint256, 
                                  receiver: address, 
                                  owner: address, 
                                  max_loss: uint256 = 0,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Withdraw an amount of asset to `receiver` burning `owner`s shares.
                                  @dev The default behavior is to not allow any loss.
                                  @param assets The amount of asset to withdraw.
                                  @param receiver The address to receive the assets.
                                  @param owner The address who's shares are being burnt.
                                  @param max_loss Optional amount of acceptable loss in Basis Points.
                                  @param strategies Optional array of strategies to withdraw from.
                                  @return The amount of shares actually burnt.
                                  """
                                  shares: uint256 = self._convert_to_shares(assets, Rounding.ROUND_UP)
                                  self._redeem(msg.sender, receiver, owner, assets, shares, max_loss, strategies)
                                  return shares
                              
                              @external
                              @nonreentrant("lock")
                              def redeem(
                                  shares: uint256, 
                                  receiver: address, 
                                  owner: address, 
                                  max_loss: uint256 = MAX_BPS,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Redeems an amount of shares of `owners` shares sending funds to `receiver`.
                                  @dev The default behavior is to allow losses to be realized.
                                  @param shares The amount of shares to burn.
                                  @param receiver The address to receive the assets.
                                  @param owner The address who's shares are being burnt.
                                  @param max_loss Optional amount of acceptable loss in Basis Points.
                                  @param strategies Optional array of strategies to withdraw from.
                                  @return The amount of assets actually withdrawn.
                                  """
                                  assets: uint256 = self._convert_to_assets(shares, Rounding.ROUND_DOWN)
                                  # Always return the actual amount of assets withdrawn.
                                  return self._redeem(msg.sender, receiver, owner, assets, shares, max_loss, strategies)
                              
                              
                              @external
                              def approve(spender: address, amount: uint256) -> bool:
                                  """
                                  @notice Approve an address to spend the vault's shares.
                                  @param spender The address to approve.
                                  @param amount The amount of shares to approve.
                                  @return True if the approval was successful.
                                  """
                                  return self._approve(msg.sender, spender, amount)
                              
                              @external
                              def transfer(receiver: address, amount: uint256) -> bool:
                                  """
                                  @notice Transfer shares to a receiver.
                                  @param receiver The address to transfer shares to.
                                  @param amount The amount of shares to transfer.
                                  @return True if the transfer was successful.
                                  """
                                  assert receiver not in [self, empty(address)]
                                  self._transfer(msg.sender, receiver, amount)
                                  return True
                              
                              @external
                              def transferFrom(sender: address, receiver: address, amount: uint256) -> bool:
                                  """
                                  @notice Transfer shares from a sender to a receiver.
                                  @param sender The address to transfer shares from.
                                  @param receiver The address to transfer shares to.
                                  @param amount The amount of shares to transfer.
                                  @return True if the transfer was successful.
                                  """
                                  assert receiver not in [self, empty(address)]
                                  return self._transfer_from(sender, receiver, amount)
                              
                              ## ERC20+4626 compatibility
                              @external
                              def permit(
                                  owner: address, 
                                  spender: address, 
                                  amount: uint256, 
                                  deadline: uint256, 
                                  v: uint8, 
                                  r: bytes32, 
                                  s: bytes32
                              ) -> bool:
                                  """
                                  @notice Approve an address to spend the vault's shares.
                                  @param owner The address to approve.
                                  @param spender The address to approve.
                                  @param amount The amount of shares to approve.
                                  @param deadline The deadline for the permit.
                                  @param v The v component of the signature.
                                  @param r The r component of the signature.
                                  @param s The s component of the signature.
                                  @return True if the approval was successful.
                                  """
                                  return self._permit(owner, spender, amount, deadline, v, r, s)
                              
                              @view
                              @external
                              def balanceOf(addr: address) -> uint256:
                                  """
                                  @notice Get the balance of a user.
                                  @param addr The address to get the balance of.
                                  @return The balance of the user.
                                  """
                                  if(addr == self):
                                      # If the address is the vault, account for locked shares.
                                      return self.balance_of[addr] - self._unlocked_shares()
                              
                                  return self.balance_of[addr]
                              
                              @view
                              @external
                              def totalSupply() -> uint256:
                                  """
                                  @notice Get the total supply of shares.
                                  @return The total supply of shares.
                                  """
                                  return self._total_supply()
                              
                              @view
                              @external
                              def totalAssets() -> uint256:
                                  """
                                  @notice Get the total assets held by the vault.
                                  @return The total assets held by the vault.
                                  """
                                  return self._total_assets()
                              
                              @view
                              @external
                              def totalIdle() -> uint256:
                                  """
                                  @notice Get the amount of loose `asset` the vault holds.
                                  @return The current total idle.
                                  """
                                  return self.total_idle
                              
                              @view
                              @external
                              def totalDebt() -> uint256:
                                  """
                                  @notice Get the the total amount of funds invested
                                  across all strategies.
                                  @return The current total debt.
                                  """
                                  return self.total_debt
                              
                              @view
                              @external
                              def convertToShares(assets: uint256) -> uint256:
                                  """
                                  @notice Convert an amount of assets to shares.
                                  @param assets The amount of assets to convert.
                                  @return The amount of shares.
                                  """
                                  return self._convert_to_shares(assets, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def previewDeposit(assets: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of shares that would be minted for a deposit.
                                  @param assets The amount of assets to deposit.
                                  @return The amount of shares that would be minted.
                                  """
                                  return self._convert_to_shares(assets, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def previewMint(shares: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of assets that would be deposited for a mint.
                                  @param shares The amount of shares to mint.
                                  @return The amount of assets that would be deposited.
                                  """
                                  return self._convert_to_assets(shares, Rounding.ROUND_UP)
                              
                              @view
                              @external
                              def convertToAssets(shares: uint256) -> uint256:
                                  """
                                  @notice Convert an amount of shares to assets.
                                  @param shares The amount of shares to convert.
                                  @return The amount of assets.
                                  """
                                  return self._convert_to_assets(shares, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def maxDeposit(receiver: address) -> uint256:
                                  """
                                  @notice Get the maximum amount of assets that can be deposited.
                                  @param receiver The address that will receive the shares.
                                  @return The maximum amount of assets that can be deposited.
                                  """
                                  return self._max_deposit(receiver)
                              
                              @view
                              @external
                              def maxMint(receiver: address) -> uint256:
                                  """
                                  @notice Get the maximum amount of shares that can be minted.
                                  @param receiver The address that will receive the shares.
                                  @return The maximum amount of shares that can be minted.
                                  """
                                  max_deposit: uint256 = self._max_deposit(receiver)
                                  return self._convert_to_shares(max_deposit, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def maxWithdraw(
                                  owner: address,
                                  max_loss: uint256 = 0,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Get the maximum amount of assets that can be withdrawn.
                                  @dev Complies to normal 4626 interface and takes custom params.
                                  NOTE: Passing in a incorrectly ordered queue may result in
                                   incorrect returns values.
                                  @param owner The address that owns the shares.
                                  @param max_loss Custom max_loss if any.
                                  @param strategies Custom strategies queue if any.
                                  @return The maximum amount of assets that can be withdrawn.
                                  """
                                  return self._max_withdraw(owner, max_loss, strategies)
                              
                              @view
                              @external
                              def maxRedeem(
                                  owner: address,
                                  max_loss: uint256 = MAX_BPS,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Get the maximum amount of shares that can be redeemed.
                                  @dev Complies to normal 4626 interface and takes custom params.
                                  NOTE: Passing in a incorrectly ordered queue may result in
                                   incorrect returns values.
                                  @param owner The address that owns the shares.
                                  @param max_loss Custom max_loss if any.
                                  @param strategies Custom strategies queue if any.
                                  @return The maximum amount of shares that can be redeemed.
                                  """
                                  return min(
                                      # Min of the shares equivalent of max_withdraw or the full balance
                                      self._convert_to_shares(self._max_withdraw(owner, max_loss, strategies), Rounding.ROUND_DOWN),
                                      self.balance_of[owner]
                                  )
                              
                              @view
                              @external
                              def previewWithdraw(assets: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of shares that would be redeemed for a withdraw.
                                  @param assets The amount of assets to withdraw.
                                  @return The amount of shares that would be redeemed.
                                  """
                                  return self._convert_to_shares(assets, Rounding.ROUND_UP)
                              
                              @view
                              @external
                              def previewRedeem(shares: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of assets that would be withdrawn for a redeem.
                                  @param shares The amount of shares to redeem.
                                  @return The amount of assets that would be withdrawn.
                                  """
                                  return self._convert_to_assets(shares, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def FACTORY() -> address:
                                  """
                                  @notice Address of the factory that deployed the vault.
                                  @dev Is used to retrieve the protocol fees.
                                  @return Address of the vault factory.
                                  """
                                  return self.factory
                              
                              @view
                              @external
                              def apiVersion() -> String[28]:
                                  """
                                  @notice Get the API version of the vault.
                                  @return The API version of the vault.
                                  """
                                  return API_VERSION
                              
                              @view
                              @external
                              def assess_share_of_unrealised_losses(strategy: address, assets_needed: uint256) -> uint256:
                                  """
                                  @notice Assess the share of unrealised losses that a strategy has.
                                  @param strategy The address of the strategy.
                                  @param assets_needed The amount of assets needed to be withdrawn.
                                  @return The share of unrealised losses that the strategy has.
                                  """
                                  assert self.strategies[strategy].current_debt >= assets_needed
                              
                                  return self._assess_share_of_unrealised_losses(strategy, assets_needed)
                              
                              ## Profit locking getter functions ##
                              
                              @view
                              @external
                              def profitMaxUnlockTime() -> uint256:
                                  """
                                  @notice Gets the current time profits are set to unlock over.
                                  @return The current profit max unlock time.
                                  """
                                  return self.profit_max_unlock_time
                              
                              @view
                              @external
                              def fullProfitUnlockDate() -> uint256:
                                  """
                                  @notice Gets the timestamp at which all profits will be unlocked.
                                  @return The full profit unlocking timestamp
                                  """
                                  return self.full_profit_unlock_date
                              
                              @view
                              @external
                              def profitUnlockingRate() -> uint256:
                                  """
                                  @notice The per second rate at which profits are unlocking.
                                  @dev This is denominated in EXTENDED_BPS decimals.
                                  @return The current profit unlocking rate.
                                  """
                                  return self.profit_unlocking_rate
                              
                              
                              @view
                              @external
                              def lastProfitUpdate() -> uint256:
                                  """
                                  @notice The timestamp of the last time shares were locked.
                                  @return The last profit update.
                                  """
                                  return self.last_profit_update
                              
                              # eip-1344
                              @view
                              @internal
                              def domain_separator() -> bytes32:
                                  return keccak256(
                                      concat(
                                          DOMAIN_TYPE_HASH,
                                          keccak256(convert("Yearn Vault", Bytes[11])),
                                          keccak256(convert(API_VERSION, Bytes[28])),
                                          convert(chain.id, bytes32),
                                          convert(self, bytes32)
                                      )
                                  )
                              
                              @view
                              @external
                              def DOMAIN_SEPARATOR() -> bytes32:
                                  """
                                  @notice Get the domain separator.
                                  @return The domain separator.
                                  """
                                  return self.domain_separator()

                              File 7 of 11: DebtAllocator
                              // SPDX-License-Identifier: GNU AGPLv3
                              pragma solidity >=0.8.18 ^0.8.0;
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                              
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                              
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                              
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                              
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `to`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address to, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                              
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Moves `amount` tokens from `from` to `to` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address from, address to, uint256 amount) external returns (bool);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/utils/math/Math.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
                              
                              /**
                               * @dev Standard math utilities missing in the Solidity language.
                               */
                              library Math {
                                  enum Rounding {
                                      Down, // Toward negative infinity
                                      Up, // Toward infinity
                                      Zero // Toward zero
                                  }
                              
                                  /**
                                   * @dev Returns the largest of two numbers.
                                   */
                                  function max(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a > b ? a : b;
                                  }
                              
                                  /**
                                   * @dev Returns the smallest of two numbers.
                                   */
                                  function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a < b ? a : b;
                                  }
                              
                                  /**
                                   * @dev Returns the average of two numbers. The result is rounded towards
                                   * zero.
                                   */
                                  function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b) / 2 can overflow.
                                      return (a & b) + (a ^ b) / 2;
                                  }
                              
                                  /**
                                   * @dev Returns the ceiling of the division of two numbers.
                                   *
                                   * This differs from standard division with `/` in that it rounds up instead
                                   * of rounding down.
                                   */
                                  function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b - 1) / b can overflow on addition, so we distribute.
                                      return a == 0 ? 0 : (a - 1) / b + 1;
                                  }
                              
                                  /**
                                   * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                                   * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                                   * with further edits by Uniswap Labs also under MIT license.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                                      unchecked {
                                          // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                          // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                          // variables such that product = prod1 * 2^256 + prod0.
                                          uint256 prod0; // Least significant 256 bits of the product
                                          uint256 prod1; // Most significant 256 bits of the product
                                          assembly {
                                              let mm := mulmod(x, y, not(0))
                                              prod0 := mul(x, y)
                                              prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                          }
                              
                                          // Handle non-overflow cases, 256 by 256 division.
                                          if (prod1 == 0) {
                                              // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                                              // The surrounding unchecked block does not change this fact.
                                              // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                                              return prod0 / denominator;
                                          }
                              
                                          // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                          require(denominator > prod1, "Math: mulDiv overflow");
                              
                                          ///////////////////////////////////////////////
                                          // 512 by 256 division.
                                          ///////////////////////////////////////////////
                              
                                          // Make division exact by subtracting the remainder from [prod1 prod0].
                                          uint256 remainder;
                                          assembly {
                                              // Compute remainder using mulmod.
                                              remainder := mulmod(x, y, denominator)
                              
                                              // Subtract 256 bit number from 512 bit number.
                                              prod1 := sub(prod1, gt(remainder, prod0))
                                              prod0 := sub(prod0, remainder)
                                          }
                              
                                          // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                          // See https://cs.stackexchange.com/q/138556/92363.
                              
                                          // Does not overflow because the denominator cannot be zero at this stage in the function.
                                          uint256 twos = denominator & (~denominator + 1);
                                          assembly {
                                              // Divide denominator by twos.
                                              denominator := div(denominator, twos)
                              
                                              // Divide [prod1 prod0] by twos.
                                              prod0 := div(prod0, twos)
                              
                                              // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                              twos := add(div(sub(0, twos), twos), 1)
                                          }
                              
                                          // Shift in bits from prod1 into prod0.
                                          prod0 |= prod1 * twos;
                              
                                          // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                          // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                          // four bits. That is, denominator * inv = 1 mod 2^4.
                                          uint256 inverse = (3 * denominator) ^ 2;
                              
                                          // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                          // in modular arithmetic, doubling the correct bits in each step.
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^256
                              
                                          // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                          // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                          // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                          // is no longer required.
                                          result = prod0 * inverse;
                                          return result;
                                      }
                                  }
                              
                                  /**
                                   * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                                      uint256 result = mulDiv(x, y, denominator);
                                      if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                          result += 1;
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                                   *
                                   * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                                   */
                                  function sqrt(uint256 a) internal pure returns (uint256) {
                                      if (a == 0) {
                                          return 0;
                                      }
                              
                                      // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                      //
                                      // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                      // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                      //
                                      // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                      // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                      // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                      //
                                      // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                      uint256 result = 1 << (log2(a) >> 1);
                              
                                      // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                      // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                      // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                      // into the expected uint128 result.
                                      unchecked {
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          return min(result, a / result);
                                      }
                                  }
                              
                                  /**
                                   * @notice Calculates sqrt(a), following the selected rounding direction.
                                   */
                                  function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = sqrt(a);
                                          return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 2, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 128;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 64;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 32;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 16;
                                          }
                                          if (value >> 8 > 0) {
                                              value >>= 8;
                                              result += 8;
                                          }
                                          if (value >> 4 > 0) {
                                              value >>= 4;
                                              result += 4;
                                          }
                                          if (value >> 2 > 0) {
                                              value >>= 2;
                                              result += 2;
                                          }
                                          if (value >> 1 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log2(value);
                                          return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 10, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >= 10 ** 64) {
                                              value /= 10 ** 64;
                                              result += 64;
                                          }
                                          if (value >= 10 ** 32) {
                                              value /= 10 ** 32;
                                              result += 32;
                                          }
                                          if (value >= 10 ** 16) {
                                              value /= 10 ** 16;
                                              result += 16;
                                          }
                                          if (value >= 10 ** 8) {
                                              value /= 10 ** 8;
                                              result += 8;
                                          }
                                          if (value >= 10 ** 4) {
                                              value /= 10 ** 4;
                                              result += 4;
                                          }
                                          if (value >= 10 ** 2) {
                                              value /= 10 ** 2;
                                              result += 2;
                                          }
                                          if (value >= 10 ** 1) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log10(value);
                                          return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 256, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   *
                                   * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                                   */
                                  function log256(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 16;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 8;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 4;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 2;
                                          }
                                          if (value >> 8 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log256(value);
                                          return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                                      }
                                  }
                              }
                              
                              // lib/tokenized-strategy-periphery/src/utils/Governance.sol
                              
                              contract Governance {
                                  /// @notice Emitted when the governance address is updated.
                                  event GovernanceTransferred(
                                      address indexed previousGovernance,
                                      address indexed newGovernance
                                  );
                              
                                  modifier onlyGovernance() {
                                      _checkGovernance();
                                      _;
                                  }
                              
                                  /// @notice Checks if the msg sender is the governance.
                                  function _checkGovernance() internal view virtual {
                                      require(governance == msg.sender, "!governance");
                                  }
                              
                                  /// @notice Address that can set the default base fee and provider
                                  address public governance;
                              
                                  constructor(address _governance) {
                                      governance = _governance;
                              
                                      emit GovernanceTransferred(address(0), _governance);
                                  }
                              
                                  /**
                                   * @notice Sets a new address as the governance of the contract.
                                   * @dev Throws if the caller is not current governance.
                                   * @param _newGovernance The new governance address.
                                   */
                                  function transferGovernance(
                                      address _newGovernance
                                  ) external virtual onlyGovernance {
                                      require(_newGovernance != address(0), "ZERO ADDRESS");
                                      address oldGovernance = governance;
                                      governance = _newGovernance;
                              
                                      emit GovernanceTransferred(oldGovernance, _newGovernance);
                                  }
                              }
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
                              
                              // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                              
                              /**
                               * @dev Interface for the optional metadata functions from the ERC20 standard.
                               *
                               * _Available since v4.1._
                               */
                              interface IERC20Metadata is IERC20 {
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() external view returns (string memory);
                              
                                  /**
                                   * @dev Returns the symbol of the token.
                                   */
                                  function symbol() external view returns (string memory);
                              
                                  /**
                                   * @dev Returns the decimals places of the token.
                                   */
                                  function decimals() external view returns (uint8);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
                              
                              /**
                               * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
                               * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
                               *
                               * _Available since v4.7._
                               */
                              interface IERC4626 is IERC20, IERC20Metadata {
                                  event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
                              
                                  event Withdraw(
                                      address indexed sender,
                                      address indexed receiver,
                                      address indexed owner,
                                      uint256 assets,
                                      uint256 shares
                                  );
                              
                                  /**
                                   * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
                                   *
                                   * - MUST be an ERC-20 token contract.
                                   * - MUST NOT revert.
                                   */
                                  function asset() external view returns (address assetTokenAddress);
                              
                                  /**
                                   * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
                                   *
                                   * - SHOULD include any compounding that occurs from yield.
                                   * - MUST be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT revert.
                                   */
                                  function totalAssets() external view returns (uint256 totalManagedAssets);
                              
                                  /**
                                   * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
                                   * scenario where all the conditions are met.
                                   *
                                   * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT show any variations depending on the caller.
                                   * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
                                   * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
                                   * from.
                                   */
                                  function convertToShares(uint256 assets) external view returns (uint256 shares);
                              
                                  /**
                                   * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
                                   * scenario where all the conditions are met.
                                   *
                                   * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT show any variations depending on the caller.
                                   * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
                                   * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
                                   * from.
                                   */
                                  function convertToAssets(uint256 shares) external view returns (uint256 assets);
                              
                                  /**
                                   * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
                                   * through a deposit call.
                                   *
                                   * - MUST return a limited value if receiver is subject to some deposit limit.
                                   * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
                                   * - MUST NOT revert.
                                   */
                                  function maxDeposit(address receiver) external view returns (uint256 maxAssets);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
                                   * current on-chain conditions.
                                   *
                                   * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
                                   *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
                                   *   in the same transaction.
                                   * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
                                   *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
                                   * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by depositing.
                                   */
                                  function previewDeposit(uint256 assets) external view returns (uint256 shares);
                              
                                  /**
                                   * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
                                   *
                                   * - MUST emit the Deposit event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   deposit execution, and are accounted for during deposit.
                                   * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
                                   *   approving enough underlying tokens to the Vault contract, etc).
                                   *
                                   * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
                                   */
                                  function deposit(uint256 assets, address receiver) external returns (uint256 shares);
                              
                                  /**
                                   * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
                                   * - MUST return a limited value if receiver is subject to some mint limit.
                                   * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
                                   * - MUST NOT revert.
                                   */
                                  function maxMint(address receiver) external view returns (uint256 maxShares);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
                                   * current on-chain conditions.
                                   *
                                   * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
                                   *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
                                   *   same transaction.
                                   * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
                                   *   would be accepted, regardless if the user has enough tokens approved, etc.
                                   * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by minting.
                                   */
                                  function previewMint(uint256 shares) external view returns (uint256 assets);
                              
                                  /**
                                   * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
                                   *
                                   * - MUST emit the Deposit event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
                                   *   execution, and are accounted for during mint.
                                   * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
                                   *   approving enough underlying tokens to the Vault contract, etc).
                                   *
                                   * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
                                   */
                                  function mint(uint256 shares, address receiver) external returns (uint256 assets);
                              
                                  /**
                                   * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
                                   * Vault, through a withdraw call.
                                   *
                                   * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
                                   * - MUST NOT revert.
                                   */
                                  function maxWithdraw(address owner) external view returns (uint256 maxAssets);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
                                   * given current on-chain conditions.
                                   *
                                   * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
                                   *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
                                   *   called
                                   *   in the same transaction.
                                   * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
                                   *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
                                   * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by depositing.
                                   */
                                  function previewWithdraw(uint256 assets) external view returns (uint256 shares);
                              
                                  /**
                                   * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
                                   *
                                   * - MUST emit the Withdraw event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   withdraw execution, and are accounted for during withdraw.
                                   * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
                                   *   not having enough shares, etc).
                                   *
                                   * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
                                   * Those methods should be performed separately.
                                   */
                                  function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
                              
                                  /**
                                   * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
                                   * through a redeem call.
                                   *
                                   * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
                                   * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
                                   * - MUST NOT revert.
                                   */
                                  function maxRedeem(address owner) external view returns (uint256 maxShares);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
                                   * given current on-chain conditions.
                                   *
                                   * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
                                   *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
                                   *   same transaction.
                                   * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
                                   *   redemption would be accepted, regardless if the user has enough shares, etc.
                                   * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
                                   */
                                  function previewRedeem(uint256 shares) external view returns (uint256 assets);
                              
                                  /**
                                   * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
                                   *
                                   * - MUST emit the Withdraw event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   redeem execution, and are accounted for during redeem.
                                   * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
                                   *   not having enough shares, etc).
                                   *
                                   * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
                                   * Those methods should be performed separately.
                                   */
                                  function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
                              }
                              
                              // lib/yearn-vaults-v3/contracts/interfaces/IVault.sol
                              
                              interface IVault is IERC4626 {
                                  // STRATEGY EVENTS
                                  event StrategyChanged(address indexed strategy, uint256 change_type);
                                  event StrategyReported(
                                      address indexed strategy,
                                      uint256 gain,
                                      uint256 loss,
                                      uint256 current_debt,
                                      uint256 protocol_fees,
                                      uint256 total_fees,
                                      uint256 total_refunds
                                  );
                                  // DEBT MANAGEMENT EVENTS
                                  event DebtUpdated(
                                      address indexed strategy,
                                      uint256 current_debt,
                                      uint256 new_debt
                                  );
                                  // ROLE UPDATES
                                  event RoleSet(address indexed account, uint256 role);
                                  event UpdateRoleManager(address indexed role_manager);
                              
                                  event UpdateAccountant(address indexed accountant);
                                  event UpdateDefaultQueue(address[] new_default_queue);
                                  event UpdateUseDefaultQueue(bool use_default_queue);
                                  event UpdatedMaxDebtForStrategy(
                                      address indexed sender,
                                      address indexed strategy,
                                      uint256 new_debt
                                  );
                                  event UpdateAutoAllocate(bool auto_allocate);
                                  event UpdateDepositLimit(uint256 deposit_limit);
                                  event UpdateMinimumTotalIdle(uint256 minimum_total_idle);
                                  event UpdateProfitMaxUnlockTime(uint256 profit_max_unlock_time);
                                  event DebtPurchased(address indexed strategy, uint256 amount);
                                  event Shutdown();
                              
                                  struct StrategyParams {
                                      uint256 activation;
                                      uint256 last_report;
                                      uint256 current_debt;
                                      uint256 max_debt;
                                  }
                              
                                  function FACTORY() external view returns (uint256);
                              
                                  function strategies(address) external view returns (StrategyParams memory);
                              
                                  function default_queue(uint256) external view returns (address);
                              
                                  function use_default_queue() external view returns (bool);
                              
                                  function auto_allocate() external view returns (bool);
                              
                                  function minimum_total_idle() external view returns (uint256);
                              
                                  function deposit_limit() external view returns (uint256);
                              
                                  function deposit_limit_module() external view returns (address);
                              
                                  function withdraw_limit_module() external view returns (address);
                              
                                  function accountant() external view returns (address);
                              
                                  function roles(address) external view returns (uint256);
                              
                                  function role_manager() external view returns (address);
                              
                                  function future_role_manager() external view returns (address);
                              
                                  function isShutdown() external view returns (bool);
                              
                                  function nonces(address) external view returns (uint256);
                              
                                  function initialize(
                                      address,
                                      string memory,
                                      string memory,
                                      address,
                                      uint256
                                  ) external;
                              
                                  function setName(string memory) external;
                              
                                  function setSymbol(string memory) external;
                              
                                  function set_accountant(address new_accountant) external;
                              
                                  function set_default_queue(address[] memory new_default_queue) external;
                              
                                  function set_use_default_queue(bool) external;
                              
                                  function set_auto_allocate(bool) external;
                              
                                  function set_deposit_limit(uint256 deposit_limit) external;
                              
                                  function set_deposit_limit(
                                      uint256 deposit_limit,
                                      bool should_override
                                  ) external;
                              
                                  function set_deposit_limit_module(
                                      address new_deposit_limit_module
                                  ) external;
                              
                                  function set_deposit_limit_module(
                                      address new_deposit_limit_module,
                                      bool should_override
                                  ) external;
                              
                                  function set_withdraw_limit_module(
                                      address new_withdraw_limit_module
                                  ) external;
                              
                                  function set_minimum_total_idle(uint256 minimum_total_idle) external;
                              
                                  function setProfitMaxUnlockTime(
                                      uint256 new_profit_max_unlock_time
                                  ) external;
                              
                                  function set_role(address account, uint256 role) external;
                              
                                  function add_role(address account, uint256 role) external;
                              
                                  function remove_role(address account, uint256 role) external;
                              
                                  function transfer_role_manager(address role_manager) external;
                              
                                  function accept_role_manager() external;
                              
                                  function unlockedShares() external view returns (uint256);
                              
                                  function pricePerShare() external view returns (uint256);
                              
                                  function get_default_queue() external view returns (address[] memory);
                              
                                  function process_report(
                                      address strategy
                                  ) external returns (uint256, uint256);
                              
                                  function buy_debt(address strategy, uint256 amount) external;
                              
                                  function add_strategy(address new_strategy) external;
                              
                                  function revoke_strategy(address strategy) external;
                              
                                  function force_revoke_strategy(address strategy) external;
                              
                                  function update_max_debt_for_strategy(
                                      address strategy,
                                      uint256 new_max_debt
                                  ) external;
                              
                                  function update_debt(
                                      address strategy,
                                      uint256 target_debt
                                  ) external returns (uint256);
                              
                                  function update_debt(
                                      address strategy,
                                      uint256 target_debt,
                                      uint256 max_loss
                                  ) external returns (uint256);
                              
                                  function shutdown_vault() external;
                              
                                  function totalIdle() external view returns (uint256);
                              
                                  function totalDebt() external view returns (uint256);
                              
                                  function apiVersion() external view returns (string memory);
                              
                                  function assess_share_of_unrealised_losses(
                                      address strategy,
                                      uint256 assets_needed
                                  ) external view returns (uint256);
                              
                                  function profitMaxUnlockTime() external view returns (uint256);
                              
                                  function fullProfitUnlockDate() external view returns (uint256);
                              
                                  function profitUnlockingRate() external view returns (uint256);
                              
                                  function lastProfitUpdate() external view returns (uint256);
                              
                                  //// NON-STANDARD ERC-4626 FUNCTIONS \\\\
                              
                                  function withdraw(
                                      uint256 assets,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss
                                  ) external returns (uint256);
                              
                                  function withdraw(
                                      uint256 assets,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external returns (uint256);
                              
                                  function redeem(
                                      uint256 shares,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss
                                  ) external returns (uint256);
                              
                                  function redeem(
                                      uint256 shares,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external returns (uint256);
                              
                                  function maxWithdraw(
                                      address owner,
                                      uint256 max_loss
                                  ) external view returns (uint256);
                              
                                  function maxWithdraw(
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external view returns (uint256);
                              
                                  function maxRedeem(
                                      address owner,
                                      uint256 max_loss
                                  ) external view returns (uint256);
                              
                                  function maxRedeem(
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external view returns (uint256);
                              
                                  //// NON-STANDARD ERC-20 FUNCTIONS \\\\
                              
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                              
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 amount,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external returns (bool);
                              }
                              
                              // src/debtAllocators/DebtAllocator.sol
                              
                              interface IBaseFee {
                                  function basefee_global() external view returns (uint256);
                              }
                              
                              /**
                               * @title YearnV3  Debt Allocator
                               * @author yearn.finance
                               * @notice
                               *  This Debt Allocator is meant to be used alongside
                               *  Yearn V3 vaults to provide the needed triggers for a keeper
                               *  to perform automated debt updates for the vaults strategies.
                               *
                               * @dev
                               *  Each vault that should be managed by this allocator will
                               *  need to be added by first setting a `minimumChange` for the
                               *  vault, which will act as the minimum amount of funds to move that will
                               *  trigger a debt update. Then adding each strategy by setting a
                               *  `targetRatio` and optionally a `maxRatio`.
                               *
                               *  The allocator aims to allocate debt between the strategies
                               *  based on their set target ratios. Which are denominated in basis
                               *  points and represent the percent of total assets that specific
                               *  strategy should hold (i.e 1_000 == 10% of the vaults `totalAssets`).
                               *
                               *  The trigger will attempt to allocate up to the `maxRatio` when
                               *  the strategy has `minimumChange` amount less than the `targetRatio`.
                               *  And will pull funds to the `targetRatio` when it has `minimumChange`
                               *  more than its `maxRatio`.
                               */
                              contract DebtAllocator is Governance {
                                  /// @notice An event emitted when the base fee provider is set.
                                  event UpdatedBaseFeeProvider(address baseFeeProvider);
                              
                                  /// @notice An event emitted when a keeper is added or removed.
                                  event UpdateKeeper(address indexed keeper, bool allowed);
                              
                                  /// @notice An event emitted when the max base fee is updated.
                                  event UpdateMaxAcceptableBaseFee(uint256 newMaxAcceptableBaseFee);
                              
                                  /// @notice An event emitted when a strategies debt ratios are Updated.
                                  event UpdateStrategyDebtRatio(
                                      address indexed vault,
                                      address indexed strategy,
                                      uint256 newTargetRatio,
                                      uint256 newMaxRatio,
                                      uint256 newTotalDebtRatio
                                  );
                              
                                  /// @notice An event emitted when a strategy is added or removed.
                                  event StrategyChanged(
                                      address indexed vault,
                                      address indexed strategy,
                                      Status status
                                  );
                              
                                  /// @notice An event emitted when the minimum change is updated.
                                  event UpdateMinimumChange(address indexed vault, uint256 newMinimumChange);
                              
                                  /// @notice An even emitted when the paused status is updated.
                                  event UpdatePaused(address indexed vault, bool indexed status);
                              
                                  /// @notice An event emitted when the minimum time to wait is updated.
                                  event UpdateMinimumWait(uint256 newMinimumWait);
                              
                                  /// @notice An event emitted when a keeper is added or removed.
                                  event UpdateManager(address indexed manager, bool allowed);
                              
                                  /// @notice An event emitted when the max debt update loss is updated.
                                  event UpdateMaxDebtUpdateLoss(uint256 newMaxDebtUpdateLoss);
                              
                                  /// @notice Status when a strategy is added or removed from the allocator.
                                  enum Status {
                                      NULL,
                                      ADDED,
                                      REMOVED
                                  }
                              
                                  /// @notice Struct for each strategies info.
                                  struct StrategyConfig {
                                      // Flag to set when a strategy is added.
                                      bool added;
                                      // The ideal percent in Basis Points the strategy should have.
                                      uint16 targetRatio;
                                      // The max percent of assets the strategy should hold.
                                      uint16 maxRatio;
                                      // Timestamp of the last time debt was updated.
                                      // The debt updates must be done through this allocator
                                      // for this to be used.
                                      uint96 lastUpdate;
                                      // We have an extra 120 bits in the slot.
                                      // So we declare the variable in the struct so it can be
                                      // used if this contract is inherited.
                                      uint120 open;
                                  }
                              
                                  /// @notice Struct to hold the vault's info.
                                  struct VaultConfig {
                                      // Optional flag to stop the triggers.
                                      bool paused;
                                      // The minimum amount denominated in asset that will
                                      // need to be moved to trigger a debt update.
                                      uint128 minimumChange;
                                      // Total debt ratio currently allocated in basis points.
                                      // Can't be more than 10_000.
                                      uint16 totalDebtRatio;
                                  }
                              
                                  /// @notice Used during the `shouldUpdateDebt` to hold the data.
                                  struct StrategyDebtInfo {
                                      VaultConfig vaultConfig;
                                      StrategyConfig strategyConfig;
                                      uint256 vaultAssets;
                                      uint256 targetDebt;
                                      uint256 maxDebt;
                                      uint256 currentIdle;
                                      uint256 minIdle;
                                      uint256 toChange;
                                  }
                              
                                  /// @notice Make sure the caller is governance or a manager.
                                  modifier onlyManagers() {
                                      _isManager();
                                      _;
                                  }
                              
                                  /// @notice Make sure the caller is a keeper
                                  modifier onlyKeepers() {
                                      _isKeeper();
                                      _;
                                  }
                              
                                  /// @notice Check is either factories governance or local manager.
                                  function _isManager() internal view virtual {
                                      require(managers[msg.sender] || msg.sender == governance, "!manager");
                                  }
                              
                                  /// @notice Check is one of the allowed keepers.
                                  function _isKeeper() internal view virtual {
                                      require(keepers[msg.sender], "!keeper");
                                  }
                              
                                  uint256 internal constant MAX_BPS = 10_000;
                              
                                  /// @notice Time to wait between debt updates in seconds.
                                  uint256 public minimumWait;
                              
                                  /// @notice Provider to read current block's base fee.
                                  address public baseFeeProvider;
                              
                                  /// @notice Max loss to accept on debt updates in basis points.
                                  uint256 public maxDebtUpdateLoss;
                              
                                  /// @notice Max the chains base fee can be during debt update.
                                  // Will default to max uint256 and need to be set to be used.
                                  uint256 public maxAcceptableBaseFee;
                              
                                  /// @notice Mapping of addresses that are allowed to update debt.
                                  mapping(address => bool) public keepers;
                              
                                  /// @notice Mapping of addresses that are allowed to update debt ratios.
                                  mapping(address => bool) public managers;
                              
                                  mapping(address => VaultConfig) internal _vaultConfigs;
                              
                                  /// @notice Mapping of vault => strategy => its config.
                                  mapping(address => mapping(address => StrategyConfig))
                                      internal _strategyConfigs;
                              
                                  constructor() Governance(msg.sender) {}
                              
                                  /**
                                   * @notice Initialize the contract after being cloned.
                                   * @dev Sets default values for the global variables.
                                   */
                                  function initialize(address _governance) external {
                                      require(governance == address(0), "initialized");
                                      require(_governance != address(0), "ZERO ADDRESS");
                              
                                      governance = _governance;
                                      emit GovernanceTransferred(address(0), _governance);
                              
                                      // Default max base fee to uint max.
                                      maxAcceptableBaseFee = type(uint256).max;
                              
                                      // Default to allow 1 BP loss.
                                      maxDebtUpdateLoss = 1;
                              
                                      // Default minimum wait to 6 hours
                                      minimumWait = 60 * 60 * 6;
                              
                                      // Default to allow governance to be a keeper.
                                      keepers[_governance] = true;
                                      emit UpdateKeeper(_governance, true);
                                  }
                              
                                  /**
                                   * @notice Debt update wrapper for the vault.
                                   * @dev This contract must have the DEBT_MANAGER role assigned to them.
                                   *
                                   *   This will also uses the `maxUpdateDebtLoss` during debt
                                   *   updates to assure decreases did not realize profits outside
                                   *   of the allowed range.
                                   */
                                  function update_debt(
                                      address _vault,
                                      address _strategy,
                                      uint256 _targetDebt
                                  ) public virtual onlyKeepers {
                                      // If going to 0 record full balance first.
                                      if (_targetDebt == 0) {
                                          IVault(_vault).process_report(_strategy);
                                      }
                              
                                      // Update debt with the default max loss.
                                      IVault(_vault).update_debt(_strategy, _targetDebt, maxDebtUpdateLoss);
                              
                                      // Update the last time the strategies debt was updated.
                                      _strategyConfigs[_vault][_strategy].lastUpdate = uint96(
                                          block.timestamp
                                      );
                                  }
                              
                                  /**
                                   * @notice Check if a strategy's debt should be updated.
                                   * @dev This should be called by a keeper to decide if a strategies
                                   * debt should be updated and if so by how much.
                                   *
                                   * @param _vault Address of the vault to update.
                                   * @param _strategy Address of the strategy to check.
                                   * @return . Bool representing if the debt should be updated.
                                   * @return . Calldata if `true` or reason if `false`.
                                   */
                                  function shouldUpdateDebt(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (bool, bytes memory) {
                                      // Store all local variables in a struct to avoid stack to deep
                                      StrategyDebtInfo memory strategyDebtInfo;
                              
                                      strategyDebtInfo.vaultConfig = getVaultConfig(_vault);
                              
                                      // Don't do anything if paused.
                                      if (strategyDebtInfo.vaultConfig.paused) {
                                          return (false, bytes("Paused"));
                                      }
                              
                                      // Check the base fee isn't too high.
                                      if (!isCurrentBaseFeeAcceptable()) return (false, bytes("Base Fee"));
                              
                                      // Get the strategy specific debt config.
                                      strategyDebtInfo.strategyConfig = getStrategyConfig(_vault, _strategy);
                              
                                      // Make sure the strategy has been added to the allocator.
                                      if (!strategyDebtInfo.strategyConfig.added) {
                                          return (false, bytes("!added"));
                                      }
                              
                                      if (
                                          block.timestamp - strategyDebtInfo.strategyConfig.lastUpdate <=
                                          minimumWait
                                      ) {
                                          return (false, bytes("min wait"));
                                      }
                              
                                      // Retrieve the strategy specific parameters.
                                      IVault.StrategyParams memory params = IVault(_vault).strategies(
                                          _strategy
                                      );
                                      // Make sure its an active strategy.
                                      require(params.activation != 0, "!active");
                              
                                      strategyDebtInfo.vaultAssets = IVault(_vault).totalAssets();
                              
                                      // Get the target debt for the strategy based on vault assets.
                                      strategyDebtInfo.targetDebt = Math.min(
                                          (strategyDebtInfo.vaultAssets *
                                              strategyDebtInfo.strategyConfig.targetRatio) / MAX_BPS,
                                          // Make sure it is not more than the max allowed.
                                          params.max_debt
                                      );
                              
                                      // Get the max debt we would want the strategy to have.
                                      strategyDebtInfo.maxDebt = Math.min(
                                          (strategyDebtInfo.vaultAssets *
                                              strategyDebtInfo.strategyConfig.maxRatio) / MAX_BPS,
                                          // Make sure it is not more than the max allowed.
                                          params.max_debt
                                      );
                              
                                      // If we need to add more.
                                      if (strategyDebtInfo.targetDebt > params.current_debt) {
                                          strategyDebtInfo.currentIdle = IVault(_vault).totalIdle();
                                          strategyDebtInfo.minIdle = IVault(_vault).minimum_total_idle();
                              
                                          // We can't add more than the available idle.
                                          if (strategyDebtInfo.minIdle >= strategyDebtInfo.currentIdle) {
                                              return (false, bytes("No Idle"));
                                          }
                              
                                          // Add up to the max if possible
                                          strategyDebtInfo.toChange = Math.min(
                                              strategyDebtInfo.maxDebt - params.current_debt,
                                              // Can't take more than is available.
                                              Math.min(
                                                  strategyDebtInfo.currentIdle - strategyDebtInfo.minIdle,
                                                  IVault(_strategy).maxDeposit(_vault)
                                              )
                                          );
                              
                                          // If the amount to add is over our threshold.
                                          if (
                                              strategyDebtInfo.toChange >
                                              strategyDebtInfo.vaultConfig.minimumChange
                                          ) {
                                              // Return true and the calldata.
                                              return (
                                                  true,
                                                  abi.encodeCall(
                                                      this.update_debt,
                                                      (
                                                          _vault,
                                                          _strategy,
                                                          params.current_debt + strategyDebtInfo.toChange
                                                      )
                                                  )
                                              );
                                          }
                                          // If current debt is greater than our max.
                                      } else if (strategyDebtInfo.maxDebt < params.current_debt) {
                                          strategyDebtInfo.toChange =
                                              params.current_debt -
                                              strategyDebtInfo.targetDebt;
                              
                                          strategyDebtInfo.currentIdle = IVault(_vault).totalIdle();
                                          strategyDebtInfo.minIdle = IVault(_vault).minimum_total_idle();
                              
                                          if (strategyDebtInfo.minIdle > strategyDebtInfo.currentIdle) {
                                              // Pull at least the amount needed for minIdle.
                                              strategyDebtInfo.toChange = Math.max(
                                                  strategyDebtInfo.toChange,
                                                  strategyDebtInfo.minIdle - strategyDebtInfo.currentIdle
                                              );
                                          }
                              
                                          // Find out by how much. Aim for the target.
                                          strategyDebtInfo.toChange = Math.min(
                                              strategyDebtInfo.toChange,
                                              // Account for the current liquidity constraints.
                                              // Use max redeem to match vault logic.
                                              IVault(_strategy).convertToAssets(
                                                  IVault(_strategy).maxRedeem(_vault)
                                              )
                                          );
                              
                                          // Check if it's over the threshold.
                                          if (
                                              strategyDebtInfo.toChange >
                                              strategyDebtInfo.vaultConfig.minimumChange
                                          ) {
                                              // Can't lower debt if there are unrealised losses.
                                              if (
                                                  IVault(_vault).assess_share_of_unrealised_losses(
                                                      _strategy,
                                                      params.current_debt
                                                  ) != 0
                                              ) {
                                                  return (false, bytes("unrealised loss"));
                                              }
                              
                                              // If so return true and the calldata.
                                              return (
                                                  true,
                                                  abi.encodeCall(
                                                      this.update_debt,
                                                      (
                                                          _vault,
                                                          _strategy,
                                                          params.current_debt - strategyDebtInfo.toChange
                                                      )
                                                  )
                                              );
                                          }
                                      }
                              
                                      // Either no change or below our minimumChange.
                                      return (false, bytes("Below Min"));
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      STRATEGY MANAGEMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Increase a strategies target debt ratio.
                                   * @dev `setStrategyDebtRatio` functions will do all needed checks.
                                   * @param _strategy The address of the strategy to increase the debt ratio for.
                                   * @param _increase The amount in Basis Points to increase it.
                                   */
                                  function increaseStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _increase
                                  ) external virtual {
                                      setStrategyDebtRatio(
                                          _vault,
                                          _strategy,
                                          getStrategyTargetRatio(_vault, _strategy) + _increase
                                      );
                                  }
                              
                                  /**
                                   * @notice Decrease a strategies target debt ratio.
                                   * @param _strategy The address of the strategy to decrease the debt ratio for.
                                   * @param _decrease The amount in Basis Points to decrease it.
                                   */
                                  function decreaseStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _decrease
                                  ) external virtual {
                                      setStrategyDebtRatio(
                                          _vault,
                                          _strategy,
                                          getStrategyTargetRatio(_vault, _strategy) - _decrease
                                      );
                                  }
                              
                                  /**
                                   * @notice Sets a new target debt ratio for a strategy.
                                   * @dev This will default to a 20% increase for max debt.
                                   *
                                   * @param _strategy Address of the strategy to set.
                                   * @param _targetRatio Amount in Basis points to allocate.
                                   */
                                  function setStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _targetRatio
                                  ) public virtual {
                                      uint256 maxRatio = Math.min((_targetRatio * 12_000) / MAX_BPS, MAX_BPS);
                                      setStrategyDebtRatio(_vault, _strategy, _targetRatio, maxRatio);
                                  }
                              
                                  /**
                                   * @notice Sets a new target debt ratio for a strategy.
                                   * @dev A `minimumChange` for that strategy must be set first.
                                   * This is to prevent debt from being updated too frequently.
                                   *
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy to set.
                                   * @param _targetRatio Amount in Basis points to allocate.
                                   * @param _maxRatio Max ratio to give on debt increases.
                                   */
                                  function setStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _targetRatio,
                                      uint256 _maxRatio
                                  ) public virtual onlyManagers {
                                      VaultConfig memory vaultConfig = getVaultConfig(_vault);
                                      // Make sure a minimumChange has been set.
                                      require(vaultConfig.minimumChange != 0, "!minimum");
                                      // Cannot be more than 100%.
                                      require(_maxRatio <= MAX_BPS, "max too high");
                                      // Max cannot be lower than the target.
                                      require(_maxRatio >= _targetRatio, "max ratio");
                              
                                      // Get the current config.
                                      StrategyConfig memory strategyConfig = getStrategyConfig(
                                          _vault,
                                          _strategy
                                      );
                              
                                      // Set added flag if not set yet.
                                      if (!strategyConfig.added) {
                                          strategyConfig.added = true;
                                          emit StrategyChanged(_vault, _strategy, Status.ADDED);
                                      }
                              
                                      // Get what will be the new total debt ratio.
                                      uint256 newTotalDebtRatio = vaultConfig.totalDebtRatio -
                                          strategyConfig.targetRatio +
                                          _targetRatio;
                              
                                      // Make sure it is under 100% allocated
                                      require(newTotalDebtRatio <= MAX_BPS, "ratio too high");
                              
                                      // Update local config.
                                      strategyConfig.targetRatio = uint16(_targetRatio);
                                      strategyConfig.maxRatio = uint16(_maxRatio);
                              
                                      // Write to storage.
                                      _strategyConfigs[_vault][_strategy] = strategyConfig;
                                      _vaultConfigs[_vault].totalDebtRatio = uint16(newTotalDebtRatio);
                              
                                      emit UpdateStrategyDebtRatio(
                                          _vault,
                                          _strategy,
                                          _targetRatio,
                                          _maxRatio,
                                          newTotalDebtRatio
                                      );
                                  }
                              
                                  /**
                                   * @notice Remove a strategy from this debt allocator.
                                   * @dev Will delete the full config for the strategy
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the address ro remove.
                                   */
                                  function removeStrategy(
                                      address _vault,
                                      address _strategy
                                  ) external virtual onlyManagers {
                                      StrategyConfig memory strategyConfig = getStrategyConfig(
                                          _vault,
                                          _strategy
                                      );
                                      require(strategyConfig.added, "!added");
                              
                                      uint256 target = strategyConfig.targetRatio;
                              
                                      // Remove any debt ratio the strategy holds.
                                      if (target != 0) {
                                          uint256 newRatio = _vaultConfigs[_vault].totalDebtRatio - target;
                                          _vaultConfigs[_vault].totalDebtRatio = uint16(newRatio);
                                          emit UpdateStrategyDebtRatio(_vault, _strategy, 0, 0, newRatio);
                                      }
                              
                                      // Remove the full config including the `added` flag.
                                      delete _strategyConfigs[_vault][_strategy];
                              
                                      // Emit Event.
                                      emit StrategyChanged(_vault, _strategy, Status.REMOVED);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      VAULT MANAGEMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Set the minimum change variable for a strategy.
                                   * @dev This is the minimum amount of debt to be
                                   * added or pulled for it to trigger an update.
                                   *
                                   * @param _vault Address of the vault
                                   * @param _minimumChange The new minimum to set for the strategy.
                                   */
                                  function setMinimumChange(
                                      address _vault,
                                      uint256 _minimumChange
                                  ) external virtual onlyGovernance {
                                      require(_minimumChange > 0, "zero change");
                                      // Make sure it fits in the slot size.
                                      require(_minimumChange < type(uint128).max, "too high");
                              
                                      // Set the new minimum.
                                      _vaultConfigs[_vault].minimumChange = uint128(_minimumChange);
                              
                                      emit UpdateMinimumChange(_vault, _minimumChange);
                                  }
                              
                                  /**
                                   * @notice Allows governance to pause the triggers.
                                   * @param _vault Address of the vault
                                   * @param _status Status to set the `paused` bool to.
                                   */
                                  function setPaused(
                                      address _vault,
                                      bool _status
                                  ) external virtual onlyGovernance {
                                      require(_status != _vaultConfigs[_vault].paused, "already set");
                                      _vaultConfigs[_vault].paused = _status;
                              
                                      emit UpdatePaused(_vault, _status);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      ALLOCATOR MANAGEMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Set the minimum time to wait before re-updating a strategies debt.
                                   * @dev This is only enforced per strategy.
                                   * @param _minimumWait The minimum time in seconds to wait.
                                   */
                                  function setMinimumWait(
                                      uint256 _minimumWait
                                  ) external virtual onlyGovernance {
                                      minimumWait = _minimumWait;
                              
                                      emit UpdateMinimumWait(_minimumWait);
                                  }
                              
                                  /**
                                   * @notice Set if a manager can update ratios.
                                   * @param _address The address to set mapping for.
                                   * @param _allowed If the address can call {update_debt}.
                                   */
                                  function setManager(
                                      address _address,
                                      bool _allowed
                                  ) external virtual onlyGovernance {
                                      managers[_address] = _allowed;
                              
                                      emit UpdateManager(_address, _allowed);
                                  }
                              
                                  /**
                                   * @notice Set the max loss in Basis points to allow on debt updates.
                                   * @dev Withdrawing during debt updates use {redeem} which allows for 100% loss.
                                   *      This can be used to assure a loss is not realized on redeem outside the tolerance.
                                   * @param _maxDebtUpdateLoss The max loss to accept on debt updates.
                                   */
                                  function setMaxDebtUpdateLoss(
                                      uint256 _maxDebtUpdateLoss
                                  ) external virtual onlyGovernance {
                                      require(_maxDebtUpdateLoss <= MAX_BPS, "higher than max");
                                      maxDebtUpdateLoss = _maxDebtUpdateLoss;
                              
                                      emit UpdateMaxDebtUpdateLoss(_maxDebtUpdateLoss);
                                  }
                              
                                  /**
                                   * @notice
                                   *  Used to set our baseFeeProvider, which checks the network's current base
                                   *  fee price to determine whether it is an optimal time to harvest or tend.
                                   *
                                   *  This may only be called by governance.
                                   * @param _baseFeeProvider Address of our baseFeeProvider
                                   */
                                  function setBaseFeeProvider(
                                      address _baseFeeProvider
                                  ) external virtual onlyGovernance {
                                      baseFeeProvider = _baseFeeProvider;
                              
                                      emit UpdatedBaseFeeProvider(_baseFeeProvider);
                                  }
                              
                                  /**
                                   * @notice Set the max acceptable base fee.
                                   * @dev This defaults to max uint256 and will need to
                                   * be set for it to be used.
                                   *
                                   * Is denominated in gwei. So 50gwei would be set as 50e9.
                                   *
                                   * @param _maxAcceptableBaseFee The new max base fee.
                                   */
                                  function setMaxAcceptableBaseFee(
                                      uint256 _maxAcceptableBaseFee
                                  ) external virtual onlyGovernance {
                                      maxAcceptableBaseFee = _maxAcceptableBaseFee;
                              
                                      emit UpdateMaxAcceptableBaseFee(_maxAcceptableBaseFee);
                                  }
                              
                                  /**
                                   * @notice Set if a keeper can update debt.
                                   * @param _address The address to set mapping for.
                                   * @param _allowed If the address can call {update_debt}.
                                   */
                                  function setKeeper(
                                      address _address,
                                      bool _allowed
                                  ) external virtual onlyGovernance {
                                      keepers[_address] = _allowed;
                              
                                      emit UpdateKeeper(_address, _allowed);
                                  }
                              
                                  /**
                                   * @notice Get a strategies full config.
                                   * @dev Used for customizations by inheriting the contract.
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy.
                                   * @return The strategies current Config.
                                   */
                                  function getStrategyConfig(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (StrategyConfig memory) {
                                      return _strategyConfigs[_vault][_strategy];
                                  }
                              
                                  /**
                                   * @notice Get a vaults full config.
                                   * @dev Used for customizations by inheriting the contract.
                                   * @param _vault Address of the vault.
                                   * @return The vaults current Config.
                                   */
                                  function getVaultConfig(
                                      address _vault
                                  ) public view virtual returns (VaultConfig memory) {
                                      return _vaultConfigs[_vault];
                                  }
                              
                                  /**
                                   * @notice Get a vaults current total debt.
                                   * @param _vault Address of the vault
                                   */
                                  function totalDebtRatio(
                                      address _vault
                                  ) external view virtual returns (uint256) {
                                      return getVaultConfig(_vault).totalDebtRatio;
                                  }
                              
                                  /**
                                   * @notice Get a vaults minimum change required.
                                   * @param _vault Address of the vault
                                   */
                                  function minimumChange(
                                      address _vault
                                  ) external view virtual returns (uint256) {
                                      return getVaultConfig(_vault).minimumChange;
                                  }
                              
                                  /**
                                   * @notice Get the paused status of a vault
                                   * @param _vault Address of the vault
                                   */
                                  function isPaused(address _vault) public view virtual returns (bool) {
                                      return getVaultConfig(_vault).paused;
                                  }
                              
                                  /**
                                   * @notice Get a strategies target debt ratio.
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy.
                                   * @return The strategies current targetRatio.
                                   */
                                  function getStrategyTargetRatio(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (uint256) {
                                      return getStrategyConfig(_vault, _strategy).targetRatio;
                                  }
                              
                                  /**
                                   * @notice Get a strategies max debt ratio.
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy.
                                   * @return The strategies current maxRatio.
                                   */
                                  function getStrategyMaxRatio(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (uint256) {
                                      return getStrategyConfig(_vault, _strategy).maxRatio;
                                  }
                              
                                  /**
                                   * @notice Returns wether or not the current base fee is acceptable
                                   *   based on the `maxAcceptableBaseFee`.
                                   * @return . If the current base fee is acceptable.
                                   */
                                  function isCurrentBaseFeeAcceptable() public view virtual returns (bool) {
                                      address _baseFeeProvider = baseFeeProvider;
                                      if (_baseFeeProvider == address(0)) return true;
                                      return
                                          maxAcceptableBaseFee >= IBaseFee(_baseFeeProvider).basefee_global();
                                  }
                              }

                              File 8 of 11: DebtAllocator
                              // SPDX-License-Identifier: GNU AGPLv3
                              pragma solidity >=0.8.18 ^0.8.0;
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                              
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                              
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                              
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                              
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `to`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address to, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                              
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Moves `amount` tokens from `from` to `to` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address from, address to, uint256 amount) external returns (bool);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/utils/math/Math.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
                              
                              /**
                               * @dev Standard math utilities missing in the Solidity language.
                               */
                              library Math {
                                  enum Rounding {
                                      Down, // Toward negative infinity
                                      Up, // Toward infinity
                                      Zero // Toward zero
                                  }
                              
                                  /**
                                   * @dev Returns the largest of two numbers.
                                   */
                                  function max(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a > b ? a : b;
                                  }
                              
                                  /**
                                   * @dev Returns the smallest of two numbers.
                                   */
                                  function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a < b ? a : b;
                                  }
                              
                                  /**
                                   * @dev Returns the average of two numbers. The result is rounded towards
                                   * zero.
                                   */
                                  function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b) / 2 can overflow.
                                      return (a & b) + (a ^ b) / 2;
                                  }
                              
                                  /**
                                   * @dev Returns the ceiling of the division of two numbers.
                                   *
                                   * This differs from standard division with `/` in that it rounds up instead
                                   * of rounding down.
                                   */
                                  function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b - 1) / b can overflow on addition, so we distribute.
                                      return a == 0 ? 0 : (a - 1) / b + 1;
                                  }
                              
                                  /**
                                   * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                                   * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                                   * with further edits by Uniswap Labs also under MIT license.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                                      unchecked {
                                          // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                          // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                          // variables such that product = prod1 * 2^256 + prod0.
                                          uint256 prod0; // Least significant 256 bits of the product
                                          uint256 prod1; // Most significant 256 bits of the product
                                          assembly {
                                              let mm := mulmod(x, y, not(0))
                                              prod0 := mul(x, y)
                                              prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                          }
                              
                                          // Handle non-overflow cases, 256 by 256 division.
                                          if (prod1 == 0) {
                                              // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                                              // The surrounding unchecked block does not change this fact.
                                              // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                                              return prod0 / denominator;
                                          }
                              
                                          // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                          require(denominator > prod1, "Math: mulDiv overflow");
                              
                                          ///////////////////////////////////////////////
                                          // 512 by 256 division.
                                          ///////////////////////////////////////////////
                              
                                          // Make division exact by subtracting the remainder from [prod1 prod0].
                                          uint256 remainder;
                                          assembly {
                                              // Compute remainder using mulmod.
                                              remainder := mulmod(x, y, denominator)
                              
                                              // Subtract 256 bit number from 512 bit number.
                                              prod1 := sub(prod1, gt(remainder, prod0))
                                              prod0 := sub(prod0, remainder)
                                          }
                              
                                          // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                          // See https://cs.stackexchange.com/q/138556/92363.
                              
                                          // Does not overflow because the denominator cannot be zero at this stage in the function.
                                          uint256 twos = denominator & (~denominator + 1);
                                          assembly {
                                              // Divide denominator by twos.
                                              denominator := div(denominator, twos)
                              
                                              // Divide [prod1 prod0] by twos.
                                              prod0 := div(prod0, twos)
                              
                                              // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                              twos := add(div(sub(0, twos), twos), 1)
                                          }
                              
                                          // Shift in bits from prod1 into prod0.
                                          prod0 |= prod1 * twos;
                              
                                          // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                          // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                          // four bits. That is, denominator * inv = 1 mod 2^4.
                                          uint256 inverse = (3 * denominator) ^ 2;
                              
                                          // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                          // in modular arithmetic, doubling the correct bits in each step.
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^256
                              
                                          // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                          // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                          // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                          // is no longer required.
                                          result = prod0 * inverse;
                                          return result;
                                      }
                                  }
                              
                                  /**
                                   * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                                      uint256 result = mulDiv(x, y, denominator);
                                      if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                          result += 1;
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                                   *
                                   * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                                   */
                                  function sqrt(uint256 a) internal pure returns (uint256) {
                                      if (a == 0) {
                                          return 0;
                                      }
                              
                                      // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                      //
                                      // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                      // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                      //
                                      // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                      // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                      // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                      //
                                      // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                      uint256 result = 1 << (log2(a) >> 1);
                              
                                      // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                      // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                      // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                      // into the expected uint128 result.
                                      unchecked {
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          return min(result, a / result);
                                      }
                                  }
                              
                                  /**
                                   * @notice Calculates sqrt(a), following the selected rounding direction.
                                   */
                                  function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = sqrt(a);
                                          return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 2, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 128;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 64;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 32;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 16;
                                          }
                                          if (value >> 8 > 0) {
                                              value >>= 8;
                                              result += 8;
                                          }
                                          if (value >> 4 > 0) {
                                              value >>= 4;
                                              result += 4;
                                          }
                                          if (value >> 2 > 0) {
                                              value >>= 2;
                                              result += 2;
                                          }
                                          if (value >> 1 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log2(value);
                                          return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 10, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >= 10 ** 64) {
                                              value /= 10 ** 64;
                                              result += 64;
                                          }
                                          if (value >= 10 ** 32) {
                                              value /= 10 ** 32;
                                              result += 32;
                                          }
                                          if (value >= 10 ** 16) {
                                              value /= 10 ** 16;
                                              result += 16;
                                          }
                                          if (value >= 10 ** 8) {
                                              value /= 10 ** 8;
                                              result += 8;
                                          }
                                          if (value >= 10 ** 4) {
                                              value /= 10 ** 4;
                                              result += 4;
                                          }
                                          if (value >= 10 ** 2) {
                                              value /= 10 ** 2;
                                              result += 2;
                                          }
                                          if (value >= 10 ** 1) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log10(value);
                                          return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 256, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   *
                                   * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                                   */
                                  function log256(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 16;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 8;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 4;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 2;
                                          }
                                          if (value >> 8 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log256(value);
                                          return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                                      }
                                  }
                              }
                              
                              // lib/tokenized-strategy-periphery/src/utils/Governance.sol
                              
                              contract Governance {
                                  /// @notice Emitted when the governance address is updated.
                                  event GovernanceTransferred(
                                      address indexed previousGovernance,
                                      address indexed newGovernance
                                  );
                              
                                  modifier onlyGovernance() {
                                      _checkGovernance();
                                      _;
                                  }
                              
                                  /// @notice Checks if the msg sender is the governance.
                                  function _checkGovernance() internal view virtual {
                                      require(governance == msg.sender, "!governance");
                                  }
                              
                                  /// @notice Address that can set the default base fee and provider
                                  address public governance;
                              
                                  constructor(address _governance) {
                                      governance = _governance;
                              
                                      emit GovernanceTransferred(address(0), _governance);
                                  }
                              
                                  /**
                                   * @notice Sets a new address as the governance of the contract.
                                   * @dev Throws if the caller is not current governance.
                                   * @param _newGovernance The new governance address.
                                   */
                                  function transferGovernance(
                                      address _newGovernance
                                  ) external virtual onlyGovernance {
                                      require(_newGovernance != address(0), "ZERO ADDRESS");
                                      address oldGovernance = governance;
                                      governance = _newGovernance;
                              
                                      emit GovernanceTransferred(oldGovernance, _newGovernance);
                                  }
                              }
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
                              
                              // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                              
                              /**
                               * @dev Interface for the optional metadata functions from the ERC20 standard.
                               *
                               * _Available since v4.1._
                               */
                              interface IERC20Metadata is IERC20 {
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() external view returns (string memory);
                              
                                  /**
                                   * @dev Returns the symbol of the token.
                                   */
                                  function symbol() external view returns (string memory);
                              
                                  /**
                                   * @dev Returns the decimals places of the token.
                                   */
                                  function decimals() external view returns (uint8);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)
                              
                              /**
                               * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
                               * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
                               *
                               * _Available since v4.7._
                               */
                              interface IERC4626 is IERC20, IERC20Metadata {
                                  event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
                              
                                  event Withdraw(
                                      address indexed sender,
                                      address indexed receiver,
                                      address indexed owner,
                                      uint256 assets,
                                      uint256 shares
                                  );
                              
                                  /**
                                   * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
                                   *
                                   * - MUST be an ERC-20 token contract.
                                   * - MUST NOT revert.
                                   */
                                  function asset() external view returns (address assetTokenAddress);
                              
                                  /**
                                   * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
                                   *
                                   * - SHOULD include any compounding that occurs from yield.
                                   * - MUST be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT revert.
                                   */
                                  function totalAssets() external view returns (uint256 totalManagedAssets);
                              
                                  /**
                                   * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
                                   * scenario where all the conditions are met.
                                   *
                                   * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT show any variations depending on the caller.
                                   * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
                                   * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
                                   * from.
                                   */
                                  function convertToShares(uint256 assets) external view returns (uint256 shares);
                              
                                  /**
                                   * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
                                   * scenario where all the conditions are met.
                                   *
                                   * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
                                   * - MUST NOT show any variations depending on the caller.
                                   * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
                                   * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
                                   * from.
                                   */
                                  function convertToAssets(uint256 shares) external view returns (uint256 assets);
                              
                                  /**
                                   * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
                                   * through a deposit call.
                                   *
                                   * - MUST return a limited value if receiver is subject to some deposit limit.
                                   * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
                                   * - MUST NOT revert.
                                   */
                                  function maxDeposit(address receiver) external view returns (uint256 maxAssets);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
                                   * current on-chain conditions.
                                   *
                                   * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
                                   *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
                                   *   in the same transaction.
                                   * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
                                   *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
                                   * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by depositing.
                                   */
                                  function previewDeposit(uint256 assets) external view returns (uint256 shares);
                              
                                  /**
                                   * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
                                   *
                                   * - MUST emit the Deposit event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   deposit execution, and are accounted for during deposit.
                                   * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
                                   *   approving enough underlying tokens to the Vault contract, etc).
                                   *
                                   * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
                                   */
                                  function deposit(uint256 assets, address receiver) external returns (uint256 shares);
                              
                                  /**
                                   * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
                                   * - MUST return a limited value if receiver is subject to some mint limit.
                                   * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
                                   * - MUST NOT revert.
                                   */
                                  function maxMint(address receiver) external view returns (uint256 maxShares);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
                                   * current on-chain conditions.
                                   *
                                   * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
                                   *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
                                   *   same transaction.
                                   * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
                                   *   would be accepted, regardless if the user has enough tokens approved, etc.
                                   * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by minting.
                                   */
                                  function previewMint(uint256 shares) external view returns (uint256 assets);
                              
                                  /**
                                   * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
                                   *
                                   * - MUST emit the Deposit event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
                                   *   execution, and are accounted for during mint.
                                   * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
                                   *   approving enough underlying tokens to the Vault contract, etc).
                                   *
                                   * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
                                   */
                                  function mint(uint256 shares, address receiver) external returns (uint256 assets);
                              
                                  /**
                                   * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
                                   * Vault, through a withdraw call.
                                   *
                                   * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
                                   * - MUST NOT revert.
                                   */
                                  function maxWithdraw(address owner) external view returns (uint256 maxAssets);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
                                   * given current on-chain conditions.
                                   *
                                   * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
                                   *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
                                   *   called
                                   *   in the same transaction.
                                   * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
                                   *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
                                   * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by depositing.
                                   */
                                  function previewWithdraw(uint256 assets) external view returns (uint256 shares);
                              
                                  /**
                                   * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
                                   *
                                   * - MUST emit the Withdraw event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   withdraw execution, and are accounted for during withdraw.
                                   * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
                                   *   not having enough shares, etc).
                                   *
                                   * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
                                   * Those methods should be performed separately.
                                   */
                                  function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
                              
                                  /**
                                   * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
                                   * through a redeem call.
                                   *
                                   * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
                                   * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
                                   * - MUST NOT revert.
                                   */
                                  function maxRedeem(address owner) external view returns (uint256 maxShares);
                              
                                  /**
                                   * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
                                   * given current on-chain conditions.
                                   *
                                   * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
                                   *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
                                   *   same transaction.
                                   * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
                                   *   redemption would be accepted, regardless if the user has enough shares, etc.
                                   * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
                                   * - MUST NOT revert.
                                   *
                                   * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
                                   * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
                                   */
                                  function previewRedeem(uint256 shares) external view returns (uint256 assets);
                              
                                  /**
                                   * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
                                   *
                                   * - MUST emit the Withdraw event.
                                   * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
                                   *   redeem execution, and are accounted for during redeem.
                                   * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
                                   *   not having enough shares, etc).
                                   *
                                   * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
                                   * Those methods should be performed separately.
                                   */
                                  function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
                              }
                              
                              // lib/yearn-vaults-v3/contracts/interfaces/IVault.sol
                              
                              interface IVault is IERC4626 {
                                  // STRATEGY EVENTS
                                  event StrategyChanged(address indexed strategy, uint256 change_type);
                                  event StrategyReported(
                                      address indexed strategy,
                                      uint256 gain,
                                      uint256 loss,
                                      uint256 current_debt,
                                      uint256 protocol_fees,
                                      uint256 total_fees,
                                      uint256 total_refunds
                                  );
                                  // DEBT MANAGEMENT EVENTS
                                  event DebtUpdated(
                                      address indexed strategy,
                                      uint256 current_debt,
                                      uint256 new_debt
                                  );
                                  // ROLE UPDATES
                                  event RoleSet(address indexed account, uint256 role);
                                  event UpdateRoleManager(address indexed role_manager);
                              
                                  event UpdateAccountant(address indexed accountant);
                                  event UpdateDefaultQueue(address[] new_default_queue);
                                  event UpdateUseDefaultQueue(bool use_default_queue);
                                  event UpdatedMaxDebtForStrategy(
                                      address indexed sender,
                                      address indexed strategy,
                                      uint256 new_debt
                                  );
                                  event UpdateAutoAllocate(bool auto_allocate);
                                  event UpdateDepositLimit(uint256 deposit_limit);
                                  event UpdateMinimumTotalIdle(uint256 minimum_total_idle);
                                  event UpdateProfitMaxUnlockTime(uint256 profit_max_unlock_time);
                                  event DebtPurchased(address indexed strategy, uint256 amount);
                                  event Shutdown();
                              
                                  struct StrategyParams {
                                      uint256 activation;
                                      uint256 last_report;
                                      uint256 current_debt;
                                      uint256 max_debt;
                                  }
                              
                                  function FACTORY() external view returns (uint256);
                              
                                  function strategies(address) external view returns (StrategyParams memory);
                              
                                  function default_queue(uint256) external view returns (address);
                              
                                  function use_default_queue() external view returns (bool);
                              
                                  function auto_allocate() external view returns (bool);
                              
                                  function minimum_total_idle() external view returns (uint256);
                              
                                  function deposit_limit() external view returns (uint256);
                              
                                  function deposit_limit_module() external view returns (address);
                              
                                  function withdraw_limit_module() external view returns (address);
                              
                                  function accountant() external view returns (address);
                              
                                  function roles(address) external view returns (uint256);
                              
                                  function role_manager() external view returns (address);
                              
                                  function future_role_manager() external view returns (address);
                              
                                  function isShutdown() external view returns (bool);
                              
                                  function nonces(address) external view returns (uint256);
                              
                                  function initialize(
                                      address,
                                      string memory,
                                      string memory,
                                      address,
                                      uint256
                                  ) external;
                              
                                  function setName(string memory) external;
                              
                                  function setSymbol(string memory) external;
                              
                                  function set_accountant(address new_accountant) external;
                              
                                  function set_default_queue(address[] memory new_default_queue) external;
                              
                                  function set_use_default_queue(bool) external;
                              
                                  function set_auto_allocate(bool) external;
                              
                                  function set_deposit_limit(uint256 deposit_limit) external;
                              
                                  function set_deposit_limit(
                                      uint256 deposit_limit,
                                      bool should_override
                                  ) external;
                              
                                  function set_deposit_limit_module(
                                      address new_deposit_limit_module
                                  ) external;
                              
                                  function set_deposit_limit_module(
                                      address new_deposit_limit_module,
                                      bool should_override
                                  ) external;
                              
                                  function set_withdraw_limit_module(
                                      address new_withdraw_limit_module
                                  ) external;
                              
                                  function set_minimum_total_idle(uint256 minimum_total_idle) external;
                              
                                  function setProfitMaxUnlockTime(
                                      uint256 new_profit_max_unlock_time
                                  ) external;
                              
                                  function set_role(address account, uint256 role) external;
                              
                                  function add_role(address account, uint256 role) external;
                              
                                  function remove_role(address account, uint256 role) external;
                              
                                  function transfer_role_manager(address role_manager) external;
                              
                                  function accept_role_manager() external;
                              
                                  function unlockedShares() external view returns (uint256);
                              
                                  function pricePerShare() external view returns (uint256);
                              
                                  function get_default_queue() external view returns (address[] memory);
                              
                                  function process_report(
                                      address strategy
                                  ) external returns (uint256, uint256);
                              
                                  function buy_debt(address strategy, uint256 amount) external;
                              
                                  function add_strategy(address new_strategy) external;
                              
                                  function revoke_strategy(address strategy) external;
                              
                                  function force_revoke_strategy(address strategy) external;
                              
                                  function update_max_debt_for_strategy(
                                      address strategy,
                                      uint256 new_max_debt
                                  ) external;
                              
                                  function update_debt(
                                      address strategy,
                                      uint256 target_debt
                                  ) external returns (uint256);
                              
                                  function update_debt(
                                      address strategy,
                                      uint256 target_debt,
                                      uint256 max_loss
                                  ) external returns (uint256);
                              
                                  function shutdown_vault() external;
                              
                                  function totalIdle() external view returns (uint256);
                              
                                  function totalDebt() external view returns (uint256);
                              
                                  function apiVersion() external view returns (string memory);
                              
                                  function assess_share_of_unrealised_losses(
                                      address strategy,
                                      uint256 assets_needed
                                  ) external view returns (uint256);
                              
                                  function profitMaxUnlockTime() external view returns (uint256);
                              
                                  function fullProfitUnlockDate() external view returns (uint256);
                              
                                  function profitUnlockingRate() external view returns (uint256);
                              
                                  function lastProfitUpdate() external view returns (uint256);
                              
                                  //// NON-STANDARD ERC-4626 FUNCTIONS \\\\
                              
                                  function withdraw(
                                      uint256 assets,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss
                                  ) external returns (uint256);
                              
                                  function withdraw(
                                      uint256 assets,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external returns (uint256);
                              
                                  function redeem(
                                      uint256 shares,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss
                                  ) external returns (uint256);
                              
                                  function redeem(
                                      uint256 shares,
                                      address receiver,
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external returns (uint256);
                              
                                  function maxWithdraw(
                                      address owner,
                                      uint256 max_loss
                                  ) external view returns (uint256);
                              
                                  function maxWithdraw(
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external view returns (uint256);
                              
                                  function maxRedeem(
                                      address owner,
                                      uint256 max_loss
                                  ) external view returns (uint256);
                              
                                  function maxRedeem(
                                      address owner,
                                      uint256 max_loss,
                                      address[] memory strategies
                                  ) external view returns (uint256);
                              
                                  //// NON-STANDARD ERC-20 FUNCTIONS \\\\
                              
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                              
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 amount,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external returns (bool);
                              }
                              
                              // src/debtAllocators/DebtAllocator.sol
                              
                              interface IBaseFee {
                                  function basefee_global() external view returns (uint256);
                              }
                              
                              /**
                               * @title YearnV3  Debt Allocator
                               * @author yearn.finance
                               * @notice
                               *  This Debt Allocator is meant to be used alongside
                               *  Yearn V3 vaults to provide the needed triggers for a keeper
                               *  to perform automated debt updates for the vaults strategies.
                               *
                               * @dev
                               *  Each vault that should be managed by this allocator will
                               *  need to be added by first setting a `minimumChange` for the
                               *  vault, which will act as the minimum amount of funds to move that will
                               *  trigger a debt update. Then adding each strategy by setting a
                               *  `targetRatio` and optionally a `maxRatio`.
                               *
                               *  The allocator aims to allocate debt between the strategies
                               *  based on their set target ratios. Which are denominated in basis
                               *  points and represent the percent of total assets that specific
                               *  strategy should hold (i.e 1_000 == 10% of the vaults `totalAssets`).
                               *
                               *  The trigger will attempt to allocate up to the `maxRatio` when
                               *  the strategy has `minimumChange` amount less than the `targetRatio`.
                               *  And will pull funds to the `targetRatio` when it has `minimumChange`
                               *  more than its `maxRatio`.
                               */
                              contract DebtAllocator is Governance {
                                  /// @notice An event emitted when the base fee provider is set.
                                  event UpdatedBaseFeeProvider(address baseFeeProvider);
                              
                                  /// @notice An event emitted when a keeper is added or removed.
                                  event UpdateKeeper(address indexed keeper, bool allowed);
                              
                                  /// @notice An event emitted when the max base fee is updated.
                                  event UpdateMaxAcceptableBaseFee(uint256 newMaxAcceptableBaseFee);
                              
                                  /// @notice An event emitted when a strategies debt ratios are Updated.
                                  event UpdateStrategyDebtRatio(
                                      address indexed vault,
                                      address indexed strategy,
                                      uint256 newTargetRatio,
                                      uint256 newMaxRatio,
                                      uint256 newTotalDebtRatio
                                  );
                              
                                  /// @notice An event emitted when a strategy is added or removed.
                                  event StrategyChanged(
                                      address indexed vault,
                                      address indexed strategy,
                                      Status status
                                  );
                              
                                  /// @notice An event emitted when the minimum change is updated.
                                  event UpdateMinimumChange(address indexed vault, uint256 newMinimumChange);
                              
                                  /// @notice An even emitted when the paused status is updated.
                                  event UpdatePaused(address indexed vault, bool indexed status);
                              
                                  /// @notice An event emitted when the minimum time to wait is updated.
                                  event UpdateMinimumWait(uint256 newMinimumWait);
                              
                                  /// @notice An event emitted when a keeper is added or removed.
                                  event UpdateManager(address indexed manager, bool allowed);
                              
                                  /// @notice An event emitted when the max debt update loss is updated.
                                  event UpdateMaxDebtUpdateLoss(uint256 newMaxDebtUpdateLoss);
                              
                                  /// @notice Status when a strategy is added or removed from the allocator.
                                  enum Status {
                                      NULL,
                                      ADDED,
                                      REMOVED
                                  }
                              
                                  /// @notice Struct for each strategies info.
                                  struct StrategyConfig {
                                      // Flag to set when a strategy is added.
                                      bool added;
                                      // The ideal percent in Basis Points the strategy should have.
                                      uint16 targetRatio;
                                      // The max percent of assets the strategy should hold.
                                      uint16 maxRatio;
                                      // Timestamp of the last time debt was updated.
                                      // The debt updates must be done through this allocator
                                      // for this to be used.
                                      uint96 lastUpdate;
                                      // We have an extra 120 bits in the slot.
                                      // So we declare the variable in the struct so it can be
                                      // used if this contract is inherited.
                                      uint120 open;
                                  }
                              
                                  /// @notice Struct to hold the vault's info.
                                  struct VaultConfig {
                                      // Optional flag to stop the triggers.
                                      bool paused;
                                      // The minimum amount denominated in asset that will
                                      // need to be moved to trigger a debt update.
                                      uint128 minimumChange;
                                      // Total debt ratio currently allocated in basis points.
                                      // Can't be more than 10_000.
                                      uint16 totalDebtRatio;
                                  }
                              
                                  /// @notice Used during the `shouldUpdateDebt` to hold the data.
                                  struct StrategyDebtInfo {
                                      VaultConfig vaultConfig;
                                      StrategyConfig strategyConfig;
                                      uint256 vaultAssets;
                                      uint256 targetDebt;
                                      uint256 maxDebt;
                                      uint256 currentIdle;
                                      uint256 minIdle;
                                      uint256 toChange;
                                  }
                              
                                  /// @notice Make sure the caller is governance or a manager.
                                  modifier onlyManagers() {
                                      _isManager();
                                      _;
                                  }
                              
                                  /// @notice Make sure the caller is a keeper
                                  modifier onlyKeepers() {
                                      _isKeeper();
                                      _;
                                  }
                              
                                  /// @notice Check is either factories governance or local manager.
                                  function _isManager() internal view virtual {
                                      require(managers[msg.sender] || msg.sender == governance, "!manager");
                                  }
                              
                                  /// @notice Check is one of the allowed keepers.
                                  function _isKeeper() internal view virtual {
                                      require(keepers[msg.sender], "!keeper");
                                  }
                              
                                  uint256 internal constant MAX_BPS = 10_000;
                              
                                  /// @notice Time to wait between debt updates in seconds.
                                  uint256 public minimumWait;
                              
                                  /// @notice Provider to read current block's base fee.
                                  address public baseFeeProvider;
                              
                                  /// @notice Max loss to accept on debt updates in basis points.
                                  uint256 public maxDebtUpdateLoss;
                              
                                  /// @notice Max the chains base fee can be during debt update.
                                  // Will default to max uint256 and need to be set to be used.
                                  uint256 public maxAcceptableBaseFee;
                              
                                  /// @notice Mapping of addresses that are allowed to update debt.
                                  mapping(address => bool) public keepers;
                              
                                  /// @notice Mapping of addresses that are allowed to update debt ratios.
                                  mapping(address => bool) public managers;
                              
                                  mapping(address => VaultConfig) internal _vaultConfigs;
                              
                                  /// @notice Mapping of vault => strategy => its config.
                                  mapping(address => mapping(address => StrategyConfig))
                                      internal _strategyConfigs;
                              
                                  constructor() Governance(msg.sender) {}
                              
                                  /**
                                   * @notice Initialize the contract after being cloned.
                                   * @dev Sets default values for the global variables.
                                   */
                                  function initialize(address _governance) external {
                                      require(governance == address(0), "initialized");
                                      require(_governance != address(0), "ZERO ADDRESS");
                              
                                      governance = _governance;
                                      emit GovernanceTransferred(address(0), _governance);
                              
                                      // Default max base fee to uint max.
                                      maxAcceptableBaseFee = type(uint256).max;
                              
                                      // Default to allow 1 BP loss.
                                      maxDebtUpdateLoss = 1;
                              
                                      // Default minimum wait to 6 hours
                                      minimumWait = 60 * 60 * 6;
                              
                                      // Default to allow governance to be a keeper.
                                      keepers[_governance] = true;
                                      emit UpdateKeeper(_governance, true);
                                  }
                              
                                  /**
                                   * @notice Debt update wrapper for the vault.
                                   * @dev This contract must have the DEBT_MANAGER role assigned to them.
                                   *
                                   *   This will also uses the `maxUpdateDebtLoss` during debt
                                   *   updates to assure decreases did not realize profits outside
                                   *   of the allowed range.
                                   */
                                  function update_debt(
                                      address _vault,
                                      address _strategy,
                                      uint256 _targetDebt
                                  ) public virtual onlyKeepers {
                                      // If going to 0 record full balance first.
                                      if (_targetDebt == 0) {
                                          IVault(_vault).process_report(_strategy);
                                      }
                              
                                      // Update debt with the default max loss.
                                      IVault(_vault).update_debt(_strategy, _targetDebt, maxDebtUpdateLoss);
                              
                                      // Update the last time the strategies debt was updated.
                                      _strategyConfigs[_vault][_strategy].lastUpdate = uint96(
                                          block.timestamp
                                      );
                                  }
                              
                                  /**
                                   * @notice Check if a strategy's debt should be updated.
                                   * @dev This should be called by a keeper to decide if a strategies
                                   * debt should be updated and if so by how much.
                                   *
                                   * @param _vault Address of the vault to update.
                                   * @param _strategy Address of the strategy to check.
                                   * @return . Bool representing if the debt should be updated.
                                   * @return . Calldata if `true` or reason if `false`.
                                   */
                                  function shouldUpdateDebt(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (bool, bytes memory) {
                                      // Store all local variables in a struct to avoid stack to deep
                                      StrategyDebtInfo memory strategyDebtInfo;
                              
                                      strategyDebtInfo.vaultConfig = getVaultConfig(_vault);
                              
                                      // Don't do anything if paused.
                                      if (strategyDebtInfo.vaultConfig.paused) {
                                          return (false, bytes("Paused"));
                                      }
                              
                                      // Check the base fee isn't too high.
                                      if (!isCurrentBaseFeeAcceptable()) return (false, bytes("Base Fee"));
                              
                                      // Get the strategy specific debt config.
                                      strategyDebtInfo.strategyConfig = getStrategyConfig(_vault, _strategy);
                              
                                      // Make sure the strategy has been added to the allocator.
                                      if (!strategyDebtInfo.strategyConfig.added) {
                                          return (false, bytes("!added"));
                                      }
                              
                                      if (
                                          block.timestamp - strategyDebtInfo.strategyConfig.lastUpdate <=
                                          minimumWait
                                      ) {
                                          return (false, bytes("min wait"));
                                      }
                              
                                      // Retrieve the strategy specific parameters.
                                      IVault.StrategyParams memory params = IVault(_vault).strategies(
                                          _strategy
                                      );
                                      // Make sure its an active strategy.
                                      require(params.activation != 0, "!active");
                              
                                      strategyDebtInfo.vaultAssets = IVault(_vault).totalAssets();
                              
                                      // Get the target debt for the strategy based on vault assets.
                                      strategyDebtInfo.targetDebt = Math.min(
                                          (strategyDebtInfo.vaultAssets *
                                              strategyDebtInfo.strategyConfig.targetRatio) / MAX_BPS,
                                          // Make sure it is not more than the max allowed.
                                          params.max_debt
                                      );
                              
                                      // Get the max debt we would want the strategy to have.
                                      strategyDebtInfo.maxDebt = Math.min(
                                          (strategyDebtInfo.vaultAssets *
                                              strategyDebtInfo.strategyConfig.maxRatio) / MAX_BPS,
                                          // Make sure it is not more than the max allowed.
                                          params.max_debt
                                      );
                              
                                      // If we need to add more.
                                      if (strategyDebtInfo.targetDebt > params.current_debt) {
                                          strategyDebtInfo.currentIdle = IVault(_vault).totalIdle();
                                          strategyDebtInfo.minIdle = IVault(_vault).minimum_total_idle();
                              
                                          // We can't add more than the available idle.
                                          if (strategyDebtInfo.minIdle >= strategyDebtInfo.currentIdle) {
                                              return (false, bytes("No Idle"));
                                          }
                              
                                          // Add up to the max if possible
                                          strategyDebtInfo.toChange = Math.min(
                                              strategyDebtInfo.maxDebt - params.current_debt,
                                              // Can't take more than is available.
                                              Math.min(
                                                  strategyDebtInfo.currentIdle - strategyDebtInfo.minIdle,
                                                  IVault(_strategy).maxDeposit(_vault)
                                              )
                                          );
                              
                                          // If the amount to add is over our threshold.
                                          if (
                                              strategyDebtInfo.toChange >
                                              strategyDebtInfo.vaultConfig.minimumChange
                                          ) {
                                              // Return true and the calldata.
                                              return (
                                                  true,
                                                  abi.encodeCall(
                                                      this.update_debt,
                                                      (
                                                          _vault,
                                                          _strategy,
                                                          params.current_debt + strategyDebtInfo.toChange
                                                      )
                                                  )
                                              );
                                          }
                                          // If current debt is greater than our max.
                                      } else if (strategyDebtInfo.maxDebt < params.current_debt) {
                                          strategyDebtInfo.toChange =
                                              params.current_debt -
                                              strategyDebtInfo.targetDebt;
                              
                                          strategyDebtInfo.currentIdle = IVault(_vault).totalIdle();
                                          strategyDebtInfo.minIdle = IVault(_vault).minimum_total_idle();
                              
                                          if (strategyDebtInfo.minIdle > strategyDebtInfo.currentIdle) {
                                              // Pull at least the amount needed for minIdle.
                                              strategyDebtInfo.toChange = Math.max(
                                                  strategyDebtInfo.toChange,
                                                  strategyDebtInfo.minIdle - strategyDebtInfo.currentIdle
                                              );
                                          }
                              
                                          // Find out by how much. Aim for the target.
                                          strategyDebtInfo.toChange = Math.min(
                                              strategyDebtInfo.toChange,
                                              // Account for the current liquidity constraints.
                                              // Use max redeem to match vault logic.
                                              IVault(_strategy).convertToAssets(
                                                  IVault(_strategy).maxRedeem(_vault)
                                              )
                                          );
                              
                                          // Check if it's over the threshold.
                                          if (
                                              strategyDebtInfo.toChange >
                                              strategyDebtInfo.vaultConfig.minimumChange
                                          ) {
                                              // Can't lower debt if there are unrealised losses.
                                              if (
                                                  IVault(_vault).assess_share_of_unrealised_losses(
                                                      _strategy,
                                                      params.current_debt
                                                  ) != 0
                                              ) {
                                                  return (false, bytes("unrealised loss"));
                                              }
                              
                                              // If so return true and the calldata.
                                              return (
                                                  true,
                                                  abi.encodeCall(
                                                      this.update_debt,
                                                      (
                                                          _vault,
                                                          _strategy,
                                                          params.current_debt - strategyDebtInfo.toChange
                                                      )
                                                  )
                                              );
                                          }
                                      }
                              
                                      // Either no change or below our minimumChange.
                                      return (false, bytes("Below Min"));
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      STRATEGY MANAGEMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Increase a strategies target debt ratio.
                                   * @dev `setStrategyDebtRatio` functions will do all needed checks.
                                   * @param _strategy The address of the strategy to increase the debt ratio for.
                                   * @param _increase The amount in Basis Points to increase it.
                                   */
                                  function increaseStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _increase
                                  ) external virtual {
                                      setStrategyDebtRatio(
                                          _vault,
                                          _strategy,
                                          getStrategyTargetRatio(_vault, _strategy) + _increase
                                      );
                                  }
                              
                                  /**
                                   * @notice Decrease a strategies target debt ratio.
                                   * @param _strategy The address of the strategy to decrease the debt ratio for.
                                   * @param _decrease The amount in Basis Points to decrease it.
                                   */
                                  function decreaseStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _decrease
                                  ) external virtual {
                                      setStrategyDebtRatio(
                                          _vault,
                                          _strategy,
                                          getStrategyTargetRatio(_vault, _strategy) - _decrease
                                      );
                                  }
                              
                                  /**
                                   * @notice Sets a new target debt ratio for a strategy.
                                   * @dev This will default to a 20% increase for max debt.
                                   *
                                   * @param _strategy Address of the strategy to set.
                                   * @param _targetRatio Amount in Basis points to allocate.
                                   */
                                  function setStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _targetRatio
                                  ) public virtual {
                                      uint256 maxRatio = Math.min((_targetRatio * 12_000) / MAX_BPS, MAX_BPS);
                                      setStrategyDebtRatio(_vault, _strategy, _targetRatio, maxRatio);
                                  }
                              
                                  /**
                                   * @notice Sets a new target debt ratio for a strategy.
                                   * @dev A `minimumChange` for that strategy must be set first.
                                   * This is to prevent debt from being updated too frequently.
                                   *
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy to set.
                                   * @param _targetRatio Amount in Basis points to allocate.
                                   * @param _maxRatio Max ratio to give on debt increases.
                                   */
                                  function setStrategyDebtRatio(
                                      address _vault,
                                      address _strategy,
                                      uint256 _targetRatio,
                                      uint256 _maxRatio
                                  ) public virtual onlyManagers {
                                      VaultConfig memory vaultConfig = getVaultConfig(_vault);
                                      // Make sure a minimumChange has been set.
                                      require(vaultConfig.minimumChange != 0, "!minimum");
                                      // Cannot be more than 100%.
                                      require(_maxRatio <= MAX_BPS, "max too high");
                                      // Max cannot be lower than the target.
                                      require(_maxRatio >= _targetRatio, "max ratio");
                              
                                      // Get the current config.
                                      StrategyConfig memory strategyConfig = getStrategyConfig(
                                          _vault,
                                          _strategy
                                      );
                              
                                      // Set added flag if not set yet.
                                      if (!strategyConfig.added) {
                                          strategyConfig.added = true;
                                          emit StrategyChanged(_vault, _strategy, Status.ADDED);
                                      }
                              
                                      // Get what will be the new total debt ratio.
                                      uint256 newTotalDebtRatio = vaultConfig.totalDebtRatio -
                                          strategyConfig.targetRatio +
                                          _targetRatio;
                              
                                      // Make sure it is under 100% allocated
                                      require(newTotalDebtRatio <= MAX_BPS, "ratio too high");
                              
                                      // Update local config.
                                      strategyConfig.targetRatio = uint16(_targetRatio);
                                      strategyConfig.maxRatio = uint16(_maxRatio);
                              
                                      // Write to storage.
                                      _strategyConfigs[_vault][_strategy] = strategyConfig;
                                      _vaultConfigs[_vault].totalDebtRatio = uint16(newTotalDebtRatio);
                              
                                      emit UpdateStrategyDebtRatio(
                                          _vault,
                                          _strategy,
                                          _targetRatio,
                                          _maxRatio,
                                          newTotalDebtRatio
                                      );
                                  }
                              
                                  /**
                                   * @notice Remove a strategy from this debt allocator.
                                   * @dev Will delete the full config for the strategy
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the address ro remove.
                                   */
                                  function removeStrategy(
                                      address _vault,
                                      address _strategy
                                  ) external virtual onlyManagers {
                                      StrategyConfig memory strategyConfig = getStrategyConfig(
                                          _vault,
                                          _strategy
                                      );
                                      require(strategyConfig.added, "!added");
                              
                                      uint256 target = strategyConfig.targetRatio;
                              
                                      // Remove any debt ratio the strategy holds.
                                      if (target != 0) {
                                          uint256 newRatio = _vaultConfigs[_vault].totalDebtRatio - target;
                                          _vaultConfigs[_vault].totalDebtRatio = uint16(newRatio);
                                          emit UpdateStrategyDebtRatio(_vault, _strategy, 0, 0, newRatio);
                                      }
                              
                                      // Remove the full config including the `added` flag.
                                      delete _strategyConfigs[_vault][_strategy];
                              
                                      // Emit Event.
                                      emit StrategyChanged(_vault, _strategy, Status.REMOVED);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      VAULT MANAGEMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Set the minimum change variable for a strategy.
                                   * @dev This is the minimum amount of debt to be
                                   * added or pulled for it to trigger an update.
                                   *
                                   * @param _vault Address of the vault
                                   * @param _minimumChange The new minimum to set for the strategy.
                                   */
                                  function setMinimumChange(
                                      address _vault,
                                      uint256 _minimumChange
                                  ) external virtual onlyGovernance {
                                      require(_minimumChange > 0, "zero change");
                                      // Make sure it fits in the slot size.
                                      require(_minimumChange < type(uint128).max, "too high");
                              
                                      // Set the new minimum.
                                      _vaultConfigs[_vault].minimumChange = uint128(_minimumChange);
                              
                                      emit UpdateMinimumChange(_vault, _minimumChange);
                                  }
                              
                                  /**
                                   * @notice Allows governance to pause the triggers.
                                   * @param _vault Address of the vault
                                   * @param _status Status to set the `paused` bool to.
                                   */
                                  function setPaused(
                                      address _vault,
                                      bool _status
                                  ) external virtual onlyGovernance {
                                      require(_status != _vaultConfigs[_vault].paused, "already set");
                                      _vaultConfigs[_vault].paused = _status;
                              
                                      emit UpdatePaused(_vault, _status);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      ALLOCATOR MANAGEMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Set the minimum time to wait before re-updating a strategies debt.
                                   * @dev This is only enforced per strategy.
                                   * @param _minimumWait The minimum time in seconds to wait.
                                   */
                                  function setMinimumWait(
                                      uint256 _minimumWait
                                  ) external virtual onlyGovernance {
                                      minimumWait = _minimumWait;
                              
                                      emit UpdateMinimumWait(_minimumWait);
                                  }
                              
                                  /**
                                   * @notice Set if a manager can update ratios.
                                   * @param _address The address to set mapping for.
                                   * @param _allowed If the address can call {update_debt}.
                                   */
                                  function setManager(
                                      address _address,
                                      bool _allowed
                                  ) external virtual onlyGovernance {
                                      managers[_address] = _allowed;
                              
                                      emit UpdateManager(_address, _allowed);
                                  }
                              
                                  /**
                                   * @notice Set the max loss in Basis points to allow on debt updates.
                                   * @dev Withdrawing during debt updates use {redeem} which allows for 100% loss.
                                   *      This can be used to assure a loss is not realized on redeem outside the tolerance.
                                   * @param _maxDebtUpdateLoss The max loss to accept on debt updates.
                                   */
                                  function setMaxDebtUpdateLoss(
                                      uint256 _maxDebtUpdateLoss
                                  ) external virtual onlyGovernance {
                                      require(_maxDebtUpdateLoss <= MAX_BPS, "higher than max");
                                      maxDebtUpdateLoss = _maxDebtUpdateLoss;
                              
                                      emit UpdateMaxDebtUpdateLoss(_maxDebtUpdateLoss);
                                  }
                              
                                  /**
                                   * @notice
                                   *  Used to set our baseFeeProvider, which checks the network's current base
                                   *  fee price to determine whether it is an optimal time to harvest or tend.
                                   *
                                   *  This may only be called by governance.
                                   * @param _baseFeeProvider Address of our baseFeeProvider
                                   */
                                  function setBaseFeeProvider(
                                      address _baseFeeProvider
                                  ) external virtual onlyGovernance {
                                      baseFeeProvider = _baseFeeProvider;
                              
                                      emit UpdatedBaseFeeProvider(_baseFeeProvider);
                                  }
                              
                                  /**
                                   * @notice Set the max acceptable base fee.
                                   * @dev This defaults to max uint256 and will need to
                                   * be set for it to be used.
                                   *
                                   * Is denominated in gwei. So 50gwei would be set as 50e9.
                                   *
                                   * @param _maxAcceptableBaseFee The new max base fee.
                                   */
                                  function setMaxAcceptableBaseFee(
                                      uint256 _maxAcceptableBaseFee
                                  ) external virtual onlyGovernance {
                                      maxAcceptableBaseFee = _maxAcceptableBaseFee;
                              
                                      emit UpdateMaxAcceptableBaseFee(_maxAcceptableBaseFee);
                                  }
                              
                                  /**
                                   * @notice Set if a keeper can update debt.
                                   * @param _address The address to set mapping for.
                                   * @param _allowed If the address can call {update_debt}.
                                   */
                                  function setKeeper(
                                      address _address,
                                      bool _allowed
                                  ) external virtual onlyGovernance {
                                      keepers[_address] = _allowed;
                              
                                      emit UpdateKeeper(_address, _allowed);
                                  }
                              
                                  /**
                                   * @notice Get a strategies full config.
                                   * @dev Used for customizations by inheriting the contract.
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy.
                                   * @return The strategies current Config.
                                   */
                                  function getStrategyConfig(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (StrategyConfig memory) {
                                      return _strategyConfigs[_vault][_strategy];
                                  }
                              
                                  /**
                                   * @notice Get a vaults full config.
                                   * @dev Used for customizations by inheriting the contract.
                                   * @param _vault Address of the vault.
                                   * @return The vaults current Config.
                                   */
                                  function getVaultConfig(
                                      address _vault
                                  ) public view virtual returns (VaultConfig memory) {
                                      return _vaultConfigs[_vault];
                                  }
                              
                                  /**
                                   * @notice Get a vaults current total debt.
                                   * @param _vault Address of the vault
                                   */
                                  function totalDebtRatio(
                                      address _vault
                                  ) external view virtual returns (uint256) {
                                      return getVaultConfig(_vault).totalDebtRatio;
                                  }
                              
                                  /**
                                   * @notice Get a vaults minimum change required.
                                   * @param _vault Address of the vault
                                   */
                                  function minimumChange(
                                      address _vault
                                  ) external view virtual returns (uint256) {
                                      return getVaultConfig(_vault).minimumChange;
                                  }
                              
                                  /**
                                   * @notice Get the paused status of a vault
                                   * @param _vault Address of the vault
                                   */
                                  function isPaused(address _vault) public view virtual returns (bool) {
                                      return getVaultConfig(_vault).paused;
                                  }
                              
                                  /**
                                   * @notice Get a strategies target debt ratio.
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy.
                                   * @return The strategies current targetRatio.
                                   */
                                  function getStrategyTargetRatio(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (uint256) {
                                      return getStrategyConfig(_vault, _strategy).targetRatio;
                                  }
                              
                                  /**
                                   * @notice Get a strategies max debt ratio.
                                   * @param _vault Address of the vault
                                   * @param _strategy Address of the strategy.
                                   * @return The strategies current maxRatio.
                                   */
                                  function getStrategyMaxRatio(
                                      address _vault,
                                      address _strategy
                                  ) public view virtual returns (uint256) {
                                      return getStrategyConfig(_vault, _strategy).maxRatio;
                                  }
                              
                                  /**
                                   * @notice Returns wether or not the current base fee is acceptable
                                   *   based on the `maxAcceptableBaseFee`.
                                   * @return . If the current base fee is acceptable.
                                   */
                                  function isCurrentBaseFeeAcceptable() public view virtual returns (bool) {
                                      address _baseFeeProvider = baseFeeProvider;
                                      if (_baseFeeProvider == address(0)) return true;
                                      return
                                          maxAcceptableBaseFee >= IBaseFee(_baseFeeProvider).basefee_global();
                                  }
                              }

                              File 9 of 11: Yearn V3 Vault
                              # @version 0.3.7
                              
                              """
                              @title Yearn V3 Vault
                              @license GNU AGPLv3
                              @author yearn.finance
                              @notice
                                  The Yearn VaultV3 is designed as a non-opinionated system to distribute funds of 
                                  depositors for a specific `asset` into different opportunities (aka Strategies)
                                  and manage accounting in a robust way.
                              
                                  Depositors receive shares (aka vaults tokens) proportional to their deposit amount. 
                                  Vault tokens are yield-bearing and can be redeemed at any time to get back deposit 
                                  plus any yield generated.
                              
                                  Addresses that are given different permissioned roles by the `role_manager` 
                                  are then able to allocate funds as they best see fit to different strategies 
                                  and adjust the strategies and allocations as needed, as well as reporting realized
                                  profits or losses.
                              
                                  Strategies are any ERC-4626 compliant contracts that use the same underlying `asset` 
                                  as the vault. The vault provides no assurances as to the safety of any strategy
                                  and it is the responsibility of those that hold the corresponding roles to choose
                                  and fund strategies that best fit their desired specifications.
                              
                                  Those holding vault tokens are able to redeem the tokens for the corresponding
                                  amount of underlying asset based on any reported profits or losses since their
                                  initial deposit.
                              
                                  The vault is built to be customized by the management to be able to fit their
                                  specific desired needs. Including the customization of strategies, accountants, 
                                  ownership etc.
                              """
                              
                              # INTERFACES #
                              
                              from vyper.interfaces import ERC20
                              from vyper.interfaces import ERC20Detailed
                              
                              interface IStrategy:
                                  def asset() -> address: view
                                  def balanceOf(owner: address) -> uint256: view
                                  def convertToAssets(shares: uint256) -> uint256: view
                                  def convertToShares(assets: uint256) -> uint256: view
                                  def previewWithdraw(assets: uint256) -> uint256: view
                                  def maxDeposit(receiver: address) -> uint256: view
                                  def deposit(assets: uint256, receiver: address) -> uint256: nonpayable
                                  def maxRedeem(owner: address) -> uint256: view
                                  def redeem(shares: uint256, receiver: address, owner: address) -> uint256: nonpayable
                                  
                              interface IAccountant:
                                  def report(strategy: address, gain: uint256, loss: uint256) -> (uint256, uint256): nonpayable
                              
                              interface IDepositLimitModule:
                                  def available_deposit_limit(receiver: address) -> uint256: view
                                  
                              interface IWithdrawLimitModule:
                                  def available_withdraw_limit(owner: address, max_loss: uint256, strategies: DynArray[address, MAX_QUEUE]) -> uint256: view
                              
                              interface IFactory:
                                  def protocol_fee_config() -> (uint16, address): view
                              
                              # EVENTS #
                              # ERC4626 EVENTS
                              event Deposit:
                                  sender: indexed(address)
                                  owner: indexed(address)
                                  assets: uint256
                                  shares: uint256
                              
                              event Withdraw:
                                  sender: indexed(address)
                                  receiver: indexed(address)
                                  owner: indexed(address)
                                  assets: uint256
                                  shares: uint256
                              
                              # ERC20 EVENTS
                              event Transfer:
                                  sender: indexed(address)
                                  receiver: indexed(address)
                                  value: uint256
                              
                              event Approval:
                                  owner: indexed(address)
                                  spender: indexed(address)
                                  value: uint256
                              
                              # STRATEGY EVENTS
                              event StrategyChanged:
                                  strategy: indexed(address)
                                  change_type: indexed(StrategyChangeType)
                                  
                              event StrategyReported:
                                  strategy: indexed(address)
                                  gain: uint256
                                  loss: uint256
                                  current_debt: uint256
                                  protocol_fees: uint256
                                  total_fees: uint256
                                  total_refunds: uint256
                              
                              # DEBT MANAGEMENT EVENTS
                              event DebtUpdated:
                                  strategy: indexed(address)
                                  current_debt: uint256
                                  new_debt: uint256
                              
                              # ROLE UPDATES
                              event RoleSet:
                                  account: indexed(address)
                                  role: indexed(Roles)
                              
                              # STORAGE MANAGEMENT EVENTS
                              event UpdateRoleManager:
                                  role_manager: indexed(address)
                              
                              event UpdateAccountant:
                                  accountant: indexed(address)
                              
                              event UpdateDepositLimitModule:
                                  deposit_limit_module: indexed(address)
                              
                              event UpdateWithdrawLimitModule:
                                  withdraw_limit_module: indexed(address)
                              
                              event UpdateDefaultQueue:
                                  new_default_queue: DynArray[address, MAX_QUEUE]
                              
                              event UpdateUseDefaultQueue:
                                  use_default_queue: bool
                              
                              event UpdatedMaxDebtForStrategy:
                                  sender: indexed(address)
                                  strategy: indexed(address)
                                  new_debt: uint256
                              
                              event UpdateDepositLimit:
                                  deposit_limit: uint256
                              
                              event UpdateMinimumTotalIdle:
                                  minimum_total_idle: uint256
                              
                              event UpdateProfitMaxUnlockTime:
                                  profit_max_unlock_time: uint256
                              
                              event DebtPurchased:
                                  strategy: indexed(address)
                                  amount: uint256
                              
                              event Shutdown:
                                  pass
                              
                              # STRUCTS #
                              struct StrategyParams:
                                  # Timestamp when the strategy was added.
                                  activation: uint256 
                                  # Timestamp of the strategies last report.
                                  last_report: uint256
                                  # The current assets the strategy holds.
                                  current_debt: uint256
                                  # The max assets the strategy can hold. 
                                  max_debt: uint256
                              
                              # CONSTANTS #
                              # The max length the withdrawal queue can be.
                              MAX_QUEUE: constant(uint256) = 10
                              # 100% in Basis Points.
                              MAX_BPS: constant(uint256) = 10_000
                              # Extended for profit locking calculations.
                              MAX_BPS_EXTENDED: constant(uint256) = 1_000_000_000_000
                              # The version of this vault.
                              API_VERSION: constant(String[28]) = "3.0.2"
                              
                              # ENUMS #
                              # Each permissioned function has its own Role.
                              # Roles can be combined in any combination or all kept separate.
                              # Follows python Enum patterns so the first Enum == 1 and doubles each time.
                              enum Roles:
                                  ADD_STRATEGY_MANAGER # Can add strategies to the vault.
                                  REVOKE_STRATEGY_MANAGER # Can remove strategies from the vault.
                                  FORCE_REVOKE_MANAGER # Can force remove a strategy causing a loss.
                                  ACCOUNTANT_MANAGER # Can set the accountant that assess fees.
                                  QUEUE_MANAGER # Can set the default withdrawal queue.
                                  REPORTING_MANAGER # Calls report for strategies.
                                  DEBT_MANAGER # Adds and removes debt from strategies.
                                  MAX_DEBT_MANAGER # Can set the max debt for a strategy.
                                  DEPOSIT_LIMIT_MANAGER # Sets deposit limit and module for the vault.
                                  WITHDRAW_LIMIT_MANAGER # Sets the withdraw limit module.
                                  MINIMUM_IDLE_MANAGER # Sets the minimum total idle the vault should keep.
                                  PROFIT_UNLOCK_MANAGER # Sets the profit_max_unlock_time.
                                  DEBT_PURCHASER # Can purchase bad debt from the vault.
                                  EMERGENCY_MANAGER # Can shutdown vault in an emergency.
                              
                              enum StrategyChangeType:
                                  ADDED
                                  REVOKED
                              
                              enum Rounding:
                                  ROUND_DOWN
                                  ROUND_UP
                              
                              # STORAGE #
                              # Underlying token used by the vault.
                              asset: public(address)
                              # Based off the `asset` decimals.
                              decimals: public(uint8)
                              # Deployer contract used to retrieve the protocol fee config.
                              factory: address
                              
                              # HashMap that records all the strategies that are allowed to receive assets from the vault.
                              strategies: public(HashMap[address, StrategyParams])
                              # The current default withdrawal queue.
                              default_queue: public(DynArray[address, MAX_QUEUE])
                              # Should the vault use the default_queue regardless whats passed in.
                              use_default_queue: public(bool)
                              
                              ### ACCOUNTING ###
                              # ERC20 - amount of shares per account
                              balance_of: HashMap[address, uint256]
                              # ERC20 - owner -> (spender -> amount)
                              allowance: public(HashMap[address, HashMap[address, uint256]])
                              # Total amount of shares that are currently minted including those locked.
                              total_supply: uint256
                              # Total amount of assets that has been deposited in strategies.
                              total_debt: uint256
                              # Current assets held in the vault contract. Replacing balanceOf(this) to avoid price_per_share manipulation.
                              total_idle: uint256
                              # Minimum amount of assets that should be kept in the vault contract to allow for fast, cheap redeems.
                              minimum_total_idle: public(uint256)
                              # Maximum amount of tokens that the vault can accept. If totalAssets > deposit_limit, deposits will revert.
                              deposit_limit: public(uint256)
                              
                              ### PERIPHERY ###
                              # Contract that charges fees and can give refunds.
                              accountant: public(address)
                              # Contract to control the deposit limit.
                              deposit_limit_module: public(address)
                              # Contract to control the withdraw limit.
                              withdraw_limit_module: public(address)
                              
                              ### ROLES ###
                              # HashMap mapping addresses to their roles
                              roles: public(HashMap[address, Roles])
                              # Address that can add and remove roles to addresses.
                              role_manager: public(address)
                              # Temporary variable to store the address of the next role_manager until the role is accepted.
                              future_role_manager: public(address)
                              
                              # ERC20 - name of the vaults token.
                              name: public(String[64])
                              # ERC20 - symbol of the vaults token.
                              symbol: public(String[32])
                              
                              # State of the vault - if set to true, only withdrawals will be available. It can't be reverted.
                              shutdown: bool
                              # The amount of time profits will unlock over.
                              profit_max_unlock_time: uint256
                              # The timestamp of when the current unlocking period ends.
                              full_profit_unlock_date: uint256
                              # The per second rate at which profit will unlock.
                              profit_unlocking_rate: uint256
                              # Last timestamp of the most recent profitable report.
                              last_profit_update: uint256
                              
                              # `nonces` track `permit` approvals with signature.
                              nonces: public(HashMap[address, uint256])
                              DOMAIN_TYPE_HASH: constant(bytes32) = keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
                              PERMIT_TYPE_HASH: constant(bytes32) = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                              
                              # Constructor
                              @external
                              def __init__():
                                  # Set `asset` so it cannot be re-initialized.
                                  self.asset = self
                                  
                              @external
                              def initialize(
                                  asset: address, 
                                  name: String[64], 
                                  symbol: String[32], 
                                  role_manager: address, 
                                  profit_max_unlock_time: uint256
                              ):
                                  """
                                  @notice
                                      Initialize a new vault. Sets the asset, name, symbol, and role manager.
                                  @param asset
                                      The address of the asset that the vault will accept.
                                  @param name
                                      The name of the vault token.
                                  @param symbol
                                      The symbol of the vault token.
                                  @param role_manager 
                                      The address that can add and remove roles to addresses
                                  @param profit_max_unlock_time
                                      The amount of time that the profit will be locked for
                                  """
                                  assert self.asset == empty(address), "initialized"
                                  assert asset != empty(address), "ZERO ADDRESS"
                                  assert role_manager != empty(address), "ZERO ADDRESS"
                              
                                  self.asset = asset
                                  # Get the decimals for the vault to use.
                                  self.decimals = ERC20Detailed(asset).decimals()
                                  
                                  # Set the factory as the deployer address.
                                  self.factory = msg.sender
                              
                                  # Must be less than one year for report cycles
                                  assert profit_max_unlock_time <= 31_556_952 # dev: profit unlock time too long
                                  self.profit_max_unlock_time = profit_max_unlock_time
                              
                                  self.name = name
                                  self.symbol = symbol
                                  self.role_manager = role_manager
                              
                              ## SHARE MANAGEMENT ##
                              ## ERC20 ##
                              @internal
                              def _spend_allowance(owner: address, spender: address, amount: uint256):
                                  # Unlimited approval does nothing (saves an SSTORE)
                                  current_allowance: uint256 = self.allowance[owner][spender]
                                  if (current_allowance < max_value(uint256)):
                                      assert current_allowance >= amount, "insufficient allowance"
                                      self._approve(owner, spender, unsafe_sub(current_allowance, amount))
                              
                              @internal
                              def _transfer(sender: address, receiver: address, amount: uint256):
                                  sender_balance: uint256 = self.balance_of[sender]
                                  assert sender_balance >= amount, "insufficient funds"
                                  self.balance_of[sender] = unsafe_sub(sender_balance, amount)
                                  self.balance_of[receiver] = unsafe_add(self.balance_of[receiver], amount)
                                  log Transfer(sender, receiver, amount)
                              
                              @internal
                              def _transfer_from(sender: address, receiver: address, amount: uint256) -> bool:
                                  self._spend_allowance(sender, msg.sender, amount)
                                  self._transfer(sender, receiver, amount)
                                  return True
                              
                              @internal
                              def _approve(owner: address, spender: address, amount: uint256) -> bool:
                                  self.allowance[owner][spender] = amount
                                  log Approval(owner, spender, amount)
                                  return True
                              
                              @internal
                              def _permit(
                                  owner: address, 
                                  spender: address, 
                                  amount: uint256, 
                                  deadline: uint256, 
                                  v: uint8, 
                                  r: bytes32, 
                                  s: bytes32
                              ) -> bool:
                                  assert owner != empty(address), "invalid owner"
                                  assert deadline >= block.timestamp, "permit expired"
                                  nonce: uint256 = self.nonces[owner]
                                  digest: bytes32 = keccak256(
                                      concat(
                                          b'\x19\x01',
                                          self.domain_separator(),
                                          keccak256(
                                              concat(
                                                  PERMIT_TYPE_HASH,
                                                  convert(owner, bytes32),
                                                  convert(spender, bytes32),
                                                  convert(amount, bytes32),
                                                  convert(nonce, bytes32),
                                                  convert(deadline, bytes32),
                                              )
                                          )
                                      )
                                  )
                                  assert ecrecover(
                                      digest, v, r, s
                                  ) == owner, "invalid signature"
                              
                                  self.allowance[owner][spender] = amount
                                  self.nonces[owner] = nonce + 1
                                  log Approval(owner, spender, amount)
                                  return True
                              
                              @internal
                              def _burn_shares(shares: uint256, owner: address):
                                  self.balance_of[owner] -= shares
                                  self.total_supply = unsafe_sub(self.total_supply, shares)
                                  log Transfer(owner, empty(address), shares)
                              
                              @view
                              @internal
                              def _unlocked_shares() -> uint256:
                                  """
                                  Returns the amount of shares that have been unlocked.
                                  To avoid sudden price_per_share spikes, profits can be processed 
                                  through an unlocking period. The mechanism involves shares to be 
                                  minted to the vault which are unlocked gradually over time. Shares 
                                  that have been locked are gradually unlocked over profit_max_unlock_time.
                                  """
                                  _full_profit_unlock_date: uint256 = self.full_profit_unlock_date
                                  unlocked_shares: uint256 = 0
                                  if _full_profit_unlock_date > block.timestamp:
                                      # If we have not fully unlocked, we need to calculate how much has been.
                                      unlocked_shares = self.profit_unlocking_rate * (block.timestamp - self.last_profit_update) / MAX_BPS_EXTENDED
                              
                                  elif _full_profit_unlock_date != 0:
                                      # All shares have been unlocked
                                      unlocked_shares = self.balance_of[self]
                              
                                  return unlocked_shares
                              
                              
                              @view
                              @internal
                              def _total_supply() -> uint256:
                                  # Need to account for the shares issued to the vault that have unlocked.
                                  return self.total_supply - self._unlocked_shares()
                              
                              @view
                              @internal
                              def _total_assets() -> uint256:
                                  """
                                  Total amount of assets that are in the vault and in the strategies. 
                                  """
                                  return self.total_idle + self.total_debt
                              
                              @view
                              @internal
                              def _convert_to_assets(shares: uint256, rounding: Rounding) -> uint256:
                                  """ 
                                  assets = shares * (total_assets / total_supply) --- (== price_per_share * shares)
                                  """
                                  if shares == max_value(uint256) or shares == 0:
                                      return shares
                              
                                  total_supply: uint256 = self._total_supply()
                                  # if total_supply is 0, price_per_share is 1
                                  if total_supply == 0: 
                                      return shares
                              
                                  numerator: uint256 = shares * self._total_assets()
                                  amount: uint256 = numerator / total_supply
                                  if rounding == Rounding.ROUND_UP and numerator % total_supply != 0:
                                      amount += 1
                              
                                  return amount
                              
                              @view
                              @internal
                              def _convert_to_shares(assets: uint256, rounding: Rounding) -> uint256:
                                  """
                                  shares = amount * (total_supply / total_assets) --- (== amount / price_per_share)
                                  """
                                  if assets == max_value(uint256) or assets == 0:
                                      return assets
                              
                                  total_supply: uint256 = self._total_supply()
                                  total_assets: uint256 = self._total_assets()
                              
                                  if total_assets == 0:
                                      # if total_assets and total_supply is 0, price_per_share is 1
                                      if total_supply == 0:
                                          return assets
                                      else:
                                          # Else if total_supply > 0 price_per_share is 0
                                          return 0
                              
                                  numerator: uint256 = assets * total_supply
                                  shares: uint256 = numerator / total_assets
                                  if rounding == Rounding.ROUND_UP and numerator % total_assets != 0:
                                      shares += 1
                              
                                  return shares
                              
                              @internal
                              def _erc20_safe_approve(token: address, spender: address, amount: uint256):
                                  # Used only to approve tokens that are not the type managed by this Vault.
                                  # Used to handle non-compliant tokens like USDT
                                  assert ERC20(token).approve(spender, amount, default_return_value=True), "approval failed"
                              
                              @internal
                              def _erc20_safe_transfer_from(token: address, sender: address, receiver: address, amount: uint256):
                                  # Used only to transfer tokens that are not the type managed by this Vault.
                                  # Used to handle non-compliant tokens like USDT
                                  assert ERC20(token).transferFrom(sender, receiver, amount, default_return_value=True), "transfer failed"
                              
                              @internal
                              def _erc20_safe_transfer(token: address, receiver: address, amount: uint256):
                                  # Used only to send tokens that are not the type managed by this Vault.
                                  # Used to handle non-compliant tokens like USDT
                                  assert ERC20(token).transfer(receiver, amount, default_return_value=True), "transfer failed"
                              
                              @internal
                              def _issue_shares(shares: uint256, recipient: address):
                                  self.balance_of[recipient] = unsafe_add(self.balance_of[recipient], shares)
                                  self.total_supply += shares
                              
                                  log Transfer(empty(address), recipient, shares)
                              
                              @internal
                              def _issue_shares_for_amount(amount: uint256, recipient: address) -> uint256:
                                  """
                                  Issues shares that are worth 'amount' in the underlying token (asset).
                                  WARNING: this takes into account that any new assets have been summed 
                                  to total_assets (otherwise pps will go down).
                                  """
                                  total_supply: uint256 = self._total_supply()
                                  total_assets: uint256 = self._total_assets()
                                  new_shares: uint256 = 0
                                  
                                  # If no supply PPS = 1.
                                  if total_supply == 0:
                                      new_shares = amount
                                  elif total_assets > amount:
                                      new_shares = amount * total_supply / (total_assets - amount)
                              
                                  # We don't make the function revert
                                  if new_shares == 0:
                                     return 0
                              
                                  self._issue_shares(new_shares, recipient)
                              
                                  return new_shares
                              
                              ## ERC4626 ##
                              @view
                              @internal
                              def _max_deposit(receiver: address) -> uint256: 
                                  if receiver in [empty(address), self]:
                                      return 0
                              
                                  # If there is a deposit limit module set use that.
                                  deposit_limit_module: address = self.deposit_limit_module
                                  if deposit_limit_module != empty(address):
                                      return IDepositLimitModule(deposit_limit_module).available_deposit_limit(receiver)
                                  
                                  # Else use the standard flow.
                                  _deposit_limit: uint256 = self.deposit_limit
                                  if (_deposit_limit == max_value(uint256)):
                                      return _deposit_limit
                              
                                  _total_assets: uint256 = self._total_assets()
                                  if (_total_assets >= _deposit_limit):
                                      return 0
                              
                                  return unsafe_sub(_deposit_limit, _total_assets)
                              
                              @view
                              @internal
                              def _max_withdraw(
                                  owner: address,
                                  max_loss: uint256,
                                  strategies: DynArray[address, MAX_QUEUE]
                              ) -> uint256:
                                  """
                                  @dev Returns the max amount of `asset` an `owner` can withdraw.
                              
                                  This will do a full simulation of the withdraw in order to determine
                                  how much is currently liquid and if the `max_loss` would allow for the 
                                  tx to not revert.
                              
                                  This will track any expected loss to check if the tx will revert, but
                                  not account for it in the amount returned since it is unrealised and 
                                  therefore will not be accounted for in the conversion rates.
                              
                                  i.e. If we have 100 debt and 10 of unrealised loss, the max we can get
                                  out is 90, but a user of the vault will need to call withdraw with 100
                                  in order to get the full 90 out.
                                  """
                              
                                  # Get the max amount for the owner if fully liquid.
                                  max_assets: uint256 = self._convert_to_assets(self.balance_of[owner], Rounding.ROUND_DOWN)
                              
                                  # If there is a withdraw limit module use that.
                                  withdraw_limit_module: address = self.withdraw_limit_module
                                  if withdraw_limit_module != empty(address):
                                      return min(
                                          # Use the min between the returned value and the max.
                                          # Means the limit module doesn't need to account for balances or conversions.
                                          IWithdrawLimitModule(withdraw_limit_module).available_withdraw_limit(owner, max_loss, strategies),
                                          max_assets
                                      )
                                  
                                  # See if we have enough idle to service the withdraw.
                                  current_idle: uint256 = self.total_idle
                                  if max_assets > current_idle:
                                      # Track how much we can pull.
                                      have: uint256 = current_idle
                                      loss: uint256 = 0
                              
                                      # Cache the default queue.
                                      _strategies: DynArray[address, MAX_QUEUE] = self.default_queue
                              
                                      # If a custom queue was passed, and we don't force the default queue.
                                      if len(strategies) != 0 and not self.use_default_queue:
                                          # Use the custom queue.
                                          _strategies = strategies
                              
                                      for strategy in _strategies:
                                          # Can't use an invalid strategy.
                                          assert self.strategies[strategy].activation != 0, "inactive strategy"
                              
                                          # Get the maximum amount the vault would withdraw from the strategy.
                                          to_withdraw: uint256 = min(
                                              # What we still need for the full withdraw.
                                              max_assets - have, 
                                              # The current debt the strategy has.
                                              self.strategies[strategy].current_debt
                                          )
                              
                                          # Get any unrealised loss for the strategy.
                                          unrealised_loss: uint256 = self._assess_share_of_unrealised_losses(strategy, to_withdraw)
                              
                                          # See if any limit is enforced by the strategy.
                                          strategy_limit: uint256 = IStrategy(strategy).convertToAssets(
                                              IStrategy(strategy).maxRedeem(self)
                                          )
                              
                                          # Adjust accordingly if there is a max withdraw limit.
                                          realizable_withdraw: uint256 = to_withdraw - unrealised_loss
                                          if strategy_limit < realizable_withdraw:
                                              if unrealised_loss != 0:
                                                  # lower unrealised loss proportional to the limit.
                                                  unrealised_loss = unrealised_loss * strategy_limit / realizable_withdraw
                              
                                              # Still count the unrealised loss as withdrawable.
                                              to_withdraw = strategy_limit + unrealised_loss
                                              
                                          # If 0 move on to the next strategy.
                                          if to_withdraw == 0:
                                              continue
                              
                                          # If there would be a loss with a non-maximum `max_loss` value.
                                          if unrealised_loss > 0 and max_loss < MAX_BPS:
                                              # Check if the loss is greater than the allowed range.
                                              if loss + unrealised_loss > (have + to_withdraw) * max_loss / MAX_BPS:
                                                  # If so use the amounts up till now.
                                                  break
                              
                                          # Add to what we can pull.
                                          have += to_withdraw
                              
                                          # If we have all we need break.
                                          if have >= max_assets:
                                              break
                              
                                          # Add any unrealised loss to the total
                                          loss += unrealised_loss
                              
                                      # Update the max after going through the queue.
                                      # In case we broke early or exhausted the queue.
                                      max_assets = have
                              
                                  return max_assets
                              
                              @internal
                              def _deposit(sender: address, recipient: address, assets: uint256) -> uint256:
                                  """
                                  Used for `deposit` calls to transfer the amount of `asset` to the vault, 
                                  issue the corresponding shares to the `recipient` and update all needed 
                                  vault accounting.
                                  """
                                  assert self.shutdown == False # dev: shutdown
                                  assert assets <= self._max_deposit(recipient), "exceed deposit limit"
                               
                                  # Transfer the tokens to the vault first.
                                  self._erc20_safe_transfer_from(self.asset, msg.sender, self, assets)
                                  # Record the change in total assets.
                                  self.total_idle += assets
                                  
                                  # Issue the corresponding shares for assets.
                                  shares: uint256 = self._issue_shares_for_amount(assets, recipient)
                              
                                  assert shares > 0, "cannot mint zero"
                              
                                  log Deposit(sender, recipient, assets, shares)
                                  return shares
                              
                              @internal
                              def _mint(sender: address, recipient: address, shares: uint256) -> uint256:
                                  """
                                  Used for `mint` calls to issue the corresponding shares to the `recipient`,
                                  transfer the amount of `asset` to the vault, and update all needed vault 
                                  accounting.
                                  """
                                  assert self.shutdown == False # dev: shutdown
                                  # Get corresponding amount of assets.
                                  assets: uint256 = self._convert_to_assets(shares, Rounding.ROUND_UP)
                              
                                  assert assets > 0, "cannot deposit zero"
                                  assert assets <= self._max_deposit(recipient), "exceed deposit limit"
                              
                                  # Transfer the tokens to the vault first.
                                  self._erc20_safe_transfer_from(self.asset, msg.sender, self, assets)
                                  # Record the change in total assets.
                                  self.total_idle += assets
                                  
                                  # Issue the corresponding shares for assets.
                                  self._issue_shares(shares, recipient)
                              
                                  log Deposit(sender, recipient, assets, shares)
                                  return assets
                              
                              @view
                              @internal
                              def _assess_share_of_unrealised_losses(strategy: address, assets_needed: uint256) -> uint256:
                                  """
                                  Returns the share of losses that a user would take if withdrawing from this strategy
                                  This accounts for losses that have been realized at the strategy level but not yet
                                  realized at the vault level.
                              
                                  e.g. if the strategy has unrealised losses for 10% of its current debt and the user 
                                  wants to withdraw 1_000 tokens, the losses that they will take is 100 token
                                  """
                                  # Minimum of how much debt the debt should be worth.
                                  strategy_current_debt: uint256 = self.strategies[strategy].current_debt
                                  # The actual amount that the debt is currently worth.
                                  vault_shares: uint256 = IStrategy(strategy).balanceOf(self)
                                  strategy_assets: uint256 = IStrategy(strategy).convertToAssets(vault_shares)
                                  
                                  # If no losses, return 0
                                  if strategy_assets >= strategy_current_debt or strategy_current_debt == 0:
                                      return 0
                              
                                  # Users will withdraw assets_needed divided by loss ratio (strategy_assets / strategy_current_debt - 1).
                                  # NOTE: If there are unrealised losses, the user will take his share.
                                  numerator: uint256 = assets_needed * strategy_assets
                                  users_share_of_loss: uint256 = assets_needed - numerator / strategy_current_debt
                                  # Always round up.
                                  if numerator % strategy_current_debt != 0:
                                      users_share_of_loss += 1
                              
                                  return users_share_of_loss
                              
                              @internal
                              def _withdraw_from_strategy(strategy: address, assets_to_withdraw: uint256):
                                  """
                                  This takes the amount denominated in asset and performs a {redeem}
                                  with the corresponding amount of shares.
                              
                                  We use {redeem} to natively take on losses without additional non-4626 standard parameters.
                                  """
                                  # Need to get shares since we use redeem to be able to take on losses.
                                  shares_to_redeem: uint256 = min(
                                      # Use previewWithdraw since it should round up.
                                      IStrategy(strategy).previewWithdraw(assets_to_withdraw), 
                                      # And check against our actual balance.
                                      IStrategy(strategy).balanceOf(self)
                                  )
                                  # Redeem the shares.
                                  IStrategy(strategy).redeem(shares_to_redeem, self, self)
                              
                              @internal
                              def _redeem(
                                  sender: address, 
                                  receiver: address, 
                                  owner: address,
                                  assets: uint256,
                                  shares: uint256, 
                                  max_loss: uint256,
                                  strategies: DynArray[address, MAX_QUEUE]
                              ) -> uint256:
                                  """
                                  This will attempt to free up the full amount of assets equivalent to
                                  `shares` and transfer them to the `receiver`. If the vault does
                                  not have enough idle funds it will go through any strategies provided by
                                  either the withdrawer or the default_queue to free up enough funds to 
                                  service the request.
                              
                                  The vault will attempt to account for any unrealized losses taken on from
                                  strategies since their respective last reports.
                              
                                  Any losses realized during the withdraw from a strategy will be passed on
                                  to the user that is redeeming their vault shares unless it exceeds the given
                                  `max_loss`.
                                  """
                                  assert receiver != empty(address), "ZERO ADDRESS"
                                  assert shares > 0, "no shares to redeem"
                                  assert assets > 0, "no assets to withdraw"
                                  assert max_loss <= MAX_BPS, "max loss"
                                  
                                  # If there is a withdraw limit module, check the max.
                                  withdraw_limit_module: address = self.withdraw_limit_module
                                  if withdraw_limit_module != empty(address):
                                      assert assets <= IWithdrawLimitModule(withdraw_limit_module).available_withdraw_limit(owner, max_loss, strategies), "exceed withdraw limit"
                              
                                  assert self.balance_of[owner] >= shares, "insufficient shares to redeem"
                                  
                                  if sender != owner:
                                      self._spend_allowance(owner, sender, shares)
                              
                                  # The amount of the underlying token to withdraw.
                                  requested_assets: uint256 = assets
                              
                                  # load to memory to save gas
                                  current_total_idle: uint256 = self.total_idle
                                  _asset: address = self.asset
                              
                                  # If there are not enough assets in the Vault contract, we try to free
                                  # funds from strategies.
                                  if requested_assets > current_total_idle:
                              
                                      # Cache the default queue.
                                      _strategies: DynArray[address, MAX_QUEUE] = self.default_queue
                              
                                      # If a custom queue was passed, and we don't force the default queue.
                                      if len(strategies) != 0 and not self.use_default_queue:
                                          # Use the custom queue.
                                          _strategies = strategies
                              
                                      # load to memory to save gas
                                      current_total_debt: uint256 = self.total_debt
                              
                                      # Withdraw from strategies only what idle doesn't cover.
                                      # `assets_needed` is the total amount we need to fill the request.
                                      assets_needed: uint256 = unsafe_sub(requested_assets, current_total_idle)
                                      # `assets_to_withdraw` is the amount to request from the current strategy.
                                      assets_to_withdraw: uint256 = 0
                              
                                      # To compare against real withdrawals from strategies
                                      previous_balance: uint256 = ERC20(_asset).balanceOf(self)
                              
                                      for strategy in _strategies:
                                          # Make sure we have a valid strategy.
                                          assert self.strategies[strategy].activation != 0, "inactive strategy"
                              
                                          # How much should the strategy have.
                                          current_debt: uint256 = self.strategies[strategy].current_debt
                              
                                          # What is the max amount to withdraw from this strategy.
                                          assets_to_withdraw = min(assets_needed, current_debt)
                              
                                          # Cache max_withdraw now for use if unrealized loss > 0
                                          # Use maxRedeem and convert it since we use redeem.
                                          max_withdraw: uint256 = IStrategy(strategy).convertToAssets(
                                              IStrategy(strategy).maxRedeem(self)
                                          )
                              
                                          # CHECK FOR UNREALISED LOSSES
                                          # If unrealised losses > 0, then the user will take the proportional share 
                                          # and realize it (required to avoid users withdrawing from lossy strategies).
                                          # NOTE: strategies need to manage the fact that realising part of the loss can 
                                          # mean the realisation of 100% of the loss!! (i.e. if for withdrawing 10% of the
                                          # strategy it needs to unwind the whole position, generated losses might be bigger)
                                          unrealised_losses_share: uint256 = self._assess_share_of_unrealised_losses(strategy, assets_to_withdraw)
                                          if unrealised_losses_share > 0:
                                              # If max withdraw is limiting the amount to pull, we need to adjust the portion of 
                                              # the unrealized loss the user should take.
                                              if max_withdraw < assets_to_withdraw - unrealised_losses_share:
                                                  # How much would we want to withdraw
                                                  wanted: uint256 = assets_to_withdraw - unrealised_losses_share
                                                  # Get the proportion of unrealised comparing what we want vs. what we can get
                                                  unrealised_losses_share = unrealised_losses_share * max_withdraw / wanted
                                                  # Adjust assets_to_withdraw so all future calculations work correctly
                                                  assets_to_withdraw = max_withdraw + unrealised_losses_share
                                              
                                              # User now "needs" less assets to be unlocked (as he took some as losses)
                                              assets_to_withdraw -= unrealised_losses_share
                                              requested_assets -= unrealised_losses_share
                                              # NOTE: done here instead of waiting for regular update of these values 
                                              # because it's a rare case (so we can save minor amounts of gas)
                                              assets_needed -= unrealised_losses_share
                                              current_total_debt -= unrealised_losses_share
                              
                                              # If max withdraw is 0 and unrealised loss is still > 0 then the strategy likely
                                              # realized a 100% loss and we will need to realize that loss before moving on.
                                              if max_withdraw == 0 and unrealised_losses_share > 0:
                                                  # Adjust the strategy debt accordingly.
                                                  new_debt: uint256 = current_debt - unrealised_losses_share
                                      
                                                  # Update strategies storage
                                                  self.strategies[strategy].current_debt = new_debt
                                                  # Log the debt update
                                                  log DebtUpdated(strategy, current_debt, new_debt)
                              
                                          # Adjust based on the max withdraw of the strategy.
                                          assets_to_withdraw = min(assets_to_withdraw, max_withdraw)
                              
                                          # Can't withdraw 0.
                                          if assets_to_withdraw == 0:
                                              continue
                                          
                                          # WITHDRAW FROM STRATEGY
                                          self._withdraw_from_strategy(strategy, assets_to_withdraw)
                                          post_balance: uint256 = ERC20(_asset).balanceOf(self)
                                          
                                          # Always check against the real amounts.
                                          withdrawn: uint256 = post_balance - previous_balance
                                          loss: uint256 = 0
                                          # Check if we redeemed too much.
                                          if withdrawn > assets_to_withdraw:
                                              # Make sure we don't underflow in debt updates.
                                              if withdrawn > current_debt:
                                                  # Can't withdraw more than our debt.
                                                  assets_to_withdraw = current_debt
                                              else:
                                                  # Add the extra to how much we withdrew.
                                                  assets_to_withdraw += (unsafe_sub(withdrawn, assets_to_withdraw))
                              
                                          # If we have not received what we expected, we consider the difference a loss.
                                          elif withdrawn < assets_to_withdraw:
                                              loss = unsafe_sub(assets_to_withdraw, withdrawn)
                              
                                          # NOTE: strategy's debt decreases by the full amount but the total idle increases 
                                          # by the actual amount only (as the difference is considered lost).
                                          current_total_idle += (assets_to_withdraw - loss)
                                          requested_assets -= loss
                                          current_total_debt -= assets_to_withdraw
                              
                                          # Vault will reduce debt because the unrealised loss has been taken by user
                                          new_debt: uint256 = current_debt - (assets_to_withdraw + unrealised_losses_share)
                                      
                                          # Update strategies storage
                                          self.strategies[strategy].current_debt = new_debt
                                          # Log the debt update
                                          log DebtUpdated(strategy, current_debt, new_debt)
                              
                                          # Break if we have enough total idle to serve initial request.
                                          if requested_assets <= current_total_idle:
                                              break
                              
                                          # We update the previous_balance variable here to save gas in next iteration.
                                          previous_balance = post_balance
                              
                                          # Reduce what we still need. Safe to use assets_to_withdraw 
                                          # here since it has been checked against requested_assets
                                          assets_needed -= assets_to_withdraw
                              
                                      # If we exhaust the queue and still have insufficient total idle, revert.
                                      assert current_total_idle >= requested_assets, "insufficient assets in vault"
                                      # Commit memory to storage.
                                      self.total_debt = current_total_debt
                              
                                  # Check if there is a loss and a non-default value was set.
                                  if assets > requested_assets and max_loss < MAX_BPS:
                                      # Assure the loss is within the allowed range.
                                      assert assets - requested_assets <= assets * max_loss / MAX_BPS, "too much loss"
                              
                                  # First burn the corresponding shares from the redeemer.
                                  self._burn_shares(shares, owner)
                                  # Commit memory to storage.
                                  self.total_idle = current_total_idle - requested_assets
                                  # Transfer the requested amount to the receiver.
                                  self._erc20_safe_transfer(_asset, receiver, requested_assets)
                              
                                  log Withdraw(sender, receiver, owner, requested_assets, shares)
                                  return requested_assets
                              
                              ## STRATEGY MANAGEMENT ##
                              @internal
                              def _add_strategy(new_strategy: address, add_to_queue: bool):
                                  assert new_strategy not in [self, empty(address)], "strategy cannot be zero address"
                                  assert IStrategy(new_strategy).asset() == self.asset, "invalid asset"
                                  assert self.strategies[new_strategy].activation == 0, "strategy already active"
                              
                                  # Add the new strategy to the mapping.
                                  self.strategies[new_strategy] = StrategyParams({
                                      activation: block.timestamp,
                                      last_report: block.timestamp,
                                      current_debt: 0,
                                      max_debt: 0
                                  })
                              
                                  # If we are adding to the queue and the default queue has space, add the strategy.
                                  if add_to_queue and len(self.default_queue) < MAX_QUEUE:
                                      self.default_queue.append(new_strategy)        
                                      
                                  log StrategyChanged(new_strategy, StrategyChangeType.ADDED)
                              
                              @internal
                              def _revoke_strategy(strategy: address, force: bool=False):
                                  assert self.strategies[strategy].activation != 0, "strategy not active"
                              
                                  # If force revoking a strategy, it will cause a loss.
                                  loss: uint256 = 0
                                  
                                  if self.strategies[strategy].current_debt != 0:
                                      assert force, "strategy has debt"
                                      # Vault realizes the full loss of outstanding debt.
                                      loss = self.strategies[strategy].current_debt
                                      # Adjust total vault debt.
                                      self.total_debt -= loss
                              
                                      log StrategyReported(strategy, 0, loss, 0, 0, 0, 0)
                              
                                  # Set strategy params all back to 0 (WARNING: it can be re-added).
                                  self.strategies[strategy] = StrategyParams({
                                    activation: 0,
                                    last_report: 0,
                                    current_debt: 0,
                                    max_debt: 0
                                  })
                              
                                  # Remove strategy if it is in the default queue.
                                  new_queue: DynArray[address, MAX_QUEUE] = []
                                  for _strategy in self.default_queue:
                                      # Add all strategies to the new queue besides the one revoked.
                                      if _strategy != strategy:
                                          new_queue.append(_strategy)
                                      
                                  # Set the default queue to our updated queue.
                                  self.default_queue = new_queue
                              
                                  log StrategyChanged(strategy, StrategyChangeType.REVOKED)
                              
                              # DEBT MANAGEMENT #
                              @internal
                              def _update_debt(strategy: address, target_debt: uint256, max_loss: uint256) -> uint256:
                                  """
                                  The vault will re-balance the debt vs target debt. Target debt must be
                                  smaller or equal to strategy's max_debt. This function will compare the 
                                  current debt with the target debt and will take funds or deposit new 
                                  funds to the strategy. 
                              
                                  The strategy can require a maximum amount of funds that it wants to receive
                                  to invest. The strategy can also reject freeing funds if they are locked.
                                  """
                                  # How much we want the strategy to have.
                                  new_debt: uint256 = target_debt
                                  # How much the strategy currently has.
                                  current_debt: uint256 = self.strategies[strategy].current_debt
                              
                                  # If the vault is shutdown we can only pull funds.
                                  if self.shutdown:
                                      new_debt = 0
                              
                                  assert new_debt != current_debt, "new debt equals current debt"
                              
                                  if current_debt > new_debt:
                                      # Reduce debt.
                                      assets_to_withdraw: uint256 = unsafe_sub(current_debt, new_debt)
                              
                                      # Ensure we always have minimum_total_idle when updating debt.
                                      minimum_total_idle: uint256 = self.minimum_total_idle
                                      total_idle: uint256 = self.total_idle
                                      
                                      # Respect minimum total idle in vault
                                      if total_idle + assets_to_withdraw < minimum_total_idle:
                                          assets_to_withdraw = unsafe_sub(minimum_total_idle, total_idle)
                                          # Cant withdraw more than the strategy has.
                                          if assets_to_withdraw > current_debt:
                                              assets_to_withdraw = current_debt
                              
                                      # Check how much we are able to withdraw.
                                      # Use maxRedeem and convert since we use redeem.
                                      withdrawable: uint256 = IStrategy(strategy).convertToAssets(
                                          IStrategy(strategy).maxRedeem(self)
                                      )
                                      assert withdrawable != 0, "nothing to withdraw"
                              
                                      # If insufficient withdrawable, withdraw what we can.
                                      if withdrawable < assets_to_withdraw:
                                          assets_to_withdraw = withdrawable
                              
                                      # If there are unrealised losses we don't let the vault reduce its debt until there is a new report
                                      unrealised_losses_share: uint256 = self._assess_share_of_unrealised_losses(strategy, assets_to_withdraw)
                                      assert unrealised_losses_share == 0, "strategy has unrealised losses"
                                      
                                      # Cache for repeated use.
                                      _asset: address = self.asset
                              
                                      # Always check the actual amount withdrawn.
                                      pre_balance: uint256 = ERC20(_asset).balanceOf(self)
                                      self._withdraw_from_strategy(strategy, assets_to_withdraw)
                                      post_balance: uint256 = ERC20(_asset).balanceOf(self)
                                      
                                      # making sure we are changing idle according to the real result no matter what. 
                                      # We pull funds with {redeem} so there can be losses or rounding differences.
                                      withdrawn: uint256 = min(post_balance - pre_balance, current_debt)
                              
                                      # If we didn't get the amount we asked for and there is a max loss.
                                      if withdrawn < assets_to_withdraw and max_loss < MAX_BPS:
                                          # Make sure the loss is within the allowed range.
                                          assert assets_to_withdraw - withdrawn <= assets_to_withdraw * max_loss / MAX_BPS, "too much loss"
                              
                                      # If we got too much make sure not to increase PPS.
                                      elif withdrawn > assets_to_withdraw:
                                          assets_to_withdraw = withdrawn
                              
                                      # Update storage.
                                      self.total_idle += withdrawn # actual amount we got.
                                      # Amount we tried to withdraw in case of losses
                                      self.total_debt -= assets_to_withdraw 
                              
                                      new_debt = current_debt - assets_to_withdraw
                                  else: 
                                      # We are increasing the strategies debt
                              
                                      # Revert if target_debt cannot be achieved due to configured max_debt for given strategy
                                      assert new_debt <= self.strategies[strategy].max_debt, "target debt higher than max debt"
                              
                                      # Vault is increasing debt with the strategy by sending more funds.
                                      max_deposit: uint256 = IStrategy(strategy).maxDeposit(self)
                                      assert max_deposit != 0, "nothing to deposit"
                              
                                      # Deposit the difference between desired and current.
                                      assets_to_deposit: uint256 = new_debt - current_debt
                                      if assets_to_deposit > max_deposit:
                                          # Deposit as much as possible.
                                          assets_to_deposit = max_deposit
                                      
                                      # Ensure we always have minimum_total_idle when updating debt.
                                      minimum_total_idle: uint256 = self.minimum_total_idle
                                      total_idle: uint256 = self.total_idle
                              
                                      assert total_idle > minimum_total_idle, "no funds to deposit"
                                      available_idle: uint256 = unsafe_sub(total_idle, minimum_total_idle)
                              
                                      # If insufficient funds to deposit, transfer only what is free.
                                      if assets_to_deposit > available_idle:
                                          assets_to_deposit = available_idle
                              
                                      # Can't Deposit 0.
                                      if assets_to_deposit > 0:
                                          # Cache for repeated use.
                                          _asset: address = self.asset
                              
                                          # Approve the strategy to pull only what we are giving it.
                                          self._erc20_safe_approve(_asset, strategy, assets_to_deposit)
                              
                                          # Always update based on actual amounts deposited.
                                          pre_balance: uint256 = ERC20(_asset).balanceOf(self)
                                          IStrategy(strategy).deposit(assets_to_deposit, self)
                                          post_balance: uint256 = ERC20(_asset).balanceOf(self)
                              
                                          # Make sure our approval is always back to 0.
                                          self._erc20_safe_approve(_asset, strategy, 0)
                              
                                          # Making sure we are changing according to the real result no 
                                          # matter what. This will spend more gas but makes it more robust.
                                          assets_to_deposit = pre_balance - post_balance
                              
                                          # Update storage.
                                          self.total_idle -= assets_to_deposit
                                          self.total_debt += assets_to_deposit
                              
                                      new_debt = current_debt + assets_to_deposit
                              
                                  # Commit memory to storage.
                                  self.strategies[strategy].current_debt = new_debt
                              
                                  log DebtUpdated(strategy, current_debt, new_debt)
                                  return new_debt
                              
                              ## ACCOUNTING MANAGEMENT ##
                              @internal
                              def _process_report(strategy: address) -> (uint256, uint256):
                                  """
                                  Processing a report means comparing the debt that the strategy has taken 
                                  with the current amount of funds it is reporting. If the strategy owes 
                                  less than it currently has, it means it has had a profit, else (assets < debt) 
                                  it has had a loss.
                              
                                  Different strategies might choose different reporting strategies: pessimistic, 
                                  only realised P&L, ... The best way to report depends on the strategy.
                              
                                  The profit will be distributed following a smooth curve over the vaults 
                                  profit_max_unlock_time seconds. Losses will be taken immediately, first from the 
                                  profit buffer (avoiding an impact in pps), then will reduce pps.
                              
                                  Any applicable fees are charged and distributed during the report as well
                                  to the specified recipients.
                                  """
                                  # Make sure we have a valid strategy.
                                  assert self.strategies[strategy].activation != 0, "inactive strategy"
                              
                                  # Vault assesses profits using 4626 compliant interface. 
                                  # NOTE: It is important that a strategies `convertToAssets` implementation
                                  # cannot be manipulated or else the vault could report incorrect gains/losses.
                                  strategy_shares: uint256 = IStrategy(strategy).balanceOf(self)
                                  # How much the vaults position is worth.
                                  total_assets: uint256 = IStrategy(strategy).convertToAssets(strategy_shares)
                                  # How much the vault had deposited to the strategy.
                                  current_debt: uint256 = self.strategies[strategy].current_debt
                              
                                  gain: uint256 = 0
                                  loss: uint256 = 0
                              
                                  ### Asses Gain or Loss ###
                              
                                  # Compare reported assets vs. the current debt.
                                  if total_assets > current_debt:
                                      # We have a gain.
                                      gain = unsafe_sub(total_assets, current_debt)
                                  else:
                                      # We have a loss.
                                      loss = unsafe_sub(current_debt, total_assets)
                                  
                                  # Cache `asset` for repeated use.
                                  _asset: address = self.asset
                              
                                  ### Asses Fees and Refunds ###
                              
                                  # For Accountant fee assessment.
                                  total_fees: uint256 = 0
                                  total_refunds: uint256 = 0
                                  # If accountant is not set, fees and refunds remain unchanged.
                                  accountant: address = self.accountant
                                  if accountant != empty(address):
                                      total_fees, total_refunds = IAccountant(accountant).report(strategy, gain, loss)
                              
                                      if total_refunds > 0:
                                          # Make sure we have enough approval and enough asset to pull.
                                          total_refunds = min(total_refunds, min(ERC20(_asset).balanceOf(accountant), ERC20(_asset).allowance(accountant, self)))
                              
                                  # Total fees to charge in shares.
                                  total_fees_shares: uint256 = 0
                                  # For Protocol fee assessment.
                                  protocol_fee_bps: uint16 = 0
                                  protocol_fees_shares: uint256 = 0
                                  protocol_fee_recipient: address = empty(address)
                                  # `shares_to_burn` is derived from amounts that would reduce the vaults PPS.
                                  # NOTE: this needs to be done before any pps changes
                                  shares_to_burn: uint256 = 0
                                  # Only need to burn shares if there is a loss or fees.
                                  if loss + total_fees > 0:
                                      # The amount of shares we will want to burn to offset losses and fees.
                                      shares_to_burn = self._convert_to_shares(loss + total_fees, Rounding.ROUND_UP)
                              
                                      # If we have fees then get the proportional amount of shares to issue.
                                      if total_fees > 0:
                                          # Get the total amount shares to issue for the fees.
                                          total_fees_shares = shares_to_burn * total_fees / (loss + total_fees)
                              
                                          # Get the protocol fee config for this vault.
                                          protocol_fee_bps, protocol_fee_recipient = IFactory(self.factory).protocol_fee_config()
                              
                                          # If there is a protocol fee.
                                          if protocol_fee_bps > 0:
                                              # Get the percent of fees to go to protocol fees.
                                              protocol_fees_shares = total_fees_shares * convert(protocol_fee_bps, uint256) / MAX_BPS
                              
                              
                                  # Shares to lock is any amount that would otherwise increase the vaults PPS.
                                  shares_to_lock: uint256 = 0
                                  profit_max_unlock_time: uint256 = self.profit_max_unlock_time
                                  # Get the amount we will lock to avoid a PPS increase.
                                  if gain + total_refunds > 0 and profit_max_unlock_time != 0:
                                      shares_to_lock = self._convert_to_shares(gain + total_refunds, Rounding.ROUND_DOWN)
                              
                                  # The total current supply including locked shares.
                                  total_supply: uint256 = self.total_supply
                                  # The total shares the vault currently owns. Both locked and unlocked.
                                  total_locked_shares: uint256 = self.balance_of[self]
                                  # Get the desired end amount of shares after all accounting.
                                  ending_supply: uint256 = total_supply + shares_to_lock - shares_to_burn - self._unlocked_shares()
                                  
                                  # If we will end with more shares than we have now.
                                  if ending_supply > total_supply:
                                      # Issue the difference.
                                      self._issue_shares(unsafe_sub(ending_supply, total_supply), self)
                              
                                  # Else we need to burn shares.
                                  elif total_supply > ending_supply:
                                      # Can't burn more than the vault owns.
                                      to_burn: uint256 = min(unsafe_sub(total_supply, ending_supply), total_locked_shares)
                                      self._burn_shares(to_burn, self)
                              
                                  # Adjust the amount to lock for this period.
                                  if shares_to_lock > shares_to_burn:
                                      # Don't lock fees or losses.
                                      shares_to_lock = unsafe_sub(shares_to_lock, shares_to_burn)
                                  else:
                                      shares_to_lock = 0
                              
                                  # Pull refunds
                                  if total_refunds > 0:
                                      # Transfer the refunded amount of asset to the vault.
                                      self._erc20_safe_transfer_from(_asset, accountant, self, total_refunds)
                                      # Update storage to increase total assets.
                                      self.total_idle += total_refunds
                              
                                  # Record any reported gains.
                                  if gain > 0:
                                      # NOTE: this will increase total_assets
                                      current_debt = unsafe_add(current_debt, gain)
                                      self.strategies[strategy].current_debt = current_debt
                                      self.total_debt += gain
                              
                                  # Or record any reported loss
                                  elif loss > 0:
                                      current_debt = unsafe_sub(current_debt, loss)
                                      self.strategies[strategy].current_debt = current_debt
                                      self.total_debt -= loss
                              
                                  # Issue shares for fees that were calculated above if applicable.
                                  if total_fees_shares > 0:
                                      # Accountant fees are (total_fees - protocol_fees).
                                      self._issue_shares(total_fees_shares - protocol_fees_shares, accountant)
                              
                                      # If we also have protocol fees.
                                      if protocol_fees_shares > 0:
                                          self._issue_shares(protocol_fees_shares, protocol_fee_recipient)
                              
                                  # Update unlocking rate and time to fully unlocked.
                                  total_locked_shares = self.balance_of[self]
                                  if total_locked_shares > 0:
                                      previously_locked_time: uint256 = 0
                                      _full_profit_unlock_date: uint256 = self.full_profit_unlock_date
                                      # Check if we need to account for shares still unlocking.
                                      if _full_profit_unlock_date > block.timestamp: 
                                          # There will only be previously locked shares if time remains.
                                          # We calculate this here since it will not occur every time we lock shares.
                                          previously_locked_time = (total_locked_shares - shares_to_lock) * (_full_profit_unlock_date - block.timestamp)
                              
                                      # new_profit_locking_period is a weighted average between the remaining time of the previously locked shares and the profit_max_unlock_time
                                      new_profit_locking_period: uint256 = (previously_locked_time + shares_to_lock * profit_max_unlock_time) / total_locked_shares
                                      # Calculate how many shares unlock per second.
                                      self.profit_unlocking_rate = total_locked_shares * MAX_BPS_EXTENDED / new_profit_locking_period
                                      # Calculate how long until the full amount of shares is unlocked.
                                      self.full_profit_unlock_date = block.timestamp + new_profit_locking_period
                                      # Update the last profitable report timestamp.
                                      self.last_profit_update = block.timestamp
                                  else:
                                      # NOTE: only setting this to the 0 will turn in the desired effect, 
                                      # no need to update profit_unlocking_rate
                                      self.full_profit_unlock_date = 0
                                  
                                  # Record the report of profit timestamp.
                                  self.strategies[strategy].last_report = block.timestamp
                              
                                  # We have to recalculate the fees paid for cases with an overall loss or no profit locking
                                  if loss + total_fees > gain + total_refunds or profit_max_unlock_time == 0:
                                      total_fees = self._convert_to_assets(total_fees_shares, Rounding.ROUND_DOWN)
                              
                                  log StrategyReported(
                                      strategy,
                                      gain,
                                      loss,
                                      current_debt,
                                      total_fees * convert(protocol_fee_bps, uint256) / MAX_BPS, # Protocol Fees
                                      total_fees,
                                      total_refunds
                                  )
                              
                                  return (gain, loss)
                              
                              # SETTERS #
                              @external
                              def set_accountant(new_accountant: address):
                                  """
                                  @notice Set the new accountant address.
                                  @param new_accountant The new accountant address.
                                  """
                                  self._enforce_role(msg.sender, Roles.ACCOUNTANT_MANAGER)
                                  self.accountant = new_accountant
                              
                                  log UpdateAccountant(new_accountant)
                              
                              @external
                              def set_default_queue(new_default_queue: DynArray[address, MAX_QUEUE]):
                                  """
                                  @notice Set the new default queue array.
                                  @dev Will check each strategy to make sure it is active. But will not
                                      check that the same strategy is not added twice. maxRedeem and maxWithdraw
                                      return values may be inaccurate if a strategy is added twice.
                                  @param new_default_queue The new default queue array.
                                  """
                                  self._enforce_role(msg.sender, Roles.QUEUE_MANAGER)
                              
                                  # Make sure every strategy in the new queue is active.
                                  for strategy in new_default_queue:
                                      assert self.strategies[strategy].activation != 0, "!inactive"
                              
                                  # Save the new queue.
                                  self.default_queue = new_default_queue
                              
                                  log UpdateDefaultQueue(new_default_queue)
                              
                              @external
                              def set_use_default_queue(use_default_queue: bool):
                                  """
                                  @notice Set a new value for `use_default_queue`.
                                  @dev If set `True` the default queue will always be
                                      used no matter whats passed in.
                                  @param use_default_queue new value.
                                  """
                                  self._enforce_role(msg.sender, Roles.QUEUE_MANAGER)
                                  self.use_default_queue = use_default_queue
                              
                                  log UpdateUseDefaultQueue(use_default_queue)
                              
                              @external
                              def set_deposit_limit(deposit_limit: uint256, override: bool = False):
                                  """
                                  @notice Set the new deposit limit.
                                  @dev Can not be changed if a deposit_limit_module
                                  is set unless the override flag is true or if shutdown.
                                  @param deposit_limit The new deposit limit.
                                  @param override If a `deposit_limit_module` already set should be overridden.
                                  """
                                  assert self.shutdown == False # Dev: shutdown
                                  self._enforce_role(msg.sender, Roles.DEPOSIT_LIMIT_MANAGER)
                              
                                  # If we are overriding the deposit limit module.
                                  if override:
                                      # Make sure it is set to address 0 if not already.
                                      if self.deposit_limit_module != empty(address):
                              
                                          self.deposit_limit_module = empty(address)
                                          log UpdateDepositLimitModule(empty(address))
                                  else:  
                                      # Make sure the deposit_limit_module has been set to address(0).
                                      assert self.deposit_limit_module == empty(address), "using module"
                              
                                  self.deposit_limit = deposit_limit
                              
                                  log UpdateDepositLimit(deposit_limit)
                              
                              @external
                              def set_deposit_limit_module(deposit_limit_module: address, override: bool = False):
                                  """
                                  @notice Set a contract to handle the deposit limit.
                                  @dev The default `deposit_limit` will need to be set to
                                  max uint256 since the module will override it or the override flag
                                  must be set to true to set it to max in 1 tx..
                                  @param deposit_limit_module Address of the module.
                                  @param override If a `deposit_limit` already set should be overridden.
                                  """
                                  assert self.shutdown == False # Dev: shutdown
                                  self._enforce_role(msg.sender, Roles.DEPOSIT_LIMIT_MANAGER)
                              
                                  # If we are overriding the deposit limit
                                  if override:
                                      # Make sure it is max uint256 if not already.
                                      if self.deposit_limit != max_value(uint256):
                              
                                          self.deposit_limit = max_value(uint256)
                                          log UpdateDepositLimit(max_value(uint256))
                                  else:
                                      # Make sure the deposit_limit has been set to uint max.
                                      assert self.deposit_limit == max_value(uint256), "using deposit limit"
                              
                                  self.deposit_limit_module = deposit_limit_module
                              
                                  log UpdateDepositLimitModule(deposit_limit_module)
                              
                              @external
                              def set_withdraw_limit_module(withdraw_limit_module: address):
                                  """
                                  @notice Set a contract to handle the withdraw limit.
                                  @dev This will override the default `max_withdraw`.
                                  @param withdraw_limit_module Address of the module.
                                  """
                                  self._enforce_role(msg.sender, Roles.WITHDRAW_LIMIT_MANAGER)
                              
                                  self.withdraw_limit_module = withdraw_limit_module
                              
                                  log UpdateWithdrawLimitModule(withdraw_limit_module)
                              
                              @external
                              def set_minimum_total_idle(minimum_total_idle: uint256):
                                  """
                                  @notice Set the new minimum total idle.
                                  @param minimum_total_idle The new minimum total idle.
                                  """
                                  self._enforce_role(msg.sender, Roles.MINIMUM_IDLE_MANAGER)
                                  self.minimum_total_idle = minimum_total_idle
                              
                                  log UpdateMinimumTotalIdle(minimum_total_idle)
                              
                              @external
                              def setProfitMaxUnlockTime(new_profit_max_unlock_time: uint256):
                                  """
                                  @notice Set the new profit max unlock time.
                                  @dev The time is denominated in seconds and must be less than 1 year.
                                      We only need to update locking period if setting to 0,
                                      since the current period will use the old rate and on the next
                                      report it will be reset with the new unlocking time.
                                  
                                      Setting to 0 will cause any currently locked profit to instantly
                                      unlock and an immediate increase in the vaults Price Per Share.
                              
                                  @param new_profit_max_unlock_time The new profit max unlock time.
                                  """
                                  self._enforce_role(msg.sender, Roles.PROFIT_UNLOCK_MANAGER)
                                  # Must be less than one year for report cycles
                                  assert new_profit_max_unlock_time <= 31_556_952, "profit unlock time too long"
                              
                                  # If setting to 0 we need to reset any locked values.
                                  if (new_profit_max_unlock_time == 0):
                              
                                      share_balance: uint256 = self.balance_of[self]
                                      if share_balance > 0:
                                          # Burn any shares the vault still has.
                                          self._burn_shares(share_balance, self)
                              
                                      # Reset unlocking variables to 0.
                                      self.profit_unlocking_rate = 0
                                      self.full_profit_unlock_date = 0
                              
                                  self.profit_max_unlock_time = new_profit_max_unlock_time
                              
                                  log UpdateProfitMaxUnlockTime(new_profit_max_unlock_time)
                              
                              # ROLE MANAGEMENT #
                              @internal
                              def _enforce_role(account: address, role: Roles):
                                  # Make sure the sender holds the role.
                                  assert role in self.roles[account], "not allowed"
                              
                              @external
                              def set_role(account: address, role: Roles):
                                  """
                                  @notice Set the roles for an account.
                                  @dev This will fully override an accounts current roles
                                   so it should include all roles the account should hold.
                                  @param account The account to set the role for.
                                  @param role The roles the account should hold.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.roles[account] = role
                              
                                  log RoleSet(account, role)
                              
                              @external
                              def add_role(account: address, role: Roles):
                                  """
                                  @notice Add a new role to an address.
                                  @dev This will add a new role to the account
                                   without effecting any of the previously held roles.
                                  @param account The account to add a role to.
                                  @param role The new role to add to account.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.roles[account] = self.roles[account] | role
                              
                                  log RoleSet(account, self.roles[account])
                              
                              @external
                              def remove_role(account: address, role: Roles):
                                  """
                                  @notice Remove a single role from an account.
                                  @dev This will leave all other roles for the 
                                   account unchanged.
                                  @param account The account to remove a Role from.
                                  @param role The Role to remove.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.roles[account] = self.roles[account] & ~role
                              
                                  log RoleSet(account, self.roles[account])
                                  
                              @external
                              def transfer_role_manager(role_manager: address):
                                  """
                                  @notice Step 1 of 2 in order to transfer the 
                                      role manager to a new address. This will set
                                      the future_role_manager. Which will then need
                                      to be accepted by the new manager.
                                  @param role_manager The new role manager address.
                                  """
                                  assert msg.sender == self.role_manager
                                  self.future_role_manager = role_manager
                              
                              @external
                              def accept_role_manager():
                                  """
                                  @notice Accept the role manager transfer.
                                  """
                                  assert msg.sender == self.future_role_manager
                                  self.role_manager = msg.sender
                                  self.future_role_manager = empty(address)
                              
                                  log UpdateRoleManager(msg.sender)
                              
                              # VAULT STATUS VIEWS
                              
                              @view
                              @external
                              def isShutdown() -> bool:
                                  """
                                  @notice Get if the vault is shutdown.
                                  @return Bool representing the shutdown status
                                  """
                                  return self.shutdown
                              @view
                              @external
                              def unlockedShares() -> uint256:
                                  """
                                  @notice Get the amount of shares that have been unlocked.
                                  @return The amount of shares that are have been unlocked.
                                  """
                                  return self._unlocked_shares()
                              
                              @view
                              @external
                              def pricePerShare() -> uint256:
                                  """
                                  @notice Get the price per share (pps) of the vault.
                                  @dev This value offers limited precision. Integrations that require 
                                      exact precision should use convertToAssets or convertToShares instead.
                                  @return The price per share.
                                  """
                                  return self._convert_to_assets(10 ** convert(self.decimals, uint256), Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def get_default_queue() -> DynArray[address, MAX_QUEUE]:
                                  """
                                  @notice Get the full default queue currently set.
                                  @return The current default withdrawal queue.
                                  """
                                  return self.default_queue
                              
                              ## REPORTING MANAGEMENT ##
                              @external
                              @nonreentrant("lock")
                              def process_report(strategy: address) -> (uint256, uint256):
                                  """
                                  @notice Process the report of a strategy.
                                  @param strategy The strategy to process the report for.
                                  @return The gain and loss of the strategy.
                                  """
                                  self._enforce_role(msg.sender, Roles.REPORTING_MANAGER)
                                  return self._process_report(strategy)
                              
                              @external
                              @nonreentrant("lock")
                              def buy_debt(strategy: address, amount: uint256):
                                  """
                                  @notice Used for governance to buy bad debt from the vault.
                                  @dev This should only ever be used in an emergency in place
                                  of force revoking a strategy in order to not report a loss.
                                  It allows the DEBT_PURCHASER role to buy the strategies debt
                                  for an equal amount of `asset`. 
                              
                                  @param strategy The strategy to buy the debt for
                                  @param amount The amount of debt to buy from the vault.
                                  """
                                  self._enforce_role(msg.sender, Roles.DEBT_PURCHASER)
                                  assert self.strategies[strategy].activation != 0, "not active"
                                  
                                  # Cache the current debt.
                                  current_debt: uint256 = self.strategies[strategy].current_debt
                                  _amount: uint256 = amount
                              
                                  assert current_debt > 0, "nothing to buy"
                                  assert _amount > 0, "nothing to buy with"
                                  
                                  if _amount > current_debt:
                                      _amount = current_debt
                              
                                  # We get the proportion of the debt that is being bought and
                                  # transfer the equivalent shares. We assume this is being used
                                  # due to strategy issues so won't rely on its conversion rates.
                                  shares: uint256 = IStrategy(strategy).balanceOf(self) * _amount / current_debt
                              
                                  assert shares > 0, "cannot buy zero"
                              
                                  self._erc20_safe_transfer_from(self.asset, msg.sender, self, _amount)
                              
                                  # Lower strategy debt
                                  self.strategies[strategy].current_debt -= _amount
                                  # lower total debt
                                  self.total_debt -= _amount
                                  # Increase total idle
                                  self.total_idle += _amount
                              
                                  # log debt change
                                  log DebtUpdated(strategy, current_debt, current_debt - _amount)
                              
                                  # Transfer the strategies shares out.
                                  self._erc20_safe_transfer(strategy, msg.sender, shares)
                              
                                  log DebtPurchased(strategy, _amount)
                              
                              ## STRATEGY MANAGEMENT ##
                              @external
                              def add_strategy(new_strategy: address, add_to_queue: bool=True):
                                  """
                                  @notice Add a new strategy.
                                  @param new_strategy The new strategy to add.
                                  """
                                  self._enforce_role(msg.sender, Roles.ADD_STRATEGY_MANAGER)
                                  self._add_strategy(new_strategy, add_to_queue)
                              
                              @external
                              def revoke_strategy(strategy: address):
                                  """
                                  @notice Revoke a strategy.
                                  @param strategy The strategy to revoke.
                                  """
                                  self._enforce_role(msg.sender, Roles.REVOKE_STRATEGY_MANAGER)
                                  self._revoke_strategy(strategy)
                              
                              @external
                              def force_revoke_strategy(strategy: address):
                                  """
                                  @notice Force revoke a strategy.
                                  @dev The vault will remove the strategy and write off any debt left 
                                      in it as a loss. This function is a dangerous function as it can force a 
                                      strategy to take a loss. All possible assets should be removed from the 
                                      strategy first via update_debt. If a strategy is removed erroneously it 
                                      can be re-added and the loss will be credited as profit. Fees will apply.
                                  @param strategy The strategy to force revoke.
                                  """
                                  self._enforce_role(msg.sender, Roles.FORCE_REVOKE_MANAGER)
                                  self._revoke_strategy(strategy, True)
                              
                              ## DEBT MANAGEMENT ##
                              @external
                              def update_max_debt_for_strategy(strategy: address, new_max_debt: uint256):
                                  """
                                  @notice Update the max debt for a strategy.
                                  @param strategy The strategy to update the max debt for.
                                  @param new_max_debt The new max debt for the strategy.
                                  """
                                  self._enforce_role(msg.sender, Roles.MAX_DEBT_MANAGER)
                                  assert self.strategies[strategy].activation != 0, "inactive strategy"
                                  self.strategies[strategy].max_debt = new_max_debt
                              
                                  log UpdatedMaxDebtForStrategy(msg.sender, strategy, new_max_debt)
                              
                              @external
                              @nonreentrant("lock")
                              def update_debt(
                                  strategy: address, 
                                  target_debt: uint256, 
                                  max_loss: uint256 = MAX_BPS
                              ) -> uint256:
                                  """
                                  @notice Update the debt for a strategy.
                                  @param strategy The strategy to update the debt for.
                                  @param target_debt The target debt for the strategy.
                                  @param max_loss Optional to check realized losses on debt decreases.
                                  @return The amount of debt added or removed.
                                  """
                                  self._enforce_role(msg.sender, Roles.DEBT_MANAGER)
                                  return self._update_debt(strategy, target_debt, max_loss)
                              
                              ## EMERGENCY MANAGEMENT ##
                              @external
                              def shutdown_vault():
                                  """
                                  @notice Shutdown the vault.
                                  """
                                  self._enforce_role(msg.sender, Roles.EMERGENCY_MANAGER)
                                  assert self.shutdown == False
                                  
                                  # Shutdown the vault.
                                  self.shutdown = True
                              
                                  # Set deposit limit to 0.
                                  if self.deposit_limit_module != empty(address):
                                      self.deposit_limit_module = empty(address)
                              
                                      log UpdateDepositLimitModule(empty(address))
                              
                                  self.deposit_limit = 0
                                  log UpdateDepositLimit(0)
                              
                                  self.roles[msg.sender] = self.roles[msg.sender] | Roles.DEBT_MANAGER
                                  log Shutdown()
                              
                              
                              ## SHARE MANAGEMENT ##
                              ## ERC20 + ERC4626 ##
                              @external
                              @nonreentrant("lock")
                              def deposit(assets: uint256, receiver: address) -> uint256:
                                  """
                                  @notice Deposit assets into the vault.
                                  @param assets The amount of assets to deposit.
                                  @param receiver The address to receive the shares.
                                  @return The amount of shares minted.
                                  """
                                  return self._deposit(msg.sender, receiver, assets)
                              
                              @external
                              @nonreentrant("lock")
                              def mint(shares: uint256, receiver: address) -> uint256:
                                  """
                                  @notice Mint shares for the receiver.
                                  @param shares The amount of shares to mint.
                                  @param receiver The address to receive the shares.
                                  @return The amount of assets deposited.
                                  """
                                  return self._mint(msg.sender, receiver, shares)
                              
                              @external
                              @nonreentrant("lock")
                              def withdraw(
                                  assets: uint256, 
                                  receiver: address, 
                                  owner: address, 
                                  max_loss: uint256 = 0,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Withdraw an amount of asset to `receiver` burning `owner`s shares.
                                  @dev The default behavior is to not allow any loss.
                                  @param assets The amount of asset to withdraw.
                                  @param receiver The address to receive the assets.
                                  @param owner The address who's shares are being burnt.
                                  @param max_loss Optional amount of acceptable loss in Basis Points.
                                  @param strategies Optional array of strategies to withdraw from.
                                  @return The amount of shares actually burnt.
                                  """
                                  shares: uint256 = self._convert_to_shares(assets, Rounding.ROUND_UP)
                                  self._redeem(msg.sender, receiver, owner, assets, shares, max_loss, strategies)
                                  return shares
                              
                              @external
                              @nonreentrant("lock")
                              def redeem(
                                  shares: uint256, 
                                  receiver: address, 
                                  owner: address, 
                                  max_loss: uint256 = MAX_BPS,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Redeems an amount of shares of `owners` shares sending funds to `receiver`.
                                  @dev The default behavior is to allow losses to be realized.
                                  @param shares The amount of shares to burn.
                                  @param receiver The address to receive the assets.
                                  @param owner The address who's shares are being burnt.
                                  @param max_loss Optional amount of acceptable loss in Basis Points.
                                  @param strategies Optional array of strategies to withdraw from.
                                  @return The amount of assets actually withdrawn.
                                  """
                                  assets: uint256 = self._convert_to_assets(shares, Rounding.ROUND_DOWN)
                                  # Always return the actual amount of assets withdrawn.
                                  return self._redeem(msg.sender, receiver, owner, assets, shares, max_loss, strategies)
                              
                              
                              @external
                              def approve(spender: address, amount: uint256) -> bool:
                                  """
                                  @notice Approve an address to spend the vault's shares.
                                  @param spender The address to approve.
                                  @param amount The amount of shares to approve.
                                  @return True if the approval was successful.
                                  """
                                  return self._approve(msg.sender, spender, amount)
                              
                              @external
                              def transfer(receiver: address, amount: uint256) -> bool:
                                  """
                                  @notice Transfer shares to a receiver.
                                  @param receiver The address to transfer shares to.
                                  @param amount The amount of shares to transfer.
                                  @return True if the transfer was successful.
                                  """
                                  assert receiver not in [self, empty(address)]
                                  self._transfer(msg.sender, receiver, amount)
                                  return True
                              
                              @external
                              def transferFrom(sender: address, receiver: address, amount: uint256) -> bool:
                                  """
                                  @notice Transfer shares from a sender to a receiver.
                                  @param sender The address to transfer shares from.
                                  @param receiver The address to transfer shares to.
                                  @param amount The amount of shares to transfer.
                                  @return True if the transfer was successful.
                                  """
                                  assert receiver not in [self, empty(address)]
                                  return self._transfer_from(sender, receiver, amount)
                              
                              ## ERC20+4626 compatibility
                              @external
                              def permit(
                                  owner: address, 
                                  spender: address, 
                                  amount: uint256, 
                                  deadline: uint256, 
                                  v: uint8, 
                                  r: bytes32, 
                                  s: bytes32
                              ) -> bool:
                                  """
                                  @notice Approve an address to spend the vault's shares.
                                  @param owner The address to approve.
                                  @param spender The address to approve.
                                  @param amount The amount of shares to approve.
                                  @param deadline The deadline for the permit.
                                  @param v The v component of the signature.
                                  @param r The r component of the signature.
                                  @param s The s component of the signature.
                                  @return True if the approval was successful.
                                  """
                                  return self._permit(owner, spender, amount, deadline, v, r, s)
                              
                              @view
                              @external
                              def balanceOf(addr: address) -> uint256:
                                  """
                                  @notice Get the balance of a user.
                                  @param addr The address to get the balance of.
                                  @return The balance of the user.
                                  """
                                  if(addr == self):
                                      # If the address is the vault, account for locked shares.
                                      return self.balance_of[addr] - self._unlocked_shares()
                              
                                  return self.balance_of[addr]
                              
                              @view
                              @external
                              def totalSupply() -> uint256:
                                  """
                                  @notice Get the total supply of shares.
                                  @return The total supply of shares.
                                  """
                                  return self._total_supply()
                              
                              @view
                              @external
                              def totalAssets() -> uint256:
                                  """
                                  @notice Get the total assets held by the vault.
                                  @return The total assets held by the vault.
                                  """
                                  return self._total_assets()
                              
                              @view
                              @external
                              def totalIdle() -> uint256:
                                  """
                                  @notice Get the amount of loose `asset` the vault holds.
                                  @return The current total idle.
                                  """
                                  return self.total_idle
                              
                              @view
                              @external
                              def totalDebt() -> uint256:
                                  """
                                  @notice Get the the total amount of funds invested
                                  across all strategies.
                                  @return The current total debt.
                                  """
                                  return self.total_debt
                              
                              @view
                              @external
                              def convertToShares(assets: uint256) -> uint256:
                                  """
                                  @notice Convert an amount of assets to shares.
                                  @param assets The amount of assets to convert.
                                  @return The amount of shares.
                                  """
                                  return self._convert_to_shares(assets, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def previewDeposit(assets: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of shares that would be minted for a deposit.
                                  @param assets The amount of assets to deposit.
                                  @return The amount of shares that would be minted.
                                  """
                                  return self._convert_to_shares(assets, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def previewMint(shares: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of assets that would be deposited for a mint.
                                  @param shares The amount of shares to mint.
                                  @return The amount of assets that would be deposited.
                                  """
                                  return self._convert_to_assets(shares, Rounding.ROUND_UP)
                              
                              @view
                              @external
                              def convertToAssets(shares: uint256) -> uint256:
                                  """
                                  @notice Convert an amount of shares to assets.
                                  @param shares The amount of shares to convert.
                                  @return The amount of assets.
                                  """
                                  return self._convert_to_assets(shares, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def maxDeposit(receiver: address) -> uint256:
                                  """
                                  @notice Get the maximum amount of assets that can be deposited.
                                  @param receiver The address that will receive the shares.
                                  @return The maximum amount of assets that can be deposited.
                                  """
                                  return self._max_deposit(receiver)
                              
                              @view
                              @external
                              def maxMint(receiver: address) -> uint256:
                                  """
                                  @notice Get the maximum amount of shares that can be minted.
                                  @param receiver The address that will receive the shares.
                                  @return The maximum amount of shares that can be minted.
                                  """
                                  max_deposit: uint256 = self._max_deposit(receiver)
                                  return self._convert_to_shares(max_deposit, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def maxWithdraw(
                                  owner: address,
                                  max_loss: uint256 = 0,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Get the maximum amount of assets that can be withdrawn.
                                  @dev Complies to normal 4626 interface and takes custom params.
                                  NOTE: Passing in a incorrectly ordered queue may result in
                                   incorrect returns values.
                                  @param owner The address that owns the shares.
                                  @param max_loss Custom max_loss if any.
                                  @param strategies Custom strategies queue if any.
                                  @return The maximum amount of assets that can be withdrawn.
                                  """
                                  return self._max_withdraw(owner, max_loss, strategies)
                              
                              @view
                              @external
                              def maxRedeem(
                                  owner: address,
                                  max_loss: uint256 = MAX_BPS,
                                  strategies: DynArray[address, MAX_QUEUE] = []
                              ) -> uint256:
                                  """
                                  @notice Get the maximum amount of shares that can be redeemed.
                                  @dev Complies to normal 4626 interface and takes custom params.
                                  NOTE: Passing in a incorrectly ordered queue may result in
                                   incorrect returns values.
                                  @param owner The address that owns the shares.
                                  @param max_loss Custom max_loss if any.
                                  @param strategies Custom strategies queue if any.
                                  @return The maximum amount of shares that can be redeemed.
                                  """
                                  return min(
                                      # Min of the shares equivalent of max_withdraw or the full balance
                                      self._convert_to_shares(self._max_withdraw(owner, max_loss, strategies), Rounding.ROUND_DOWN),
                                      self.balance_of[owner]
                                  )
                              
                              @view
                              @external
                              def previewWithdraw(assets: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of shares that would be redeemed for a withdraw.
                                  @param assets The amount of assets to withdraw.
                                  @return The amount of shares that would be redeemed.
                                  """
                                  return self._convert_to_shares(assets, Rounding.ROUND_UP)
                              
                              @view
                              @external
                              def previewRedeem(shares: uint256) -> uint256:
                                  """
                                  @notice Preview the amount of assets that would be withdrawn for a redeem.
                                  @param shares The amount of shares to redeem.
                                  @return The amount of assets that would be withdrawn.
                                  """
                                  return self._convert_to_assets(shares, Rounding.ROUND_DOWN)
                              
                              @view
                              @external
                              def FACTORY() -> address:
                                  """
                                  @notice Address of the factory that deployed the vault.
                                  @dev Is used to retrieve the protocol fees.
                                  @return Address of the vault factory.
                                  """
                                  return self.factory
                              
                              @view
                              @external
                              def apiVersion() -> String[28]:
                                  """
                                  @notice Get the API version of the vault.
                                  @return The API version of the vault.
                                  """
                                  return API_VERSION
                              
                              @view
                              @external
                              def assess_share_of_unrealised_losses(strategy: address, assets_needed: uint256) -> uint256:
                                  """
                                  @notice Assess the share of unrealised losses that a strategy has.
                                  @param strategy The address of the strategy.
                                  @param assets_needed The amount of assets needed to be withdrawn.
                                  @return The share of unrealised losses that the strategy has.
                                  """
                                  assert self.strategies[strategy].current_debt >= assets_needed
                              
                                  return self._assess_share_of_unrealised_losses(strategy, assets_needed)
                              
                              ## Profit locking getter functions ##
                              
                              @view
                              @external
                              def profitMaxUnlockTime() -> uint256:
                                  """
                                  @notice Gets the current time profits are set to unlock over.
                                  @return The current profit max unlock time.
                                  """
                                  return self.profit_max_unlock_time
                              
                              @view
                              @external
                              def fullProfitUnlockDate() -> uint256:
                                  """
                                  @notice Gets the timestamp at which all profits will be unlocked.
                                  @return The full profit unlocking timestamp
                                  """
                                  return self.full_profit_unlock_date
                              
                              @view
                              @external
                              def profitUnlockingRate() -> uint256:
                                  """
                                  @notice The per second rate at which profits are unlocking.
                                  @dev This is denominated in EXTENDED_BPS decimals.
                                  @return The current profit unlocking rate.
                                  """
                                  return self.profit_unlocking_rate
                              
                              
                              @view
                              @external
                              def lastProfitUpdate() -> uint256:
                                  """
                                  @notice The timestamp of the last time shares were locked.
                                  @return The last profit update.
                                  """
                                  return self.last_profit_update
                              
                              # eip-1344
                              @view
                              @internal
                              def domain_separator() -> bytes32:
                                  return keccak256(
                                      concat(
                                          DOMAIN_TYPE_HASH,
                                          keccak256(convert("Yearn Vault", Bytes[11])),
                                          keccak256(convert(API_VERSION, Bytes[28])),
                                          convert(chain.id, bytes32),
                                          convert(self, bytes32)
                                      )
                                  )
                              
                              @view
                              @external
                              def DOMAIN_SEPARATOR() -> bytes32:
                                  """
                                  @notice Get the domain separator.
                                  @return The domain separator.
                                  """
                                  return self.domain_separator()

                              File 10 of 11: TokenizedStrategy
                              // SPDX-License-Identifier: AGPL-3.0
                              pragma solidity >=0.8.18 ^0.8.0 ^0.8.1;
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
                              
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                              
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                              
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                              
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `to`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address to, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                              
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                              
                                  /**
                                   * @dev Moves `amount` tokens from `from` to `to` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address from, address to, uint256 amount) external returns (bool);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
                              
                              /**
                               * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
                               * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
                               *
                               * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
                               * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
                               * need to send a transaction, and thus is not required to hold Ether at all.
                               *
                               * ==== Security Considerations
                               *
                               * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
                               * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
                               * considered as an intention to spend the allowance in any specific way. The second is that because permits have
                               * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
                               * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
                               * generally recommended is:
                               *
                               * ```solidity
                               * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
                               *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
                               *     doThing(..., value);
                               * }
                               *
                               * function doThing(..., uint256 value) public {
                               *     token.safeTransferFrom(msg.sender, address(this), value);
                               *     ...
                               * }
                               * ```
                               *
                               * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
                               * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
                               * {SafeERC20-safeTransferFrom}).
                               *
                               * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
                               * contracts should have entry points that don't rely on permit.
                               */
                              interface IERC20Permit {
                                  /**
                                   * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                                   * given ``owner``'s signed approval.
                                   *
                                   * IMPORTANT: The same issues {IERC20-approve} has related to transaction
                                   * ordering also apply here.
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   * - `deadline` must be a timestamp in the future.
                                   * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                                   * over the EIP712-formatted function arguments.
                                   * - the signature must use ``owner``'s current nonce (see {nonces}).
                                   *
                                   * For more information on the signature format, see the
                                   * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                                   * section].
                                   *
                                   * CAUTION: See Security Considerations above.
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external;
                              
                                  /**
                                   * @dev Returns the current nonce for `owner`. This value must be
                                   * included whenever a signature is generated for {permit}.
                                   *
                                   * Every successful call to {permit} increases ``owner``'s nonce by one. This
                                   * prevents a signature from being used multiple times.
                                   */
                                  function nonces(address owner) external view returns (uint256);
                              
                                  /**
                                   * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
                                   */
                                  // solhint-disable-next-line func-name-mixedcase
                                  function DOMAIN_SEPARATOR() external view returns (bytes32);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/utils/Address.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
                              
                              /**
                               * @dev Collection of functions related to the address type
                               */
                              library Address {
                                  /**
                                   * @dev Returns true if `account` is a contract.
                                   *
                                   * [IMPORTANT]
                                   * ====
                                   * It is unsafe to assume that an address for which this function returns
                                   * false is an externally-owned account (EOA) and not a contract.
                                   *
                                   * Among others, `isContract` will return false for the following
                                   * types of addresses:
                                   *
                                   *  - an externally-owned account
                                   *  - a contract in construction
                                   *  - an address where a contract will be created
                                   *  - an address where a contract lived, but was destroyed
                                   *
                                   * Furthermore, `isContract` will also return true if the target contract within
                                   * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
                                   * which only has an effect at the end of a transaction.
                                   * ====
                                   *
                                   * [IMPORTANT]
                                   * ====
                                   * You shouldn't rely on `isContract` to protect against flash loan attacks!
                                   *
                                   * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
                                   * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
                                   * constructor.
                                   * ====
                                   */
                                  function isContract(address account) internal view returns (bool) {
                                      // This method relies on extcodesize/address.code.length, which returns 0
                                      // for contracts in construction, since the code is only stored at the end
                                      // of the constructor execution.
                              
                                      return account.code.length > 0;
                                  }
                              
                                  /**
                                   * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                                   * `recipient`, forwarding all available gas and reverting on errors.
                                   *
                                   * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                                   * of certain opcodes, possibly making contracts go over the 2300 gas limit
                                   * imposed by `transfer`, making them unable to receive funds via
                                   * `transfer`. {sendValue} removes this limitation.
                                   *
                                   * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                                   *
                                   * IMPORTANT: because control is transferred to `recipient`, care must be
                                   * taken to not create reentrancy vulnerabilities. Consider using
                                   * {ReentrancyGuard} or the
                                   * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                                   */
                                  function sendValue(address payable recipient, uint256 amount) internal {
                                      require(address(this).balance >= amount, "Address: insufficient balance");
                              
                                      (bool success, ) = recipient.call{value: amount}("");
                                      require(success, "Address: unable to send value, recipient may have reverted");
                                  }
                              
                                  /**
                                   * @dev Performs a Solidity function call using a low level `call`. A
                                   * plain `call` is an unsafe replacement for a function call: use this
                                   * function instead.
                                   *
                                   * If `target` reverts with a revert reason, it is bubbled up by this
                                   * function (like regular Solidity function calls).
                                   *
                                   * Returns the raw returned data. To convert to the expected return value,
                                   * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                                   *
                                   * Requirements:
                                   *
                                   * - `target` must be a contract.
                                   * - calling `target` with `data` must not revert.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                      return functionCallWithValue(target, data, 0, "Address: low-level call failed");
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                                   * `errorMessage` as a fallback revert reason when `target` reverts.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCall(
                                      address target,
                                      bytes memory data,
                                      string memory errorMessage
                                  ) internal returns (bytes memory) {
                                      return functionCallWithValue(target, data, 0, errorMessage);
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but also transferring `value` wei to `target`.
                                   *
                                   * Requirements:
                                   *
                                   * - the calling contract must have an ETH balance of at least `value`.
                                   * - the called Solidity function must be `payable`.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                      return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                                   * with `errorMessage` as a fallback revert reason when `target` reverts.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCallWithValue(
                                      address target,
                                      bytes memory data,
                                      uint256 value,
                                      string memory errorMessage
                                  ) internal returns (bytes memory) {
                                      require(address(this).balance >= value, "Address: insufficient balance for call");
                                      (bool success, bytes memory returndata) = target.call{value: value}(data);
                                      return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but performing a static call.
                                   *
                                   * _Available since v3.3._
                                   */
                                  function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                      return functionStaticCall(target, data, "Address: low-level static call failed");
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                                   * but performing a static call.
                                   *
                                   * _Available since v3.3._
                                   */
                                  function functionStaticCall(
                                      address target,
                                      bytes memory data,
                                      string memory errorMessage
                                  ) internal view returns (bytes memory) {
                                      (bool success, bytes memory returndata) = target.staticcall(data);
                                      return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but performing a delegate call.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                      return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                                  }
                              
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                                   * but performing a delegate call.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function functionDelegateCall(
                                      address target,
                                      bytes memory data,
                                      string memory errorMessage
                                  ) internal returns (bytes memory) {
                                      (bool success, bytes memory returndata) = target.delegatecall(data);
                                      return verifyCallResultFromTarget(target, success, returndata, errorMessage);
                                  }
                              
                                  /**
                                   * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
                                   * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
                                   *
                                   * _Available since v4.8._
                                   */
                                  function verifyCallResultFromTarget(
                                      address target,
                                      bool success,
                                      bytes memory returndata,
                                      string memory errorMessage
                                  ) internal view returns (bytes memory) {
                                      if (success) {
                                          if (returndata.length == 0) {
                                              // only check isContract if the call was successful and the return data is empty
                                              // otherwise we already know that it was a contract
                                              require(isContract(target), "Address: call to non-contract");
                                          }
                                          return returndata;
                                      } else {
                                          _revert(returndata, errorMessage);
                                      }
                                  }
                              
                                  /**
                                   * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
                                   * revert reason or using the provided one.
                                   *
                                   * _Available since v4.3._
                                   */
                                  function verifyCallResult(
                                      bool success,
                                      bytes memory returndata,
                                      string memory errorMessage
                                  ) internal pure returns (bytes memory) {
                                      if (success) {
                                          return returndata;
                                      } else {
                                          _revert(returndata, errorMessage);
                                      }
                                  }
                              
                                  function _revert(bytes memory returndata, string memory errorMessage) private pure {
                                      // Look for revert reason and bubble it up if present
                                      if (returndata.length > 0) {
                                          // The easiest way to bubble the revert reason is using memory via assembly
                                          /// @solidity memory-safe-assembly
                                          assembly {
                                              let returndata_size := mload(returndata)
                                              revert(add(32, returndata), returndata_size)
                                          }
                                      } else {
                                          revert(errorMessage);
                                      }
                                  }
                              }
                              
                              // lib/openzeppelin-contracts/contracts/utils/Context.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
                              
                              /**
                               * @dev Provides information about the current execution context, including the
                               * sender of the transaction and its data. While these are generally available
                               * via msg.sender and msg.data, they should not be accessed in such a direct
                               * manner, since when dealing with meta-transactions the account sending and
                               * paying for execution may not be the actual sender (as far as an application
                               * is concerned).
                               *
                               * This contract is only required for intermediate, library-like contracts.
                               */
                              abstract contract Context {
                                  function _msgSender() internal view virtual returns (address) {
                                      return msg.sender;
                                  }
                              
                                  function _msgData() internal view virtual returns (bytes calldata) {
                                      return msg.data;
                                  }
                              
                                  function _contextSuffixLength() internal view virtual returns (uint256) {
                                      return 0;
                                  }
                              }
                              
                              // lib/openzeppelin-contracts/contracts/utils/math/Math.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
                              
                              /**
                               * @dev Standard math utilities missing in the Solidity language.
                               */
                              library Math {
                                  enum Rounding {
                                      Down, // Toward negative infinity
                                      Up, // Toward infinity
                                      Zero // Toward zero
                                  }
                              
                                  /**
                                   * @dev Returns the largest of two numbers.
                                   */
                                  function max(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a > b ? a : b;
                                  }
                              
                                  /**
                                   * @dev Returns the smallest of two numbers.
                                   */
                                  function min(uint256 a, uint256 b) internal pure returns (uint256) {
                                      return a < b ? a : b;
                                  }
                              
                                  /**
                                   * @dev Returns the average of two numbers. The result is rounded towards
                                   * zero.
                                   */
                                  function average(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b) / 2 can overflow.
                                      return (a & b) + (a ^ b) / 2;
                                  }
                              
                                  /**
                                   * @dev Returns the ceiling of the division of two numbers.
                                   *
                                   * This differs from standard division with `/` in that it rounds up instead
                                   * of rounding down.
                                   */
                                  function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
                                      // (a + b - 1) / b can overflow on addition, so we distribute.
                                      return a == 0 ? 0 : (a - 1) / b + 1;
                                  }
                              
                                  /**
                                   * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
                                   * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
                                   * with further edits by Uniswap Labs also under MIT license.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
                                      unchecked {
                                          // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
                                          // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
                                          // variables such that product = prod1 * 2^256 + prod0.
                                          uint256 prod0; // Least significant 256 bits of the product
                                          uint256 prod1; // Most significant 256 bits of the product
                                          assembly {
                                              let mm := mulmod(x, y, not(0))
                                              prod0 := mul(x, y)
                                              prod1 := sub(sub(mm, prod0), lt(mm, prod0))
                                          }
                              
                                          // Handle non-overflow cases, 256 by 256 division.
                                          if (prod1 == 0) {
                                              // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                                              // The surrounding unchecked block does not change this fact.
                                              // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                                              return prod0 / denominator;
                                          }
                              
                                          // Make sure the result is less than 2^256. Also prevents denominator == 0.
                                          require(denominator > prod1, "Math: mulDiv overflow");
                              
                                          ///////////////////////////////////////////////
                                          // 512 by 256 division.
                                          ///////////////////////////////////////////////
                              
                                          // Make division exact by subtracting the remainder from [prod1 prod0].
                                          uint256 remainder;
                                          assembly {
                                              // Compute remainder using mulmod.
                                              remainder := mulmod(x, y, denominator)
                              
                                              // Subtract 256 bit number from 512 bit number.
                                              prod1 := sub(prod1, gt(remainder, prod0))
                                              prod0 := sub(prod0, remainder)
                                          }
                              
                                          // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
                                          // See https://cs.stackexchange.com/q/138556/92363.
                              
                                          // Does not overflow because the denominator cannot be zero at this stage in the function.
                                          uint256 twos = denominator & (~denominator + 1);
                                          assembly {
                                              // Divide denominator by twos.
                                              denominator := div(denominator, twos)
                              
                                              // Divide [prod1 prod0] by twos.
                                              prod0 := div(prod0, twos)
                              
                                              // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                                              twos := add(div(sub(0, twos), twos), 1)
                                          }
                              
                                          // Shift in bits from prod1 into prod0.
                                          prod0 |= prod1 * twos;
                              
                                          // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
                                          // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
                                          // four bits. That is, denominator * inv = 1 mod 2^4.
                                          uint256 inverse = (3 * denominator) ^ 2;
                              
                                          // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
                                          // in modular arithmetic, doubling the correct bits in each step.
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^8
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^16
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^32
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^64
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^128
                                          inverse *= 2 - denominator * inverse; // inverse mod 2^256
                              
                                          // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
                                          // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
                                          // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
                                          // is no longer required.
                                          result = prod0 * inverse;
                                          return result;
                                      }
                                  }
                              
                                  /**
                                   * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
                                   */
                                  function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
                                      uint256 result = mulDiv(x, y, denominator);
                                      if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
                                          result += 1;
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
                                   *
                                   * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
                                   */
                                  function sqrt(uint256 a) internal pure returns (uint256) {
                                      if (a == 0) {
                                          return 0;
                                      }
                              
                                      // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
                                      //
                                      // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
                                      // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
                                      //
                                      // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
                                      // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
                                      // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
                                      //
                                      // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
                                      uint256 result = 1 << (log2(a) >> 1);
                              
                                      // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
                                      // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
                                      // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
                                      // into the expected uint128 result.
                                      unchecked {
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          result = (result + a / result) >> 1;
                                          return min(result, a / result);
                                      }
                                  }
                              
                                  /**
                                   * @notice Calculates sqrt(a), following the selected rounding direction.
                                   */
                                  function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = sqrt(a);
                                          return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 2, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 128;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 64;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 32;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 16;
                                          }
                                          if (value >> 8 > 0) {
                                              value >>= 8;
                                              result += 8;
                                          }
                                          if (value >> 4 > 0) {
                                              value >>= 4;
                                              result += 4;
                                          }
                                          if (value >> 2 > 0) {
                                              value >>= 2;
                                              result += 2;
                                          }
                                          if (value >> 1 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log2(value);
                                          return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 10, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >= 10 ** 64) {
                                              value /= 10 ** 64;
                                              result += 64;
                                          }
                                          if (value >= 10 ** 32) {
                                              value /= 10 ** 32;
                                              result += 32;
                                          }
                                          if (value >= 10 ** 16) {
                                              value /= 10 ** 16;
                                              result += 16;
                                          }
                                          if (value >= 10 ** 8) {
                                              value /= 10 ** 8;
                                              result += 8;
                                          }
                                          if (value >= 10 ** 4) {
                                              value /= 10 ** 4;
                                              result += 4;
                                          }
                                          if (value >= 10 ** 2) {
                                              value /= 10 ** 2;
                                              result += 2;
                                          }
                                          if (value >= 10 ** 1) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log10(value);
                                          return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
                                      }
                                  }
                              
                                  /**
                                   * @dev Return the log in base 256, rounded down, of a positive value.
                                   * Returns 0 if given 0.
                                   *
                                   * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
                                   */
                                  function log256(uint256 value) internal pure returns (uint256) {
                                      uint256 result = 0;
                                      unchecked {
                                          if (value >> 128 > 0) {
                                              value >>= 128;
                                              result += 16;
                                          }
                                          if (value >> 64 > 0) {
                                              value >>= 64;
                                              result += 8;
                                          }
                                          if (value >> 32 > 0) {
                                              value >>= 32;
                                              result += 4;
                                          }
                                          if (value >> 16 > 0) {
                                              value >>= 16;
                                              result += 2;
                                          }
                                          if (value >> 8 > 0) {
                                              result += 1;
                                          }
                                      }
                                      return result;
                                  }
                              
                                  /**
                                   * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
                                   * Returns 0 if given 0.
                                   */
                                  function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
                                      unchecked {
                                          uint256 result = log256(value);
                                          return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
                                      }
                                  }
                              }
                              
                              // src/interfaces/IBaseStrategy.sol
                              
                              interface IBaseStrategy {
                                  function tokenizedStrategyAddress() external view returns (address);
                              
                                  /*//////////////////////////////////////////////////////////////
                                                          IMMUTABLE FUNCTIONS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  function availableDepositLimit(
                                      address _owner
                                  ) external view returns (uint256);
                              
                                  function availableWithdrawLimit(
                                      address _owner
                                  ) external view returns (uint256);
                              
                                  function deployFunds(uint256 _assets) external;
                              
                                  function freeFunds(uint256 _amount) external;
                              
                                  function harvestAndReport() external returns (uint256);
                              
                                  function tendThis(uint256 _totalIdle) external;
                              
                                  function shutdownWithdraw(uint256 _amount) external;
                              
                                  function tendTrigger() external view returns (bool, bytes memory);
                              }
                              
                              // src/interfaces/IFactory.sol
                              
                              interface IFactory {
                                  function protocol_fee_config() external view returns (uint16, address);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
                              
                              // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
                              
                              /**
                               * @dev Interface for the optional metadata functions from the ERC20 standard.
                               *
                               * _Available since v4.1._
                               */
                              interface IERC20Metadata is IERC20 {
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() external view returns (string memory);
                              
                                  /**
                                   * @dev Returns the symbol of the token.
                                   */
                                  function symbol() external view returns (string memory);
                              
                                  /**
                                   * @dev Returns the decimals places of the token.
                                   */
                                  function decimals() external view returns (uint8);
                              }
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
                              
                              /**
                               * @dev Implementation of the {IERC20} interface.
                               *
                               * This implementation is agnostic to the way tokens are created. This means
                               * that a supply mechanism has to be added in a derived contract using {_mint}.
                               * For a generic mechanism see {ERC20PresetMinterPauser}.
                               *
                               * TIP: For a detailed writeup see our guide
                               * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
                               * to implement supply mechanisms].
                               *
                               * The default value of {decimals} is 18. To change this, you should override
                               * this function so it returns a different value.
                               *
                               * We have followed general OpenZeppelin Contracts guidelines: functions revert
                               * instead returning `false` on failure. This behavior is nonetheless
                               * conventional and does not conflict with the expectations of ERC20
                               * applications.
                               *
                               * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
                               * This allows applications to reconstruct the allowance for all accounts just
                               * by listening to said events. Other implementations of the EIP may not emit
                               * these events, as it isn't required by the specification.
                               *
                               * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
                               * functions have been added to mitigate the well-known issues around setting
                               * allowances. See {IERC20-approve}.
                               */
                              contract ERC20 is Context, IERC20, IERC20Metadata {
                                  mapping(address => uint256) private _balances;
                              
                                  mapping(address => mapping(address => uint256)) private _allowances;
                              
                                  uint256 private _totalSupply;
                              
                                  string private _name;
                                  string private _symbol;
                              
                                  /**
                                   * @dev Sets the values for {name} and {symbol}.
                                   *
                                   * All two of these values are immutable: they can only be set once during
                                   * construction.
                                   */
                                  constructor(string memory name_, string memory symbol_) {
                                      _name = name_;
                                      _symbol = symbol_;
                                  }
                              
                                  /**
                                   * @dev Returns the name of the token.
                                   */
                                  function name() public view virtual override returns (string memory) {
                                      return _name;
                                  }
                              
                                  /**
                                   * @dev Returns the symbol of the token, usually a shorter version of the
                                   * name.
                                   */
                                  function symbol() public view virtual override returns (string memory) {
                                      return _symbol;
                                  }
                              
                                  /**
                                   * @dev Returns the number of decimals used to get its user representation.
                                   * For example, if `decimals` equals `2`, a balance of `505` tokens should
                                   * be displayed to a user as `5.05` (`505 / 10 ** 2`).
                                   *
                                   * Tokens usually opt for a value of 18, imitating the relationship between
                                   * Ether and Wei. This is the default value returned by this function, unless
                                   * it's overridden.
                                   *
                                   * NOTE: This information is only used for _display_ purposes: it in
                                   * no way affects any of the arithmetic of the contract, including
                                   * {IERC20-balanceOf} and {IERC20-transfer}.
                                   */
                                  function decimals() public view virtual override returns (uint8) {
                                      return 18;
                                  }
                              
                                  /**
                                   * @dev See {IERC20-totalSupply}.
                                   */
                                  function totalSupply() public view virtual override returns (uint256) {
                                      return _totalSupply;
                                  }
                              
                                  /**
                                   * @dev See {IERC20-balanceOf}.
                                   */
                                  function balanceOf(address account) public view virtual override returns (uint256) {
                                      return _balances[account];
                                  }
                              
                                  /**
                                   * @dev See {IERC20-transfer}.
                                   *
                                   * Requirements:
                                   *
                                   * - `to` cannot be the zero address.
                                   * - the caller must have a balance of at least `amount`.
                                   */
                                  function transfer(address to, uint256 amount) public virtual override returns (bool) {
                                      address owner = _msgSender();
                                      _transfer(owner, to, amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev See {IERC20-allowance}.
                                   */
                                  function allowance(address owner, address spender) public view virtual override returns (uint256) {
                                      return _allowances[owner][spender];
                                  }
                              
                                  /**
                                   * @dev See {IERC20-approve}.
                                   *
                                   * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                                   * `transferFrom`. This is semantically equivalent to an infinite approval.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   */
                                  function approve(address spender, uint256 amount) public virtual override returns (bool) {
                                      address owner = _msgSender();
                                      _approve(owner, spender, amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev See {IERC20-transferFrom}.
                                   *
                                   * Emits an {Approval} event indicating the updated allowance. This is not
                                   * required by the EIP. See the note at the beginning of {ERC20}.
                                   *
                                   * NOTE: Does not update the allowance if the current allowance
                                   * is the maximum `uint256`.
                                   *
                                   * Requirements:
                                   *
                                   * - `from` and `to` cannot be the zero address.
                                   * - `from` must have a balance of at least `amount`.
                                   * - the caller must have allowance for ``from``'s tokens of at least
                                   * `amount`.
                                   */
                                  function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
                                      address spender = _msgSender();
                                      _spendAllowance(from, spender, amount);
                                      _transfer(from, to, amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Atomically increases the allowance granted to `spender` by the caller.
                                   *
                                   * This is an alternative to {approve} that can be used as a mitigation for
                                   * problems described in {IERC20-approve}.
                                   *
                                   * Emits an {Approval} event indicating the updated allowance.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   */
                                  function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
                                      address owner = _msgSender();
                                      _approve(owner, spender, allowance(owner, spender) + addedValue);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Atomically decreases the allowance granted to `spender` by the caller.
                                   *
                                   * This is an alternative to {approve} that can be used as a mitigation for
                                   * problems described in {IERC20-approve}.
                                   *
                                   * Emits an {Approval} event indicating the updated allowance.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   * - `spender` must have allowance for the caller of at least
                                   * `subtractedValue`.
                                   */
                                  function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
                                      address owner = _msgSender();
                                      uint256 currentAllowance = allowance(owner, spender);
                                      require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
                                      unchecked {
                                          _approve(owner, spender, currentAllowance - subtractedValue);
                                      }
                              
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Moves `amount` of tokens from `from` to `to`.
                                   *
                                   * This internal function is equivalent to {transfer}, and can be used to
                                   * e.g. implement automatic token fees, slashing mechanisms, etc.
                                   *
                                   * Emits a {Transfer} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `from` cannot be the zero address.
                                   * - `to` cannot be the zero address.
                                   * - `from` must have a balance of at least `amount`.
                                   */
                                  function _transfer(address from, address to, uint256 amount) internal virtual {
                                      require(from != address(0), "ERC20: transfer from the zero address");
                                      require(to != address(0), "ERC20: transfer to the zero address");
                              
                                      _beforeTokenTransfer(from, to, amount);
                              
                                      uint256 fromBalance = _balances[from];
                                      require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
                                      unchecked {
                                          _balances[from] = fromBalance - amount;
                                          // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
                                          // decrementing then incrementing.
                                          _balances[to] += amount;
                                      }
                              
                                      emit Transfer(from, to, amount);
                              
                                      _afterTokenTransfer(from, to, amount);
                                  }
                              
                                  /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                                   * the total supply.
                                   *
                                   * Emits a {Transfer} event with `from` set to the zero address.
                                   *
                                   * Requirements:
                                   *
                                   * - `account` cannot be the zero address.
                                   */
                                  function _mint(address account, uint256 amount) internal virtual {
                                      require(account != address(0), "ERC20: mint to the zero address");
                              
                                      _beforeTokenTransfer(address(0), account, amount);
                              
                                      _totalSupply += amount;
                                      unchecked {
                                          // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
                                          _balances[account] += amount;
                                      }
                                      emit Transfer(address(0), account, amount);
                              
                                      _afterTokenTransfer(address(0), account, amount);
                                  }
                              
                                  /**
                                   * @dev Destroys `amount` tokens from `account`, reducing the
                                   * total supply.
                                   *
                                   * Emits a {Transfer} event with `to` set to the zero address.
                                   *
                                   * Requirements:
                                   *
                                   * - `account` cannot be the zero address.
                                   * - `account` must have at least `amount` tokens.
                                   */
                                  function _burn(address account, uint256 amount) internal virtual {
                                      require(account != address(0), "ERC20: burn from the zero address");
                              
                                      _beforeTokenTransfer(account, address(0), amount);
                              
                                      uint256 accountBalance = _balances[account];
                                      require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
                                      unchecked {
                                          _balances[account] = accountBalance - amount;
                                          // Overflow not possible: amount <= accountBalance <= totalSupply.
                                          _totalSupply -= amount;
                                      }
                              
                                      emit Transfer(account, address(0), amount);
                              
                                      _afterTokenTransfer(account, address(0), amount);
                                  }
                              
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                                   *
                                   * This internal function is equivalent to `approve`, and can be used to
                                   * e.g. set automatic allowances for certain subsystems, etc.
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `owner` cannot be the zero address.
                                   * - `spender` cannot be the zero address.
                                   */
                                  function _approve(address owner, address spender, uint256 amount) internal virtual {
                                      require(owner != address(0), "ERC20: approve from the zero address");
                                      require(spender != address(0), "ERC20: approve to the zero address");
                              
                                      _allowances[owner][spender] = amount;
                                      emit Approval(owner, spender, amount);
                                  }
                              
                                  /**
                                   * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                                   *
                                   * Does not update the allowance amount in case of infinite allowance.
                                   * Revert if not enough allowance is available.
                                   *
                                   * Might emit an {Approval} event.
                                   */
                                  function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
                                      uint256 currentAllowance = allowance(owner, spender);
                                      if (currentAllowance != type(uint256).max) {
                                          require(currentAllowance >= amount, "ERC20: insufficient allowance");
                                          unchecked {
                                              _approve(owner, spender, currentAllowance - amount);
                                          }
                                      }
                                  }
                              
                                  /**
                                   * @dev Hook that is called before any transfer of tokens. This includes
                                   * minting and burning.
                                   *
                                   * Calling conditions:
                                   *
                                   * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                                   * will be transferred to `to`.
                                   * - when `from` is zero, `amount` tokens will be minted for `to`.
                                   * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
                                   * - `from` and `to` are never both zero.
                                   *
                                   * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                                   */
                                  function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                              
                                  /**
                                   * @dev Hook that is called after any transfer of tokens. This includes
                                   * minting and burning.
                                   *
                                   * Calling conditions:
                                   *
                                   * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
                                   * has been transferred to `to`.
                                   * - when `from` is zero, `amount` tokens have been minted for `to`.
                                   * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
                                   * - `from` and `to` are never both zero.
                                   *
                                   * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
                                   */
                                  function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
                              }
                              
                              // lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol
                              
                              // OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
                              
                              /**
                               * @title SafeERC20
                               * @dev Wrappers around ERC20 operations that throw on failure (when the token
                               * contract returns false). Tokens that return no value (and instead revert or
                               * throw on failure) are also supported, non-reverting calls are assumed to be
                               * successful.
                               * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                               * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                               */
                              library SafeERC20 {
                                  using Address for address;
                              
                                  /**
                                   * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful.
                                   */
                                  function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                                  }
                              
                                  /**
                                   * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
                                   * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
                                   */
                                  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                                  }
                              
                                  /**
                                   * @dev Deprecated. This function has issues similar to the ones found in
                                   * {IERC20-approve}, and its usage is discouraged.
                                   *
                                   * Whenever possible, use {safeIncreaseAllowance} and
                                   * {safeDecreaseAllowance} instead.
                                   */
                                  function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                      // safeApprove should only be called when setting an initial allowance,
                                      // or when resetting it to zero. To increase and decrease it, use
                                      // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                      require(
                                          (value == 0) || (token.allowance(address(this), spender) == 0),
                                          "SafeERC20: approve from non-zero to non-zero allowance"
                                      );
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                                  }
                              
                                  /**
                                   * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful.
                                   */
                                  function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 oldAllowance = token.allowance(address(this), spender);
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
                                  }
                              
                                  /**
                                   * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful.
                                   */
                                  function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      unchecked {
                                          uint256 oldAllowance = token.allowance(address(this), spender);
                                          require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
                                          _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
                                      }
                                  }
                              
                                  /**
                                   * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
                                   * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
                                   * to be set to zero before setting it to a non-zero value, such as USDT.
                                   */
                                  function forceApprove(IERC20 token, address spender, uint256 value) internal {
                                      bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
                              
                                      if (!_callOptionalReturnBool(token, approvalCall)) {
                                          _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
                                          _callOptionalReturn(token, approvalCall);
                                      }
                                  }
                              
                                  /**
                                   * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
                                   * Revert on invalid signature.
                                   */
                                  function safePermit(
                                      IERC20Permit token,
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      uint256 nonceBefore = token.nonces(owner);
                                      token.permit(owner, spender, value, deadline, v, r, s);
                                      uint256 nonceAfter = token.nonces(owner);
                                      require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
                                  }
                              
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   */
                                  function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
                                      // the target address contains contract code and also asserts for success in the low-level call.
                              
                                      bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                      require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                  }
                              
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   *
                                   * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
                                   */
                                  function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
                                      // and not revert is the subcall reverts.
                              
                                      (bool success, bytes memory returndata) = address(token).call(data);
                                      return
                                          success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
                                  }
                              }
                              
                              // src/TokenizedStrategy.sol
                              
                              /**$$$$$$$$$$$$$$$$$$$$$$$$$$$&Mr/|1+~>>iiiiiiiiiii>~+{|tuMW$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$$$$$$$$B#j]->iiiiiiiiiiiiiiiiiiiiiiiiiiii>-?f*B$$$$$$$$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$$$$@zj}~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~}fv@$$$$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$@z(+iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii+)zB$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$Mf~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~t#@$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$@u[iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii?n@$$$$$$$$$$$$$
                              $$$$$$$$$$$@z]iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii?u@$$$$$$$$$$$
                              $$$$$$$$$$v]iiiiiiiiiiiiiiii,.';iiiiiiiiiiiiiiiiiiiiiiiiii;'."iiiiiiiiiiiiiiii?u$$$$$$$$$$
                              $$$$$$$$%)>iiiiiiiiiiiiiii,.    ';iiiiiiiiiiiiiiiiiiiiii;'    ."iiiiiiiiiiiiiiii1%$$$$$$$$
                              $$$$$$$c~iiiiiiiiiiiiiii,.        ';iiiiiiiiiiiiiiiiii;'        ."iiiiiiiiiiiiiii~u$$$$$$$
                              $$$$$B/>iiiiiiiiiiiiii!'            `IiiiiiiiiiiiiiiI`            .Iiiiiiiiiiiiiii>|%$$$$$
                              $$$$@)iiiiiiiiiiiiiiiii;'             `Iiiiiiiiiiil`             ';iiiiiiiiiiiiiiiii}@$$$$
                              $$$B|iiiiiiiiiiiiiiiiiiii;'             `Iiiiiiil`             ';iiiiiiiiiiiiiiiiiiii1B$$$
                              $$@)iiiiiiiiiiiiiiiiiiiiiii:'             `;iiI`             ':iiiiiiiiiiiiiiiiiiiiiii{B$$
                              $$|iiiiiiiiiiiiiiiiiiiiiiiiii;'             ``             ':iiiiiiiiiiiiiiiiiiiiiiiiii1$$
                              $v>iiiiiiiiiiiiiiiiiiiiiiiiiiii:'                        ':iiiiiiiiiiiiiiiiiiiiiiiiiiii>x$
                              &?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:'                    .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-W
                              ziiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:'                .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiv
                              -iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:'            .,iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-
                              <iiiiiiiiiiiiiiiiiiii!.':iiiiiiiiiiiiii,          "iiiiiiiiiiiiii;'.Iiiiiiiiiiiiiiiiiiiii<
                              iiiiiiiiiiiiiiiiiiiii'   ';iiiiiiiiiiiii          Iiiiiiiiiiiii;'   .iiiiiiiiiiiiiiiiiiiii
                              iiiiiiiiiiiiiiiiiiii,      ';iiiiiiiiiii          IiiiiiiiiiiI`      `iiiiiiiiiiiiiiiiiiii
                              iiiiiiiiiiiiiiiiiiii.        `Iiiiiiiiii          Iiiiiiiii!`         !iiiiiiiiiiiiiiiiiii
                              iiiiiiiiiiiiiiiiiii;          :iiiiiiiii          Iiiiiiiii!          ,iiiiiiiiiiiiiiiiiii
                              iiiiiiiiiiiiiiiiiii,          iiiiiiiiii          Iiiiiiiiii.         ^iiiiiiiiiiiiiiiiiii
                              <iiiiiiiiiiiiiiiiii,          iiiiiiiiii          Iiiiiiiiii'         ^iiiiiiiiiiiiiiiiii<
                              -iiiiiiiiiiiiiiiiii;          Iiiiiiiiii          Iiiiiiiiii.         "iiiiiiiiiiiiiiiiii-
                              ziiiiiiiiiiiiiiiiiii.         'iiiiiiiii''''''''''liiiiiiii^          liiiiiiiiiiiiiiiiiiv
                              &?iiiiiiiiiiiiiiiiii^          ^iiiiiiiiiiiiiiiiiiiiiiiiii,          `iiiiiiiiiiiiiiiiii_W
                              $u>iiiiiiiiiiiiiiiiii.          `!iiiiiiiiiiiiiiiiiiiiiii^          .liiiiiiiiiiiiiiiiiir$
                              $$(iiiiiiiiiiiiiiiiii;.          ."iiiiiiiiiiiiiiiiiiii,.           :iiiiiiiiiiiiiiiiii}$$
                              $$@{iiiiiiiiiiiiiiiiii;.           .`:iiiiiiiiiiiiii;^.            :iiiiiiiiiiiiiiiiii}B$$
                              $$$B)iiiiiiiiiiiiiiiiii!'              '`",::::,"`'.             .Iiiiiiiiiiiiiiiiiii{%$$$
                              $$$$@1iiiiiiiiiiiiiiiiiii,.                                     ^iiiiiiiiiiiiiiiiiii[@$$$$
                              $$$$$B|>iiiiiiiiiiiiiiiiii!^.                                 `liiiiiiiiiiiiiiiiii>)%$$$$$
                              $$$$$$$c~iiiiiiiiiiiiiiiiiiii"'                            ."!iiiiiiiiiiiiiiiiiii~n$$$$$$$
                              $$$$$$$$B)iiiiiiiiiiiiiiiiiiiii!,`.                    .'"liiiiiiiiiiiiiiiiiiiii1%$$$$$$$$
                              $$$$$$$$$@u]iiiiiiiiiiiiiiiiiiiiiiil,^`'..      ..''^,liiiiiiiiiiiiiiiiiiiiiii-x@$$$$$$$$$
                              $$$$$$$$$$$@v?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-x$$$$$$$$$$$$
                              $$$$$$$$$$$$$@n?iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii-rB$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$/~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii<\*@$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$Bc1~iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii~{v%$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$$$$Bvf]<iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii<]tuB$$$$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$$$$$$$$%zt-+>iiiiiiiiiiiiiiiiiiiiiiiiiiiii+_tc%$$$$$$$$$$$$$$$$$$$$$$$$$
                              $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$W#u/|{+~>iiiiiiiiiiii><+{|/n#W$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/
                              
                              /**
                               * @title Yearn Tokenized Strategy
                               * @author yearn.finance
                               * @notice
                               *  This TokenizedStrategy can be used by anyone wishing to easily build
                               *  and deploy their own custom ERC4626 compliant single strategy Vault.
                               *
                               *  The TokenizedStrategy contract is meant to be used as the proxy
                               *  implementation contract that will handle all logic, storage and
                               *  management for a custom strategy that inherits the `BaseStrategy`.
                               *  Any function calls to the strategy that are not defined within that
                               *  strategy will be forwarded through a delegateCall to this contract.
                              
                               *  A strategist only needs to override a few simple functions that are
                               *  focused entirely on the strategy specific needs to easily and cheaply
                               *  deploy their own permissionless 4626 compliant vault.
                               */
                              contract TokenizedStrategy {
                                  using Math for uint256;
                                  using SafeERC20 for ERC20;
                              
                                  /*//////////////////////////////////////////////////////////////
                                                               EVENTS
                                  //////////////////////////////////////////////////////////////*/
                                  /**
                                   * @notice Emitted when a strategy is shutdown.
                                   */
                                  event StrategyShutdown();
                              
                                  /**
                                   * @notice Emitted on the initialization of any new `strategy` that uses `asset`
                                   * with this specific `apiVersion`.
                                   */
                                  event NewTokenizedStrategy(
                                      address indexed strategy,
                                      address indexed asset,
                                      string apiVersion
                                  );
                              
                                  /**
                                   * @notice Emitted when the strategy reports `profit` or `loss` and
                                   * `performanceFees` and `protocolFees` are paid out.
                                   */
                                  event Reported(
                                      uint256 profit,
                                      uint256 loss,
                                      uint256 protocolFees,
                                      uint256 performanceFees
                                  );
                              
                                  /**
                                   * @notice Emitted when the 'performanceFeeRecipient' address is
                                   * updated to 'newPerformanceFeeRecipient'.
                                   */
                                  event UpdatePerformanceFeeRecipient(
                                      address indexed newPerformanceFeeRecipient
                                  );
                              
                                  /**
                                   * @notice Emitted when the 'keeper' address is updated to 'newKeeper'.
                                   */
                                  event UpdateKeeper(address indexed newKeeper);
                              
                                  /**
                                   * @notice Emitted when the 'performanceFee' is updated to 'newPerformanceFee'.
                                   */
                                  event UpdatePerformanceFee(uint16 newPerformanceFee);
                              
                                  /**
                                   * @notice Emitted when the 'management' address is updated to 'newManagement'.
                                   */
                                  event UpdateManagement(address indexed newManagement);
                              
                                  /**
                                   * @notice Emitted when the 'emergencyAdmin' address is updated to 'newEmergencyAdmin'.
                                   */
                                  event UpdateEmergencyAdmin(address indexed newEmergencyAdmin);
                              
                                  /**
                                   * @notice Emitted when the 'profitMaxUnlockTime' is updated to 'newProfitMaxUnlockTime'.
                                   */
                                  event UpdateProfitMaxUnlockTime(uint256 newProfitMaxUnlockTime);
                              
                                  /**
                                   * @notice Emitted when the 'pendingManagement' address is updated to 'newPendingManagement'.
                                   */
                                  event UpdatePendingManagement(address indexed newPendingManagement);
                              
                                  /**
                                   * @notice Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(
                                      address indexed owner,
                                      address indexed spender,
                                      uint256 value
                                  );
                              
                                  /**
                                   * @notice Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                              
                                  /**
                                   * @notice Emitted when the `caller` has exchanged `assets` for `shares`,
                                   * and transferred those `shares` to `owner`.
                                   */
                                  event Deposit(
                                      address indexed caller,
                                      address indexed owner,
                                      uint256 assets,
                                      uint256 shares
                                  );
                              
                                  /**
                                   * @notice Emitted when the `caller` has exchanged `owner`s `shares` for `assets`,
                                   * and transferred those `assets` to `receiver`.
                                   */
                                  event Withdraw(
                                      address indexed caller,
                                      address indexed receiver,
                                      address indexed owner,
                                      uint256 assets,
                                      uint256 shares
                                  );
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      STORAGE STRUCT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @dev The struct that will hold all the storage data for each strategy
                                   * that uses this implementation.
                                   *
                                   * This replaces all state variables for a traditional contract. This
                                   * full struct will be initialized on the creation of the strategy
                                   * and continually updated and read from for the life of the contract.
                                   *
                                   * We combine all the variables into one struct to limit the amount of
                                   * times the custom storage slots need to be loaded during complex functions.
                                   *
                                   * Loading the corresponding storage slot for the struct does not
                                   * load any of the contents of the struct into memory. So the size
                                   * will not increase memory related gas usage.
                                   */
                                  // prettier-ignore
                                  struct StrategyData {
                                      // The ERC20 compliant underlying asset that will be
                                      // used by the Strategy
                                      ERC20 asset;
                              
                                      // These are the corresponding ERC20 variables needed for the
                                      // strategies token that is issued and burned on each deposit or withdraw.
                                      uint8 decimals; // The amount of decimals that `asset` and strategy use.
                                      string name; // The name of the token for the strategy.
                                      uint256 totalSupply; // The total amount of shares currently issued.
                                      mapping(address => uint256) nonces; // Mapping of nonces used for permit functions.
                                      mapping(address => uint256) balances; // Mapping to track current balances for each account that holds shares.
                                      mapping(address => mapping(address => uint256)) allowances; // Mapping to track the allowances for the strategies shares.
                              
                                      // We manually track `totalAssets` to prevent PPS manipulation through airdrops.
                                      uint256 totalAssets;
                              
                                      // Variables for profit reporting and locking.
                                      // We use uint96 for timestamps to fit in the same slot as an address. That overflows in 2.5e+21 years.
                                      // I know Yearn moves slowly but surely V4 will be out by then.
                                      // If the timestamps ever overflow tell the cyborgs still using this code I'm sorry for being cheap.
                                      uint256 profitUnlockingRate; // The rate at which locked profit is unlocking.
                                      uint96 fullProfitUnlockDate; // The timestamp at which all locked shares will unlock.
                                      address keeper; // Address given permission to call {report} and {tend}.
                                      uint32 profitMaxUnlockTime; // The amount of seconds that the reported profit unlocks over.
                                      uint16 performanceFee; // The percent in basis points of profit that is charged as a fee.
                                      address performanceFeeRecipient; // The address to pay the `performanceFee` to.
                                      uint96 lastReport; // The last time a {report} was called.
                              
                                      // Access management variables.
                                      address management; // Main address that can set all configurable variables.
                                      address pendingManagement; // Address that is pending to take over `management`.
                                      address emergencyAdmin; // Address to act in emergencies as well as `management`.
                              
                                      // Strategy Status
                                      uint8 entered; // To prevent reentrancy. Use uint8 for gas savings.
                                      bool shutdown; // Bool that can be used to stop deposits into the strategy.
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                          MODIFIERS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @dev Require that the call is coming from the strategies management.
                                   */
                                  modifier onlyManagement() {
                                      requireManagement(msg.sender);
                                      _;
                                  }
                              
                                  /**
                                   * @dev Require that the call is coming from either the strategies
                                   * management or the keeper.
                                   */
                                  modifier onlyKeepers() {
                                      requireKeeperOrManagement(msg.sender);
                                      _;
                                  }
                              
                                  /**
                                   * @dev Require that the call is coming from either the strategies
                                   * management or the emergencyAdmin.
                                   */
                                  modifier onlyEmergencyAuthorized() {
                                      requireEmergencyAuthorized(msg.sender);
                                      _;
                                  }
                              
                                  /**
                                   * @dev Prevents a contract from calling itself, directly or indirectly.
                                   * Placed over all state changing functions for increased safety.
                                   */
                                  modifier nonReentrant() {
                                      StrategyData storage S = _strategyStorage();
                                      // On the first call to nonReentrant, `entered` will be false (2)
                                      require(S.entered != ENTERED, "ReentrancyGuard: reentrant call");
                              
                                      // Any calls to nonReentrant after this point will fail
                                      S.entered = ENTERED;
                              
                                      _;
                              
                                      // Reset to false (1) once call has finished.
                                      S.entered = NOT_ENTERED;
                                  }
                              
                                  /**
                                   * @notice Require a caller is `management`.
                                   * @dev Is left public so that it can be used by the Strategy.
                                   *
                                   * When the Strategy calls this the msg.sender would be the
                                   * address of the strategy so we need to specify the sender.
                                   *
                                   * @param _sender The original msg.sender.
                                   */
                                  function requireManagement(address _sender) public view {
                                      require(_sender == _strategyStorage().management, "!management");
                                  }
                              
                                  /**
                                   * @notice Require a caller is the `keeper` or `management`.
                                   * @dev Is left public so that it can be used by the Strategy.
                                   *
                                   * When the Strategy calls this the msg.sender would be the
                                   * address of the strategy so we need to specify the sender.
                                   *
                                   * @param _sender The original msg.sender.
                                   */
                                  function requireKeeperOrManagement(address _sender) public view {
                                      StrategyData storage S = _strategyStorage();
                                      require(_sender == S.keeper || _sender == S.management, "!keeper");
                                  }
                              
                                  /**
                                   * @notice Require a caller is the `management` or `emergencyAdmin`.
                                   * @dev Is left public so that it can be used by the Strategy.
                                   *
                                   * When the Strategy calls this the msg.sender would be the
                                   * address of the strategy so we need to specify the sender.
                                   *
                                   * @param _sender The original msg.sender.
                                   */
                                  function requireEmergencyAuthorized(address _sender) public view {
                                      StrategyData storage S = _strategyStorage();
                                      require(
                                          _sender == S.emergencyAdmin || _sender == S.management,
                                          "!emergency authorized"
                                      );
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                             CONSTANTS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /// @notice API version this TokenizedStrategy implements.
                                  string internal constant API_VERSION = "3.0.4";
                              
                                  /// @notice Value to set the `entered` flag to during a call.
                                  uint8 internal constant ENTERED = 2;
                                  /// @notice Value to set the `entered` flag to at the end of the call.
                                  uint8 internal constant NOT_ENTERED = 1;
                              
                                  /// @notice Maximum in Basis Points the Performance Fee can be set to.
                                  uint16 public constant MAX_FEE = 5_000; // 50%
                              
                                  /// @notice Used for fee calculations.
                                  uint256 internal constant MAX_BPS = 10_000;
                                  /// @notice Used for profit unlocking rate calculations.
                                  uint256 internal constant MAX_BPS_EXTENDED = 1_000_000_000_000;
                              
                                  /// @notice Seconds per year for max profit unlocking time.
                                  uint256 internal constant SECONDS_PER_YEAR = 31_556_952; // 365.2425 days
                              
                                  /**
                                   * @dev Custom storage slot that will be used to store the
                                   * `StrategyData` struct that holds each strategies
                                   * specific storage variables.
                                   *
                                   * Any storage updates done by the TokenizedStrategy actually update
                                   * the storage of the calling contract. This variable points
                                   * to the specific location that will be used to store the
                                   * struct that holds all that data.
                                   *
                                   * We use a custom string in order to get a random
                                   * storage slot that will allow for strategists to use any
                                   * amount of storage in their strategy without worrying
                                   * about collisions.
                                   */
                                  bytes32 internal constant BASE_STRATEGY_STORAGE =
                                      bytes32(uint256(keccak256("yearn.base.strategy.storage")) - 1);
                              
                                  /*//////////////////////////////////////////////////////////////
                                                             IMMUTABLE
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /// @notice Address of the previously deployed Vault factory that the
                                  // protocol fee config is retrieved from.
                                  address public immutable FACTORY;
                              
                                  /*//////////////////////////////////////////////////////////////
                                                          STORAGE GETTER
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @dev will return the actual storage slot where the strategy
                                   * specific `StrategyData` struct is stored for both read
                                   * and write operations.
                                   *
                                   * This loads just the slot location, not the full struct
                                   * so it can be used in a gas efficient manner.
                                   */
                                  function _strategyStorage() internal pure returns (StrategyData storage S) {
                                      // Since STORAGE_SLOT is a constant, we have to put a variable
                                      // on the stack to access it from an inline assembly block.
                                      bytes32 slot = BASE_STRATEGY_STORAGE;
                                      assembly {
                                          S.slot := slot
                                      }
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                        INITIALIZATION
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Used to initialize storage for a newly deployed strategy.
                                   * @dev This should be called atomically whenever a new strategy is
                                   * deployed and can only be called once for each strategy.
                                   *
                                   * This will set all the default storage that must be set for a
                                   * strategy to function. Any changes can be made post deployment
                                   * through external calls from `management`.
                                   *
                                   * The function will also emit an event that off chain indexers can
                                   * look for to track any new deployments using this TokenizedStrategy.
                                   *
                                   * @param _asset Address of the underlying asset.
                                   * @param _name Name the strategy will use.
                                   * @param _management Address to set as the strategies `management`.
                                   * @param _performanceFeeRecipient Address to receive performance fees.
                                   * @param _keeper Address to set as strategies `keeper`.
                                   */
                                  function initialize(
                                      address _asset,
                                      string memory _name,
                                      address _management,
                                      address _performanceFeeRecipient,
                                      address _keeper
                                  ) external {
                                      // Cache storage pointer.
                                      StrategyData storage S = _strategyStorage();
                              
                                      // Make sure we aren't initialized.
                                      require(address(S.asset) == address(0), "initialized");
                              
                                      // Set the strategy's underlying asset.
                                      S.asset = ERC20(_asset);
                                      // Set the Strategy Tokens name.
                                      S.name = _name;
                                      // Set decimals based off the `asset`.
                                      S.decimals = ERC20(_asset).decimals();
                              
                                      // Default to a 10 day profit unlock period.
                                      S.profitMaxUnlockTime = 10 days;
                                      // Set address to receive performance fees.
                                      // Can't be address(0) or we will be burning fees.
                                      require(_performanceFeeRecipient != address(0), "ZERO ADDRESS");
                                      // Can't mint shares to its self because of profit locking.
                                      require(_performanceFeeRecipient != address(this), "self");
                                      S.performanceFeeRecipient = _performanceFeeRecipient;
                                      // Default to a 10% performance fee.
                                      S.performanceFee = 1_000;
                                      // Set last report to this block.
                                      S.lastReport = uint96(block.timestamp);
                              
                                      // Set the default management address. Can't be 0.
                                      require(_management != address(0), "ZERO ADDRESS");
                                      S.management = _management;
                                      // Set the keeper address
                                      S.keeper = _keeper;
                              
                                      // Emit event to signal a new strategy has been initialized.
                                      emit NewTokenizedStrategy(address(this), _asset, API_VERSION);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                    ERC4626 WRITE METHODS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Mints `shares` of strategy shares to `receiver` by
                                   * depositing exactly `assets` of underlying tokens.
                                   * @param assets The amount of underlying to deposit in.
                                   * @param receiver The address to receive the `shares`.
                                   * @return shares The actual amount of shares issued.
                                   */
                                  function deposit(
                                      uint256 assets,
                                      address receiver
                                  ) external nonReentrant returns (uint256 shares) {
                                      // Get the storage slot for all following calls.
                                      StrategyData storage S = _strategyStorage();
                              
                                      // Deposit full balance if using max uint.
                                      if (assets == type(uint256).max) {
                                          assets = S.asset.balanceOf(msg.sender);
                                      }
                              
                                      // Checking max deposit will also check if shutdown.
                                      require(
                                          assets <= _maxDeposit(S, receiver),
                                          "ERC4626: deposit more than max"
                                      );
                                      // Check for rounding error.
                                      require(
                                          (shares = _convertToShares(S, assets, Math.Rounding.Down)) != 0,
                                          "ZERO_SHARES"
                                      );
                              
                                      _deposit(S, receiver, assets, shares);
                                  }
                              
                                  /**
                                   * @notice Mints exactly `shares` of strategy shares to
                                   * `receiver` by depositing `assets` of underlying tokens.
                                   * @param shares The amount of strategy shares mint.
                                   * @param receiver The address to receive the `shares`.
                                   * @return assets The actual amount of asset deposited.
                                   */
                                  function mint(
                                      uint256 shares,
                                      address receiver
                                  ) external nonReentrant returns (uint256 assets) {
                                      // Get the storage slot for all following calls.
                                      StrategyData storage S = _strategyStorage();
                              
                                      // Checking max mint will also check if shutdown.
                                      require(shares <= _maxMint(S, receiver), "ERC4626: mint more than max");
                                      // Check for rounding error.
                                      require(
                                          (assets = _convertToAssets(S, shares, Math.Rounding.Up)) != 0,
                                          "ZERO_ASSETS"
                                      );
                              
                                      _deposit(S, receiver, assets, shares);
                                  }
                              
                                  /**
                                   * @notice Withdraws exactly `assets` from `owners` shares and sends
                                   * the underlying tokens to `receiver`.
                                   * @dev This will default to not allowing any loss to be taken.
                                   * @param assets The amount of underlying to withdraw.
                                   * @param receiver The address to receive `assets`.
                                   * @param owner The address whose shares are burnt.
                                   * @return shares The actual amount of shares burnt.
                                   */
                                  function withdraw(
                                      uint256 assets,
                                      address receiver,
                                      address owner
                                  ) external returns (uint256 shares) {
                                      return withdraw(assets, receiver, owner, 0);
                                  }
                              
                                  /**
                                   * @notice Withdraws `assets` from `owners` shares and sends
                                   * the underlying tokens to `receiver`.
                                   * @dev This includes an added parameter to allow for losses.
                                   * @param assets The amount of underlying to withdraw.
                                   * @param receiver The address to receive `assets`.
                                   * @param owner The address whose shares are burnt.
                                   * @param maxLoss The amount of acceptable loss in Basis points.
                                   * @return shares The actual amount of shares burnt.
                                   */
                                  function withdraw(
                                      uint256 assets,
                                      address receiver,
                                      address owner,
                                      uint256 maxLoss
                                  ) public nonReentrant returns (uint256 shares) {
                                      // Get the storage slot for all following calls.
                                      StrategyData storage S = _strategyStorage();
                                      require(
                                          assets <= _maxWithdraw(S, owner),
                                          "ERC4626: withdraw more than max"
                                      );
                                      // Check for rounding error or 0 value.
                                      require(
                                          (shares = _convertToShares(S, assets, Math.Rounding.Up)) != 0,
                                          "ZERO_SHARES"
                                      );
                              
                                      // Withdraw and track the actual amount withdrawn for loss check.
                                      _withdraw(S, receiver, owner, assets, shares, maxLoss);
                                  }
                              
                                  /**
                                   * @notice Redeems exactly `shares` from `owner` and
                                   * sends `assets` of underlying tokens to `receiver`.
                                   * @dev This will default to allowing any loss passed to be realized.
                                   * @param shares The amount of shares burnt.
                                   * @param receiver The address to receive `assets`.
                                   * @param owner The address whose shares are burnt.
                                   * @return assets The actual amount of underlying withdrawn.
                                   */
                                  function redeem(
                                      uint256 shares,
                                      address receiver,
                                      address owner
                                  ) external returns (uint256) {
                                      // We default to not limiting a potential loss.
                                      return redeem(shares, receiver, owner, MAX_BPS);
                                  }
                              
                                  /**
                                   * @notice Redeems exactly `shares` from `owner` and
                                   * sends `assets` of underlying tokens to `receiver`.
                                   * @dev This includes an added parameter to allow for losses.
                                   * @param shares The amount of shares burnt.
                                   * @param receiver The address to receive `assets`.
                                   * @param owner The address whose shares are burnt.
                                   * @param maxLoss The amount of acceptable loss in Basis points.
                                   * @return . The actual amount of underlying withdrawn.
                                   */
                                  function redeem(
                                      uint256 shares,
                                      address receiver,
                                      address owner,
                                      uint256 maxLoss
                                  ) public nonReentrant returns (uint256) {
                                      // Get the storage slot for all following calls.
                                      StrategyData storage S = _strategyStorage();
                                      require(
                                          shares <= _maxRedeem(S, owner),
                                          "ERC4626: redeem more than max"
                                      );
                                      uint256 assets;
                                      // Check for rounding error or 0 value.
                                      require(
                                          (assets = _convertToAssets(S, shares, Math.Rounding.Down)) != 0,
                                          "ZERO_ASSETS"
                                      );
                              
                                      // We need to return the actual amount withdrawn in case of a loss.
                                      return _withdraw(S, receiver, owner, assets, shares, maxLoss);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                  EXTERNAL 4626 VIEW METHODS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Get the total amount of assets this strategy holds
                                   * as of the last report.
                                   *
                                   * We manually track `totalAssets` to avoid any PPS manipulation.
                                   *
                                   * @return . Total assets the strategy holds.
                                   */
                                  function totalAssets() external view returns (uint256) {
                                      return _totalAssets(_strategyStorage());
                                  }
                              
                                  /**
                                   * @notice Get the current supply of the strategies shares.
                                   *
                                   * Locked shares issued to the strategy from profits are not
                                   * counted towards the full supply until they are unlocked.
                                   *
                                   * As more shares slowly unlock the totalSupply will decrease
                                   * causing the PPS of the strategy to increase.
                                   *
                                   * @return . Total amount of shares outstanding.
                                   */
                                  function totalSupply() external view returns (uint256) {
                                      return _totalSupply(_strategyStorage());
                                  }
                              
                                  /**
                                   * @notice The amount of shares that the strategy would
                                   *  exchange for the amount of assets provided, in an
                                   * ideal scenario where all the conditions are met.
                                   *
                                   * @param assets The amount of underlying.
                                   * @return . Expected shares that `assets` represents.
                                   */
                                  function convertToShares(uint256 assets) external view returns (uint256) {
                                      return _convertToShares(_strategyStorage(), assets, Math.Rounding.Down);
                                  }
                              
                                  /**
                                   * @notice The amount of assets that the strategy would
                                   * exchange for the amount of shares provided, in an
                                   * ideal scenario where all the conditions are met.
                                   *
                                   * @param shares The amount of the strategies shares.
                                   * @return . Expected amount of `asset` the shares represents.
                                   */
                                  function convertToAssets(uint256 shares) external view returns (uint256) {
                                      return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Down);
                                  }
                              
                                  /**
                                   * @notice Allows an on-chain or off-chain user to simulate
                                   * the effects of their deposit at the current block, given
                                   * current on-chain conditions.
                                   * @dev This will round down.
                                   *
                                   * @param assets The amount of `asset` to deposits.
                                   * @return . Expected shares that would be issued.
                                   */
                                  function previewDeposit(uint256 assets) external view returns (uint256) {
                                      return _convertToShares(_strategyStorage(), assets, Math.Rounding.Down);
                                  }
                              
                                  /**
                                   * @notice Allows an on-chain or off-chain user to simulate
                                   * the effects of their mint at the current block, given
                                   * current on-chain conditions.
                                   * @dev This is used instead of convertToAssets so that it can
                                   * round up for safer mints.
                                   *
                                   * @param shares The amount of shares to mint.
                                   * @return . The needed amount of `asset` for the mint.
                                   */
                                  function previewMint(uint256 shares) external view returns (uint256) {
                                      return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Up);
                                  }
                              
                                  /**
                                   * @notice Allows an on-chain or off-chain user to simulate
                                   * the effects of their withdrawal at the current block,
                                   * given current on-chain conditions.
                                   * @dev This is used instead of convertToShares so that it can
                                   * round up for safer withdraws.
                                   *
                                   * @param assets The amount of `asset` that would be withdrawn.
                                   * @return . The amount of shares that would be burnt.
                                   */
                                  function previewWithdraw(uint256 assets) external view returns (uint256) {
                                      return _convertToShares(_strategyStorage(), assets, Math.Rounding.Up);
                                  }
                              
                                  /**
                                   * @notice Allows an on-chain or off-chain user to simulate
                                   * the effects of their redemption at the current block,
                                   * given current on-chain conditions.
                                   * @dev This will round down.
                                   *
                                   * @param shares The amount of shares that would be redeemed.
                                   * @return . The amount of `asset` that would be returned.
                                   */
                                  function previewRedeem(uint256 shares) external view returns (uint256) {
                                      return _convertToAssets(_strategyStorage(), shares, Math.Rounding.Down);
                                  }
                              
                                  /**
                                   * @notice Total number of underlying assets that can
                                   * be deposited into the strategy, where `receiver`
                                   * corresponds to the receiver of the shares of a {deposit} call.
                                   *
                                   * @param receiver The address receiving the shares.
                                   * @return . The max that `receiver` can deposit in `asset`.
                                   */
                                  function maxDeposit(address receiver) external view returns (uint256) {
                                      return _maxDeposit(_strategyStorage(), receiver);
                                  }
                              
                                  /**
                                   * @notice Total number of shares that can be minted to `receiver`
                                   * of a {mint} call.
                                   *
                                   * @param receiver The address receiving the shares.
                                   * @return _maxMint The max that `receiver` can mint in shares.
                                   */
                                  function maxMint(address receiver) external view returns (uint256) {
                                      return _maxMint(_strategyStorage(), receiver);
                                  }
                              
                                  /**
                                   * @notice Total number of underlying assets that can be
                                   * withdrawn from the strategy by `owner`, where `owner`
                                   * corresponds to the msg.sender of a {redeem} call.
                                   *
                                   * @param owner The owner of the shares.
                                   * @return _maxWithdraw Max amount of `asset` that can be withdrawn.
                                   */
                                  function maxWithdraw(address owner) external view returns (uint256) {
                                      return _maxWithdraw(_strategyStorage(), owner);
                                  }
                              
                                  /**
                                   * @notice Variable `maxLoss` is ignored.
                                   * @dev Accepts a `maxLoss` variable in order to match the multi
                                   * strategy vaults ABI.
                                   */
                                  function maxWithdraw(
                                      address owner,
                                      uint256 /*maxLoss*/
                                  ) external view returns (uint256) {
                                      return _maxWithdraw(_strategyStorage(), owner);
                                  }
                              
                                  /**
                                   * @notice Total number of strategy shares that can be
                                   * redeemed from the strategy by `owner`, where `owner`
                                   * corresponds to the msg.sender of a {redeem} call.
                                   *
                                   * @param owner The owner of the shares.
                                   * @return _maxRedeem Max amount of shares that can be redeemed.
                                   */
                                  function maxRedeem(address owner) external view returns (uint256) {
                                      return _maxRedeem(_strategyStorage(), owner);
                                  }
                              
                                  /**
                                   * @notice Variable `maxLoss` is ignored.
                                   * @dev Accepts a `maxLoss` variable in order to match the multi
                                   * strategy vaults ABI.
                                   */
                                  function maxRedeem(
                                      address owner,
                                      uint256 /*maxLoss*/
                                  ) external view returns (uint256) {
                                      return _maxRedeem(_strategyStorage(), owner);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                  INTERNAL 4626 VIEW METHODS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /// @dev Internal implementation of {totalAssets}.
                                  function _totalAssets(
                                      StrategyData storage S
                                  ) internal view returns (uint256) {
                                      return S.totalAssets;
                                  }
                              
                                  /// @dev Internal implementation of {totalSupply}.
                                  function _totalSupply(
                                      StrategyData storage S
                                  ) internal view returns (uint256) {
                                      return S.totalSupply - _unlockedShares(S);
                                  }
                              
                                  /// @dev Internal implementation of {convertToShares}.
                                  function _convertToShares(
                                      StrategyData storage S,
                                      uint256 assets,
                                      Math.Rounding _rounding
                                  ) internal view returns (uint256) {
                                      // Saves an extra SLOAD if values are non-zero.
                                      uint256 totalSupply_ = _totalSupply(S);
                                      // If supply is 0, PPS = 1.
                                      if (totalSupply_ == 0) return assets;
                              
                                      uint256 totalAssets_ = _totalAssets(S);
                                      // If assets are 0 but supply is not PPS = 0.
                                      if (totalAssets_ == 0) return 0;
                              
                                      return assets.mulDiv(totalSupply_, totalAssets_, _rounding);
                                  }
                              
                                  /// @dev Internal implementation of {convertToAssets}.
                                  function _convertToAssets(
                                      StrategyData storage S,
                                      uint256 shares,
                                      Math.Rounding _rounding
                                  ) internal view returns (uint256) {
                                      // Saves an extra SLOAD if totalSupply() is non-zero.
                                      uint256 supply = _totalSupply(S);
                              
                                      return
                                          supply == 0
                                              ? shares
                                              : shares.mulDiv(_totalAssets(S), supply, _rounding);
                                  }
                              
                                  /// @dev Internal implementation of {maxDeposit}.
                                  function _maxDeposit(
                                      StrategyData storage S,
                                      address receiver
                                  ) internal view returns (uint256) {
                                      // Cannot deposit when shutdown or to the strategy.
                                      if (S.shutdown || receiver == address(this)) return 0;
                              
                                      return IBaseStrategy(address(this)).availableDepositLimit(receiver);
                                  }
                              
                                  /// @dev Internal implementation of {maxMint}.
                                  function _maxMint(
                                      StrategyData storage S,
                                      address receiver
                                  ) internal view returns (uint256 maxMint_) {
                                      // Cannot mint when shutdown or to the strategy.
                                      if (S.shutdown || receiver == address(this)) return 0;
                              
                                      maxMint_ = IBaseStrategy(address(this)).availableDepositLimit(receiver);
                                      if (maxMint_ != type(uint256).max) {
                                          maxMint_ = _convertToShares(S, maxMint_, Math.Rounding.Down);
                                      }
                                  }
                              
                                  /// @dev Internal implementation of {maxWithdraw}.
                                  function _maxWithdraw(
                                      StrategyData storage S,
                                      address owner
                                  ) internal view returns (uint256 maxWithdraw_) {
                                      // Get the max the owner could withdraw currently.
                                      maxWithdraw_ = IBaseStrategy(address(this)).availableWithdrawLimit(
                                          owner
                                      );
                              
                                      // If there is no limit enforced.
                                      if (maxWithdraw_ == type(uint256).max) {
                                          // Saves a min check if there is no withdrawal limit.
                                          maxWithdraw_ = _convertToAssets(
                                              S,
                                              _balanceOf(S, owner),
                                              Math.Rounding.Down
                                          );
                                      } else {
                                          maxWithdraw_ = Math.min(
                                              _convertToAssets(S, _balanceOf(S, owner), Math.Rounding.Down),
                                              maxWithdraw_
                                          );
                                      }
                                  }
                              
                                  /// @dev Internal implementation of {maxRedeem}.
                                  function _maxRedeem(
                                      StrategyData storage S,
                                      address owner
                                  ) internal view returns (uint256 maxRedeem_) {
                                      // Get the max the owner could withdraw currently.
                                      maxRedeem_ = IBaseStrategy(address(this)).availableWithdrawLimit(owner);
                              
                                      // Conversion would overflow and saves a min check if there is no withdrawal limit.
                                      if (maxRedeem_ == type(uint256).max) {
                                          maxRedeem_ = _balanceOf(S, owner);
                                      } else {
                                          maxRedeem_ = Math.min(
                                              // Can't redeem more than the balance.
                                              _convertToShares(S, maxRedeem_, Math.Rounding.Down),
                                              _balanceOf(S, owner)
                                          );
                                      }
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                  INTERNAL 4626 WRITE METHODS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @dev Function to be called during {deposit} and {mint}.
                                   *
                                   * This function handles all logic including transfers,
                                   * minting and accounting.
                                   *
                                   * We do all external calls before updating any internal
                                   * values to prevent view reentrancy issues from the token
                                   * transfers or the _deployFunds() calls.
                                   */
                                  function _deposit(
                                      StrategyData storage S,
                                      address receiver,
                                      uint256 assets,
                                      uint256 shares
                                  ) internal {
                                      // Cache storage variables used more than once.
                                      ERC20 _asset = S.asset;
                              
                                      // Need to transfer before minting or ERC777s could reenter.
                                      _asset.safeTransferFrom(msg.sender, address(this), assets);
                              
                                      // We can deploy the full loose balance currently held.
                                      IBaseStrategy(address(this)).deployFunds(
                                          _asset.balanceOf(address(this))
                                      );
                              
                                      // Adjust total Assets.
                                      S.totalAssets += assets;
                              
                                      // mint shares
                                      _mint(S, receiver, shares);
                              
                                      emit Deposit(msg.sender, receiver, assets, shares);
                                  }
                              
                                  /**
                                   * @dev To be called during {redeem} and {withdraw}.
                                   *
                                   * This will handle all logic, transfers and accounting
                                   * in order to service the withdraw request.
                                   *
                                   * If we are not able to withdraw the full amount needed, it will
                                   * be counted as a loss and passed on to the user.
                                   */
                                  function _withdraw(
                                      StrategyData storage S,
                                      address receiver,
                                      address owner,
                                      uint256 assets,
                                      uint256 shares,
                                      uint256 maxLoss
                                  ) internal returns (uint256) {
                                      require(receiver != address(0), "ZERO ADDRESS");
                                      require(maxLoss <= MAX_BPS, "exceeds MAX_BPS");
                              
                                      // Spend allowance if applicable.
                                      if (msg.sender != owner) {
                                          _spendAllowance(S, owner, msg.sender, shares);
                                      }
                              
                                      // Cache `asset` since it is used multiple times..
                                      ERC20 _asset = S.asset;
                              
                                      uint256 idle = _asset.balanceOf(address(this));
                                      uint256 loss;
                                      // Check if we need to withdraw funds.
                                      if (idle < assets) {
                                          // Tell Strategy to free what we need.
                                          unchecked {
                                              IBaseStrategy(address(this)).freeFunds(assets - idle);
                                          }
                              
                                          // Return the actual amount withdrawn. Adjust for potential under withdraws.
                                          idle = _asset.balanceOf(address(this));
                              
                                          // If we didn't get enough out then we have a loss.
                                          if (idle < assets) {
                                              unchecked {
                                                  loss = assets - idle;
                                              }
                                              // If a non-default max loss parameter was set.
                                              if (maxLoss < MAX_BPS) {
                                                  // Make sure we are within the acceptable range.
                                                  require(
                                                      loss <= (assets * maxLoss) / MAX_BPS,
                                                      "too much loss"
                                                  );
                                              }
                                              // Lower the amount to be withdrawn.
                                              assets = idle;
                                          }
                                      }
                              
                                      // Update assets based on how much we took.
                                      S.totalAssets -= (assets + loss);
                              
                                      _burn(S, owner, shares);
                              
                                      // Transfer the amount of underlying to the receiver.
                                      _asset.safeTransfer(receiver, assets);
                              
                                      emit Withdraw(msg.sender, receiver, owner, assets, shares);
                              
                                      // Return the actual amount of assets withdrawn.
                                      return assets;
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      PROFIT REPORTING
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Function for keepers to call to harvest and record all
                                   * profits accrued.
                                   *
                                   * @dev This will account for any gains/losses since the last report
                                   * and charge fees accordingly.
                                   *
                                   * Any profit over the fees charged will be immediately locked
                                   * so there is no change in PricePerShare. Then slowly unlocked
                                   * over the `maxProfitUnlockTime` each second based on the
                                   * calculated `profitUnlockingRate`.
                                   *
                                   * In case of a loss it will first attempt to offset the loss
                                   * with any remaining locked shares from the last report in
                                   * order to reduce any negative impact to PPS.
                                   *
                                   * Will then recalculate the new time to unlock profits over and the
                                   * rate based on a weighted average of any remaining time from the
                                   * last report and the new amount of shares to be locked.
                                   *
                                   * @return profit The notional amount of gain if any since the last
                                   * report in terms of `asset`.
                                   * @return loss The notional amount of loss if any since the last
                                   * report in terms of `asset`.
                                   */
                                  function report()
                                      external
                                      nonReentrant
                                      onlyKeepers
                                      returns (uint256 profit, uint256 loss)
                                  {
                                      // Cache storage pointer since its used repeatedly.
                                      StrategyData storage S = _strategyStorage();
                              
                                      // Tell the strategy to report the real total assets it has.
                                      // It should do all reward selling and redepositing now and
                                      // account for deployed and loose `asset` so we can accurately
                                      // account for all funds including those potentially airdropped
                                      // and then have any profits immediately locked.
                                      uint256 newTotalAssets = IBaseStrategy(address(this))
                                          .harvestAndReport();
                              
                                      uint256 oldTotalAssets = _totalAssets(S);
                              
                                      // Get the amount of shares we need to burn from previous reports.
                                      uint256 sharesToBurn = _unlockedShares(S);
                              
                                      // Initialize variables needed throughout.
                                      uint256 totalFees;
                                      uint256 protocolFees;
                                      uint256 sharesToLock;
                                      uint256 _profitMaxUnlockTime = S.profitMaxUnlockTime;
                                      // Calculate profit/loss.
                                      if (newTotalAssets > oldTotalAssets) {
                                          // We have a profit.
                                          unchecked {
                                              profit = newTotalAssets - oldTotalAssets;
                                          }
                              
                                          // We need to get the equivalent amount of shares
                                          // at the current PPS before any minting or burning.
                                          sharesToLock = _convertToShares(S, profit, Math.Rounding.Down);
                              
                                          // Cache the performance fee.
                                          uint16 fee = S.performanceFee;
                                          uint256 totalFeeShares;
                                          // If we are charging a performance fee
                                          if (fee != 0) {
                                              // Asses performance fees.
                                              unchecked {
                                                  // Get in `asset` for the event.
                                                  totalFees = (profit * fee) / MAX_BPS;
                                                  // And in shares for the payment.
                                                  totalFeeShares = (sharesToLock * fee) / MAX_BPS;
                                              }
                              
                                              // Get the protocol fee config from the factory.
                                              (
                                                  uint16 protocolFeeBps,
                                                  address protocolFeesRecipient
                                              ) = IFactory(FACTORY).protocol_fee_config();
                              
                                              uint256 protocolFeeShares;
                                              // Check if there is a protocol fee to charge.
                                              if (protocolFeeBps != 0) {
                                                  unchecked {
                                                      // Calculate protocol fees based on the performance Fees.
                                                      protocolFeeShares =
                                                          (totalFeeShares * protocolFeeBps) /
                                                          MAX_BPS;
                                                      // Need amount in underlying for event.
                                                      protocolFees = (totalFees * protocolFeeBps) / MAX_BPS;
                                                  }
                              
                                                  // Mint the protocol fees to the recipient.
                                                  _mint(S, protocolFeesRecipient, protocolFeeShares);
                                              }
                              
                                              // Mint the difference to the strategy fee recipient.
                                              unchecked {
                                                  _mint(
                                                      S,
                                                      S.performanceFeeRecipient,
                                                      totalFeeShares - protocolFeeShares
                                                  );
                                              }
                                          }
                              
                                          // Check if we are locking profit.
                                          if (_profitMaxUnlockTime != 0) {
                                              // lock (profit - fees)
                                              unchecked {
                                                  sharesToLock -= totalFeeShares;
                                              }
                              
                                              // If we are burning more than re-locking.
                                              if (sharesToBurn > sharesToLock) {
                                                  // Burn the difference
                                                  unchecked {
                                                      _burn(S, address(this), sharesToBurn - sharesToLock);
                                                  }
                                              } else if (sharesToLock > sharesToBurn) {
                                                  // Mint the shares to lock the strategy.
                                                  unchecked {
                                                      _mint(S, address(this), sharesToLock - sharesToBurn);
                                                  }
                                              }
                                          }
                                      } else {
                                          // Expect we have a loss.
                                          unchecked {
                                              loss = oldTotalAssets - newTotalAssets;
                                          }
                              
                                          // Check in case `else` was due to being equal.
                                          if (loss != 0) {
                                              // We will try and burn the unlocked shares and as much from any
                                              // pending profit still unlocking to offset the loss to prevent any PPS decline post report.
                                              sharesToBurn = Math.min(
                                                  // Cannot burn more than we have.
                                                  S.balances[address(this)],
                                                  // Try and burn both the shares already unlocked and the amount for the loss.
                                                  _convertToShares(S, loss, Math.Rounding.Down) + sharesToBurn
                                              );
                                          }
                              
                                          // Check if there is anything to burn.
                                          if (sharesToBurn != 0) {
                                              _burn(S, address(this), sharesToBurn);
                                          }
                                      }
                              
                                      // Update unlocking rate and time to fully unlocked.
                                      uint256 totalLockedShares = S.balances[address(this)];
                                      if (totalLockedShares != 0) {
                                          uint256 previouslyLockedTime;
                                          uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate;
                                          // Check if we need to account for shares still unlocking.
                                          if (_fullProfitUnlockDate > block.timestamp) {
                                              unchecked {
                                                  // There will only be previously locked shares if time remains.
                                                  // We calculate this here since it should be rare.
                                                  previouslyLockedTime =
                                                      (_fullProfitUnlockDate - block.timestamp) *
                                                      (totalLockedShares - sharesToLock);
                                              }
                                          }
                              
                                          // newProfitLockingPeriod is a weighted average between the remaining
                                          // time of the previously locked shares and the profitMaxUnlockTime.
                                          uint256 newProfitLockingPeriod = (previouslyLockedTime +
                                              sharesToLock *
                                              _profitMaxUnlockTime) / totalLockedShares;
                              
                                          // Calculate how many shares unlock per second.
                                          S.profitUnlockingRate =
                                              (totalLockedShares * MAX_BPS_EXTENDED) /
                                              newProfitLockingPeriod;
                              
                                          // Calculate how long until the full amount of shares is unlocked.
                                          S.fullProfitUnlockDate = uint96(
                                              block.timestamp + newProfitLockingPeriod
                                          );
                                      } else {
                                          // Only setting this to 0 will turn in the desired effect,
                                          // no need to update profitUnlockingRate.
                                          S.fullProfitUnlockDate = 0;
                                      }
                              
                                      // Update the new total assets value.
                                      S.totalAssets = newTotalAssets;
                                      S.lastReport = uint96(block.timestamp);
                              
                                      // Emit event with info
                                      emit Reported(
                                          profit,
                                          loss,
                                          protocolFees, // Protocol fees
                                          totalFees - protocolFees // Performance Fees
                                      );
                                  }
                              
                                  /**
                                   * @notice Get how many shares have been unlocked since last report.
                                   * @return . The amount of shares that have unlocked.
                                   */
                                  function unlockedShares() external view returns (uint256) {
                                      return _unlockedShares(_strategyStorage());
                                  }
                              
                                  /**
                                   * @dev To determine how many of the shares that were locked during the last
                                   * report have since unlocked.
                                   *
                                   * If the `fullProfitUnlockDate` has passed the full strategy's balance will
                                   * count as unlocked.
                                   *
                                   * @return unlocked The amount of shares that have unlocked.
                                   */
                                  function _unlockedShares(
                                      StrategyData storage S
                                  ) internal view returns (uint256 unlocked) {
                                      uint96 _fullProfitUnlockDate = S.fullProfitUnlockDate;
                                      if (_fullProfitUnlockDate > block.timestamp) {
                                          unchecked {
                                              unlocked =
                                                  (S.profitUnlockingRate * (block.timestamp - S.lastReport)) /
                                                  MAX_BPS_EXTENDED;
                                          }
                                      } else if (_fullProfitUnlockDate != 0) {
                                          // All shares have been unlocked.
                                          unlocked = S.balances[address(this)];
                                      }
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                          TENDING
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice For a 'keeper' to 'tend' the strategy if a custom
                                   * tendTrigger() is implemented.
                                   *
                                   * @dev Both 'tendTrigger' and '_tend' will need to be overridden
                                   * for this to be used.
                                   *
                                   * This will callback the internal '_tend' call in the BaseStrategy
                                   * with the total current amount available to the strategy to deploy.
                                   *
                                   * This is a permissioned function so if desired it could
                                   * be used for illiquid or manipulatable strategies to compound
                                   * rewards, perform maintenance or deposit/withdraw funds.
                                   *
                                   * This will not cause any change in PPS. Total assets will
                                   * be the same before and after.
                                   *
                                   * A report() call will be needed to record any profits or losses.
                                   */
                                  function tend() external nonReentrant onlyKeepers {
                                      // Tend the strategy with the current loose balance.
                                      IBaseStrategy(address(this)).tendThis(
                                          _strategyStorage().asset.balanceOf(address(this))
                                      );
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      STRATEGY SHUTDOWN
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Used to shutdown the strategy preventing any further deposits.
                                   * @dev Can only be called by the current `management` or `emergencyAdmin`.
                                   *
                                   * This will stop any new {deposit} or {mint} calls but will
                                   * not prevent {withdraw} or {redeem}. It will also still allow for
                                   * {tend} and {report} so that management can report any last losses
                                   * in an emergency as well as provide any maintenance to allow for full
                                   * withdraw.
                                   *
                                   * This is a one way switch and can never be set back once shutdown.
                                   */
                                  function shutdownStrategy() external onlyEmergencyAuthorized {
                                      _strategyStorage().shutdown = true;
                              
                                      emit StrategyShutdown();
                                  }
                              
                                  /**
                                   * @notice To manually withdraw funds from the yield source after a
                                   * strategy has been shutdown.
                                   * @dev This can only be called post {shutdownStrategy}.
                                   *
                                   * This will never cause a change in PPS. Total assets will
                                   * be the same before and after.
                                   *
                                   * A strategist will need to override the {_emergencyWithdraw} function
                                   * in their strategy for this to work.
                                   *
                                   * @param amount The amount of asset to attempt to free.
                                   */
                                  function emergencyWithdraw(
                                      uint256 amount
                                  ) external nonReentrant onlyEmergencyAuthorized {
                                      // Make sure the strategy has been shutdown.
                                      require(_strategyStorage().shutdown, "not shutdown");
                              
                                      // Withdraw from the yield source.
                                      IBaseStrategy(address(this)).shutdownWithdraw(amount);
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      GETTER FUNCTIONS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Get the underlying asset for the strategy.
                                   * @return . The underlying asset.
                                   */
                                  function asset() external view returns (address) {
                                      return address(_strategyStorage().asset);
                                  }
                              
                                  /**
                                   * @notice Get the API version for this TokenizedStrategy.
                                   * @return . The API version for this TokenizedStrategy
                                   */
                                  function apiVersion() external pure returns (string memory) {
                                      return API_VERSION;
                                  }
                              
                                  /**
                                   * @notice Get the current address that controls the strategy.
                                   * @return . Address of management
                                   */
                                  function management() external view returns (address) {
                                      return _strategyStorage().management;
                                  }
                              
                                  /**
                                   * @notice Get the current pending management address if any.
                                   * @return . Address of pendingManagement
                                   */
                                  function pendingManagement() external view returns (address) {
                                      return _strategyStorage().pendingManagement;
                                  }
                              
                                  /**
                                   * @notice Get the current address that can call tend and report.
                                   * @return . Address of the keeper
                                   */
                                  function keeper() external view returns (address) {
                                      return _strategyStorage().keeper;
                                  }
                              
                                  /**
                                   * @notice Get the current address that can shutdown and emergency withdraw.
                                   * @return . Address of the emergencyAdmin
                                   */
                                  function emergencyAdmin() external view returns (address) {
                                      return _strategyStorage().emergencyAdmin;
                                  }
                              
                                  /**
                                   * @notice Get the current performance fee charged on profits.
                                   * denominated in Basis Points where 10_000 == 100%
                                   * @return . Current performance fee.
                                   */
                                  function performanceFee() external view returns (uint16) {
                                      return _strategyStorage().performanceFee;
                                  }
                              
                                  /**
                                   * @notice Get the current address that receives the performance fees.
                                   * @return . Address of performanceFeeRecipient
                                   */
                                  function performanceFeeRecipient() external view returns (address) {
                                      return _strategyStorage().performanceFeeRecipient;
                                  }
                              
                                  /**
                                   * @notice Gets the timestamp at which all profits will be unlocked.
                                   * @return . The full profit unlocking timestamp
                                   */
                                  function fullProfitUnlockDate() external view returns (uint256) {
                                      return uint256(_strategyStorage().fullProfitUnlockDate);
                                  }
                              
                                  /**
                                   * @notice The per second rate at which profits are unlocking.
                                   * @dev This is denominated in EXTENDED_BPS decimals.
                                   * @return . The current profit unlocking rate.
                                   */
                                  function profitUnlockingRate() external view returns (uint256) {
                                      return _strategyStorage().profitUnlockingRate;
                                  }
                              
                                  /**
                                   * @notice Gets the current time profits are set to unlock over.
                                   * @return . The current profit max unlock time.
                                   */
                                  function profitMaxUnlockTime() external view returns (uint256) {
                                      return _strategyStorage().profitMaxUnlockTime;
                                  }
                              
                                  /**
                                   * @notice The timestamp of the last time protocol fees were charged.
                                   * @return . The last report.
                                   */
                                  function lastReport() external view returns (uint256) {
                                      return uint256(_strategyStorage().lastReport);
                                  }
                              
                                  /**
                                   * @notice Get the price per share.
                                   * @dev This value offers limited precision. Integrations that require
                                   * exact precision should use convertToAssets or convertToShares instead.
                                   *
                                   * @return . The price per share.
                                   */
                                  function pricePerShare() external view returns (uint256) {
                                      StrategyData storage S = _strategyStorage();
                                      return _convertToAssets(S, 10 ** S.decimals, Math.Rounding.Down);
                                  }
                              
                                  /**
                                   * @notice To check if the strategy has been shutdown.
                                   * @return . Whether or not the strategy is shutdown.
                                   */
                                  function isShutdown() external view returns (bool) {
                                      return _strategyStorage().shutdown;
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      SETTER FUNCTIONS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Step one of two to set a new address to be in charge of the strategy.
                                   * @dev Can only be called by the current `management`. The address is
                                   * set to pending management and will then have to call {acceptManagement}
                                   * in order for the 'management' to officially change.
                                   *
                                   * Cannot set `management` to address(0).
                                   *
                                   * @param _management New address to set `pendingManagement` to.
                                   */
                                  function setPendingManagement(address _management) external onlyManagement {
                                      require(_management != address(0), "ZERO ADDRESS");
                                      _strategyStorage().pendingManagement = _management;
                              
                                      emit UpdatePendingManagement(_management);
                                  }
                              
                                  /**
                                   * @notice Step two of two to set a new 'management' of the strategy.
                                   * @dev Can only be called by the current `pendingManagement`.
                                   */
                                  function acceptManagement() external {
                                      StrategyData storage S = _strategyStorage();
                                      require(msg.sender == S.pendingManagement, "!pending");
                                      S.management = msg.sender;
                                      S.pendingManagement = address(0);
                              
                                      emit UpdateManagement(msg.sender);
                                  }
                              
                                  /**
                                   * @notice Sets a new address to be in charge of tend and reports.
                                   * @dev Can only be called by the current `management`.
                                   *
                                   * @param _keeper New address to set `keeper` to.
                                   */
                                  function setKeeper(address _keeper) external onlyManagement {
                                      _strategyStorage().keeper = _keeper;
                              
                                      emit UpdateKeeper(_keeper);
                                  }
                              
                                  /**
                                   * @notice Sets a new address to be able to shutdown the strategy.
                                   * @dev Can only be called by the current `management`.
                                   *
                                   * @param _emergencyAdmin New address to set `emergencyAdmin` to.
                                   */
                                  function setEmergencyAdmin(
                                      address _emergencyAdmin
                                  ) external onlyManagement {
                                      _strategyStorage().emergencyAdmin = _emergencyAdmin;
                              
                                      emit UpdateEmergencyAdmin(_emergencyAdmin);
                                  }
                              
                                  /**
                                   * @notice Sets the performance fee to be charged on reported gains.
                                   * @dev Can only be called by the current `management`.
                                   *
                                   * Denominated in Basis Points. So 100% == 10_000.
                                   * Cannot set greater than to MAX_FEE.
                                   *
                                   * @param _performanceFee New performance fee.
                                   */
                                  function setPerformanceFee(uint16 _performanceFee) external onlyManagement {
                                      require(_performanceFee <= MAX_FEE, "MAX FEE");
                                      _strategyStorage().performanceFee = _performanceFee;
                              
                                      emit UpdatePerformanceFee(_performanceFee);
                                  }
                              
                                  /**
                                   * @notice Sets a new address to receive performance fees.
                                   * @dev Can only be called by the current `management`.
                                   *
                                   * Cannot set to address(0).
                                   *
                                   * @param _performanceFeeRecipient New address to set `management` to.
                                   */
                                  function setPerformanceFeeRecipient(
                                      address _performanceFeeRecipient
                                  ) external onlyManagement {
                                      require(_performanceFeeRecipient != address(0), "ZERO ADDRESS");
                                      require(_performanceFeeRecipient != address(this), "Cannot be self");
                                      _strategyStorage().performanceFeeRecipient = _performanceFeeRecipient;
                              
                                      emit UpdatePerformanceFeeRecipient(_performanceFeeRecipient);
                                  }
                              
                                  /**
                                   * @notice Sets the time for profits to be unlocked over.
                                   * @dev Can only be called by the current `management`.
                                   *
                                   * Denominated in seconds and cannot be greater than 1 year.
                                   *
                                   * NOTE: Setting to 0 will cause all currently locked profit
                                   * to be unlocked instantly and should be done with care.
                                   *
                                   * `profitMaxUnlockTime` is stored as a uint32 for packing but can
                                   * be passed in as uint256 for simplicity.
                                   *
                                   * @param _profitMaxUnlockTime New `profitMaxUnlockTime`.
                                   */
                                  function setProfitMaxUnlockTime(
                                      uint256 _profitMaxUnlockTime
                                  ) external onlyManagement {
                                      // Must be less than a year.
                                      require(_profitMaxUnlockTime <= SECONDS_PER_YEAR, "too long");
                                      StrategyData storage S = _strategyStorage();
                              
                                      // If we are setting to 0 we need to adjust amounts.
                                      if (_profitMaxUnlockTime == 0) {
                                          uint256 shares = S.balances[address(this)];
                                          if (shares != 0) {
                                              // Burn all shares if applicable.
                                              _burn(S, address(this), shares);
                                          }
                                          // Reset unlocking variables
                                          S.profitUnlockingRate = 0;
                                          S.fullProfitUnlockDate = 0;
                                      }
                              
                                      S.profitMaxUnlockTime = uint32(_profitMaxUnlockTime);
                              
                                      emit UpdateProfitMaxUnlockTime(_profitMaxUnlockTime);
                                  }
                              
                                  /**
                                   * @notice Updates the name for the strategy.
                                   * @param _name The new name for the strategy.
                                   */
                                  function setName(string calldata _name) external onlyManagement {
                                      _strategyStorage().name = _name;
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                      ERC20 METHODS
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Returns the name of the token.
                                   * @return . The name the strategy is using for its token.
                                   */
                                  function name() external view returns (string memory) {
                                      return _strategyStorage().name;
                                  }
                              
                                  /**
                                   * @notice Returns the symbol of the strategies token.
                                   * @dev Will be 'ys + asset symbol'.
                                   * @return . The symbol the strategy is using for its tokens.
                                   */
                                  function symbol() external view returns (string memory) {
                                      return
                                          string(abi.encodePacked("ys", _strategyStorage().asset.symbol()));
                                  }
                              
                                  /**
                                   * @notice Returns the number of decimals used to get its user representation.
                                   * @return . The decimals used for the strategy and `asset`.
                                   */
                                  function decimals() external view returns (uint8) {
                                      return _strategyStorage().decimals;
                                  }
                              
                                  /**
                                   * @notice Returns the current balance for a given '_account'.
                                   * @dev If the '_account` is the strategy then this will subtract
                                   * the amount of shares that have been unlocked since the last profit first.
                                   * @param account the address to return the balance for.
                                   * @return . The current balance in y shares of the '_account'.
                                   */
                                  function balanceOf(address account) external view returns (uint256) {
                                      return _balanceOf(_strategyStorage(), account);
                                  }
                              
                                  /// @dev Internal implementation of {balanceOf}.
                                  function _balanceOf(
                                      StrategyData storage S,
                                      address account
                                  ) internal view returns (uint256) {
                                      if (account == address(this)) {
                                          return S.balances[account] - _unlockedShares(S);
                                      }
                                      return S.balances[account];
                                  }
                              
                                  /**
                                   * @notice Transfer '_amount` of shares from `msg.sender` to `to`.
                                   * @dev
                                   * Requirements:
                                   *
                                   * - `to` cannot be the zero address.
                                   * - `to` cannot be the address of the strategy.
                                   * - the caller must have a balance of at least `_amount`.
                                   *
                                   * @param to The address shares will be transferred to.
                                   * @param amount The amount of shares to be transferred from sender.
                                   * @return . a boolean value indicating whether the operation succeeded.
                                   */
                                  function transfer(address to, uint256 amount) external returns (bool) {
                                      _transfer(_strategyStorage(), msg.sender, to, amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @notice Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   * @param owner The address who owns the shares.
                                   * @param spender The address who would be moving the owners shares.
                                   * @return . The remaining amount of shares of `owner` that could be moved by `spender`.
                                   */
                                  function allowance(
                                      address owner,
                                      address spender
                                  ) external view returns (uint256) {
                                      return _allowance(_strategyStorage(), owner, spender);
                                  }
                              
                                  /// @dev Internal implementation of {allowance}.
                                  function _allowance(
                                      StrategyData storage S,
                                      address owner,
                                      address spender
                                  ) internal view returns (uint256) {
                                      return S.allowances[owner][spender];
                                  }
                              
                                  /**
                                   * @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   * @dev
                                   *
                                   * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
                                   * `transferFrom`. This is semantically equivalent to an infinite approval.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * @param spender the address to allow the shares to be moved by.
                                   * @param amount the amount of shares to allow `spender` to move.
                                   * @return . a boolean value indicating whether the operation succeeded.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool) {
                                      _approve(_strategyStorage(), msg.sender, spender, amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @notice `amount` tokens from `from` to `to` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * @dev
                                   * Emits an {Approval} event indicating the updated allowance. This is not
                                   * required by the EIP.
                                   *
                                   * NOTE: Does not update the allowance if the current allowance
                                   * is the maximum `uint256`.
                                   *
                                   * Requirements:
                                   *
                                   * - `from` and `to` cannot be the zero address.
                                   * - `to` cannot be the address of the strategy.
                                   * - `from` must have a balance of at least `amount`.
                                   * - the caller must have allowance for ``from``'s tokens of at least
                                   * `amount`.
                                   *
                                   * Emits a {Transfer} event.
                                   *
                                   * @param from the address to be moving shares from.
                                   * @param to the address to be moving shares to.
                                   * @param amount the quantity of shares to move.
                                   * @return . a boolean value indicating whether the operation succeeded.
                                   */
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 amount
                                  ) external returns (bool) {
                                      StrategyData storage S = _strategyStorage();
                                      _spendAllowance(S, from, msg.sender, amount);
                                      _transfer(S, from, to, amount);
                                      return true;
                                  }
                              
                                  /**
                                   * @dev Moves `amount` of tokens from `from` to `to`.
                                   *
                                   * This internal function is equivalent to {transfer}, and can be used to
                                   * e.g. implement automatic token fees, slashing mechanisms, etc.
                                   *
                                   * Emits a {Transfer} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `from` cannot be the zero address.
                                   * - `to` cannot be the zero address.
                                   * - `to` cannot be the strategies address
                                   * - `from` must have a balance of at least `amount`.
                                   *
                                   */
                                  function _transfer(
                                      StrategyData storage S,
                                      address from,
                                      address to,
                                      uint256 amount
                                  ) internal {
                                      require(from != address(0), "ERC20: transfer from the zero address");
                                      require(to != address(0), "ERC20: transfer to the zero address");
                                      require(to != address(this), "ERC20 transfer to strategy");
                              
                                      S.balances[from] -= amount;
                                      unchecked {
                                          S.balances[to] += amount;
                                      }
                              
                                      emit Transfer(from, to, amount);
                                  }
                              
                                  /** @dev Creates `amount` tokens and assigns them to `account`, increasing
                                   * the total supply.
                                   *
                                   * Emits a {Transfer} event with `from` set to the zero address.
                                   *
                                   * Requirements:
                                   *
                                   * - `account` cannot be the zero address.
                                   *
                                   */
                                  function _mint(
                                      StrategyData storage S,
                                      address account,
                                      uint256 amount
                                  ) internal {
                                      require(account != address(0), "ERC20: mint to the zero address");
                              
                                      S.totalSupply += amount;
                                      unchecked {
                                          S.balances[account] += amount;
                                      }
                                      emit Transfer(address(0), account, amount);
                                  }
                              
                                  /**
                                   * @dev Destroys `amount` tokens from `account`, reducing the
                                   * total supply.
                                   *
                                   * Emits a {Transfer} event with `to` set to the zero address.
                                   *
                                   * Requirements:
                                   *
                                   * - `account` cannot be the zero address.
                                   * - `account` must have at least `amount` tokens.
                                   */
                                  function _burn(
                                      StrategyData storage S,
                                      address account,
                                      uint256 amount
                                  ) internal {
                                      require(account != address(0), "ERC20: burn from the zero address");
                              
                                      S.balances[account] -= amount;
                                      unchecked {
                                          S.totalSupply -= amount;
                                      }
                                      emit Transfer(account, address(0), amount);
                                  }
                              
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
                                   *
                                   * This internal function is equivalent to `approve`, and can be used to
                                   * e.g. set automatic allowances for certain subsystems, etc.
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `owner` cannot be the zero address.
                                   * - `spender` cannot be the zero address.
                                   */
                                  function _approve(
                                      StrategyData storage S,
                                      address owner,
                                      address spender,
                                      uint256 amount
                                  ) internal {
                                      require(owner != address(0), "ERC20: approve from the zero address");
                                      require(spender != address(0), "ERC20: approve to the zero address");
                              
                                      S.allowances[owner][spender] = amount;
                                      emit Approval(owner, spender, amount);
                                  }
                              
                                  /**
                                   * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
                                   *
                                   * Does not update the allowance amount in case of infinite allowance.
                                   * Revert if not enough allowance is available.
                                   *
                                   * Might emit an {Approval} event.
                                   */
                                  function _spendAllowance(
                                      StrategyData storage S,
                                      address owner,
                                      address spender,
                                      uint256 amount
                                  ) internal {
                                      uint256 currentAllowance = _allowance(S, owner, spender);
                                      if (currentAllowance != type(uint256).max) {
                                          require(
                                              currentAllowance >= amount,
                                              "ERC20: insufficient allowance"
                                          );
                                          unchecked {
                                              _approve(S, owner, spender, currentAllowance - amount);
                                          }
                                      }
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                          EIP-2612 LOGIC
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @notice Returns the current nonce for `owner`. This value must be
                                   * included whenever a signature is generated for {permit}.
                                   *
                                   * @dev Every successful call to {permit} increases ``owner``'s nonce by one. This
                                   * prevents a signature from being used multiple times.
                                   *
                                   * @param _owner the address of the account to return the nonce for.
                                   * @return . the current nonce for the account.
                                   */
                                  function nonces(address _owner) external view returns (uint256) {
                                      return _strategyStorage().nonces[_owner];
                                  }
                              
                                  /**
                                   * @notice Sets `value` as the allowance of `spender` over ``owner``'s tokens,
                                   * given ``owner``'s signed approval.
                                   *
                                   * @dev IMPORTANT: The same issues {IERC20-approve} has related to transaction
                                   * ordering also apply here.
                                   *
                                   * Emits an {Approval} event.
                                   *
                                   * Requirements:
                                   *
                                   * - `spender` cannot be the zero address.
                                   * - `deadline` must be a timestamp in the future.
                                   * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
                                   * over the EIP712-formatted function arguments.
                                   * - the signature must use ``owner``'s current nonce (see {nonces}).
                                   *
                                   * For more information on the signature format, see the
                                   * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
                                   * section].
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external {
                                      require(deadline >= block.timestamp, "ERC20: PERMIT_DEADLINE_EXPIRED");
                              
                                      // Unchecked because the only math done is incrementing
                                      // the owner's nonce which cannot realistically overflow.
                                      unchecked {
                                          address recoveredAddress = ecrecover(
                                              keccak256(
                                                  abi.encodePacked(
                                                      "\x19\x01",
                                                      DOMAIN_SEPARATOR(),
                                                      keccak256(
                                                          abi.encode(
                                                              keccak256(
                                                                  "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                                              ),
                                                              owner,
                                                              spender,
                                                              value,
                                                              _strategyStorage().nonces[owner]++,
                                                              deadline
                                                          )
                                                      )
                                                  )
                                              ),
                                              v,
                                              r,
                                              s
                                          );
                              
                                          require(
                                              recoveredAddress != address(0) && recoveredAddress == owner,
                                              "ERC20: INVALID_SIGNER"
                                          );
                              
                                          _approve(_strategyStorage(), recoveredAddress, spender, value);
                                      }
                                  }
                              
                                  /**
                                   * @notice Returns the domain separator used in the encoding of the signature
                                   * for {permit}, as defined by {EIP712}.
                                   *
                                   * @return . The domain separator that will be used for any {permit} calls.
                                   */
                                  function DOMAIN_SEPARATOR() public view returns (bytes32) {
                                      return
                                          keccak256(
                                              abi.encode(
                                                  keccak256(
                                                      "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
                                                  ),
                                                  keccak256("Yearn Vault"),
                                                  keccak256(bytes(API_VERSION)),
                                                  block.chainid,
                                                  address(this)
                                              )
                                          );
                                  }
                              
                                  /*//////////////////////////////////////////////////////////////
                                                          DEPLOYMENT
                                  //////////////////////////////////////////////////////////////*/
                              
                                  /**
                                   * @dev On contract creation we set `asset` for this contract to address(1).
                                   * This prevents it from ever being initialized in the future.
                                   * @param _factory Address of the factory of the same version for protocol fees.
                                   */
                                  constructor(address _factory) {
                                      FACTORY = _factory;
                                      _strategyStorage().asset = ERC20(address(1));
                                  }
                              }

                              File 11 of 11: FiatTokenV2_2
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { EIP712Domain } from "./EIP712Domain.sol"; // solhint-disable-line no-unused-import
                              import { Blacklistable } from "../v1/Blacklistable.sol"; // solhint-disable-line no-unused-import
                              import { FiatTokenV1 } from "../v1/FiatTokenV1.sol"; // solhint-disable-line no-unused-import
                              import { FiatTokenV2 } from "./FiatTokenV2.sol"; // solhint-disable-line no-unused-import
                              import { FiatTokenV2_1 } from "./FiatTokenV2_1.sol";
                              import { EIP712 } from "../util/EIP712.sol";
                              // solhint-disable func-name-mixedcase
                              /**
                               * @title FiatToken V2.2
                               * @notice ERC20 Token backed by fiat reserves, version 2.2
                               */
                              contract FiatTokenV2_2 is FiatTokenV2_1 {
                                  /**
                                   * @notice Initialize v2.2
                                   * @param accountsToBlacklist   A list of accounts to migrate from the old blacklist
                                   * @param newSymbol             New token symbol
                                   * data structure to the new blacklist data structure.
                                   */
                                  function initializeV2_2(
                                      address[] calldata accountsToBlacklist,
                                      string calldata newSymbol
                                  ) external {
                                      // solhint-disable-next-line reason-string
                                      require(_initializedVersion == 2);
                                      // Update fiat token symbol
                                      symbol = newSymbol;
                                      // Add previously blacklisted accounts to the new blacklist data structure
                                      // and remove them from the old blacklist data structure.
                                      for (uint256 i = 0; i < accountsToBlacklist.length; i++) {
                                          require(
                                              _deprecatedBlacklisted[accountsToBlacklist[i]],
                                              "FiatTokenV2_2: Blacklisting previously unblacklisted account!"
                                          );
                                          _blacklist(accountsToBlacklist[i]);
                                          delete _deprecatedBlacklisted[accountsToBlacklist[i]];
                                      }
                                      _blacklist(address(this));
                                      delete _deprecatedBlacklisted[address(this)];
                                      _initializedVersion = 3;
                                  }
                                  /**
                                   * @dev Internal function to get the current chain id.
                                   * @return The current chain id.
                                   */
                                  function _chainId() internal virtual view returns (uint256) {
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      return chainId;
                                  }
                                  /**
                                   * @inheritdoc EIP712Domain
                                   */
                                  function _domainSeparator() internal override view returns (bytes32) {
                                      return EIP712.makeDomainSeparator(name, "2", _chainId());
                                  }
                                  /**
                                   * @notice Update allowance with a signed permit
                                   * @dev EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param owner       Token owner's address (Authorizer)
                                   * @param spender     Spender's address
                                   * @param value       Amount of allowance
                                   * @param deadline    The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                                   * @param signature   Signature bytes signed by an EOA wallet or a contract wallet
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      bytes memory signature
                                  ) external whenNotPaused {
                                      _permit(owner, spender, value, deadline, signature);
                                  }
                                  /**
                                   * @notice Execute a transfer with a signed authorization
                                   * @dev EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                                   */
                                  function transferWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      bytes memory signature
                                  ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                      _transferWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          signature
                                      );
                                  }
                                  /**
                                   * @notice Receive a transfer with a signed authorization from the payer
                                   * @dev This has an additional check to ensure that the payee's address
                                   * matches the caller of this function to prevent front-running attacks.
                                   * EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                                   */
                                  function receiveWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      bytes memory signature
                                  ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                      _receiveWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          signature
                                      );
                                  }
                                  /**
                                   * @notice Attempt to cancel an authorization
                                   * @dev Works only if the authorization is not yet used.
                                   * EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param signature     Signature bytes signed by an EOA wallet or a contract wallet
                                   */
                                  function cancelAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      bytes memory signature
                                  ) external whenNotPaused {
                                      _cancelAuthorization(authorizer, nonce, signature);
                                  }
                                  /**
                                   * @dev Helper method that sets the blacklist state of an account on balanceAndBlacklistStates.
                                   * If _shouldBlacklist is true, we apply a (1 << 255) bitmask with an OR operation on the
                                   * account's balanceAndBlacklistState. This flips the high bit for the account to 1,
                                   * indicating that the account is blacklisted.
                                   *
                                   * If _shouldBlacklist if false, we reset the account's balanceAndBlacklistStates to their
                                   * balances. This clears the high bit for the account, indicating that the account is unblacklisted.
                                   * @param _account         The address of the account.
                                   * @param _shouldBlacklist True if the account should be blacklisted, false if the account should be unblacklisted.
                                   */
                                  function _setBlacklistState(address _account, bool _shouldBlacklist)
                                      internal
                                      override
                                  {
                                      balanceAndBlacklistStates[_account] = _shouldBlacklist
                                          ? balanceAndBlacklistStates[_account] | (1 << 255)
                                          : _balanceOf(_account);
                                  }
                                  /**
                                   * @dev Helper method that sets the balance of an account on balanceAndBlacklistStates.
                                   * Since balances are stored in the last 255 bits of the balanceAndBlacklistStates value,
                                   * we need to ensure that the updated balance does not exceed (2^255 - 1).
                                   * Since blacklisted accounts' balances cannot be updated, the method will also
                                   * revert if the account is blacklisted
                                   * @param _account The address of the account.
                                   * @param _balance The new fiat token balance of the account (max: (2^255 - 1)).
                                   */
                                  function _setBalance(address _account, uint256 _balance) internal override {
                                      require(
                                          _balance <= ((1 << 255) - 1),
                                          "FiatTokenV2_2: Balance exceeds (2^255 - 1)"
                                      );
                                      require(
                                          !_isBlacklisted(_account),
                                          "FiatTokenV2_2: Account is blacklisted"
                                      );
                                      balanceAndBlacklistStates[_account] = _balance;
                                  }
                                  /**
                                   * @inheritdoc Blacklistable
                                   */
                                  function _isBlacklisted(address _account)
                                      internal
                                      override
                                      view
                                      returns (bool)
                                  {
                                      return balanceAndBlacklistStates[_account] >> 255 == 1;
                                  }
                                  /**
                                   * @dev Helper method to obtain the balance of an account. Since balances
                                   * are stored in the last 255 bits of the balanceAndBlacklistStates value,
                                   * we apply a ((1 << 255) - 1) bit bitmask with an AND operation on the
                                   * balanceAndBlacklistState to obtain the balance.
                                   * @param _account  The address of the account.
                                   * @return          The fiat token balance of the account.
                                   */
                                  function _balanceOf(address _account)
                                      internal
                                      override
                                      view
                                      returns (uint256)
                                  {
                                      return balanceAndBlacklistStates[_account] & ((1 << 255) - 1);
                                  }
                                  /**
                                   * @inheritdoc FiatTokenV1
                                   */
                                  function approve(address spender, uint256 value)
                                      external
                                      override
                                      whenNotPaused
                                      returns (bool)
                                  {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  /**
                                   * @inheritdoc FiatTokenV2
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external override whenNotPaused {
                                      _permit(owner, spender, value, deadline, v, r, s);
                                  }
                                  /**
                                   * @inheritdoc FiatTokenV2
                                   */
                                  function increaseAllowance(address spender, uint256 increment)
                                      external
                                      override
                                      whenNotPaused
                                      returns (bool)
                                  {
                                      _increaseAllowance(msg.sender, spender, increment);
                                      return true;
                                  }
                                  /**
                                   * @inheritdoc FiatTokenV2
                                   */
                                  function decreaseAllowance(address spender, uint256 decrement)
                                      external
                                      override
                                      whenNotPaused
                                      returns (bool)
                                  {
                                      _decreaseAllowance(msg.sender, spender, decrement);
                                      return true;
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.2 <0.8.0;
                              /**
                               * @dev Collection of functions related to the address type
                               */
                              library Address {
                                  /**
                                   * @dev Returns true if `account` is a contract.
                                   *
                                   * [IMPORTANT]
                                   * ====
                                   * It is unsafe to assume that an address for which this function returns
                                   * false is an externally-owned account (EOA) and not a contract.
                                   *
                                   * Among others, `isContract` will return false for the following
                                   * types of addresses:
                                   *
                                   *  - an externally-owned account
                                   *  - a contract in construction
                                   *  - an address where a contract will be created
                                   *  - an address where a contract lived, but was destroyed
                                   * ====
                                   */
                                  function isContract(address account) internal view returns (bool) {
                                      // This method relies on extcodesize, which returns 0 for contracts in
                                      // construction, since the code is only stored at the end of the
                                      // constructor execution.
                                      uint256 size;
                                      // solhint-disable-next-line no-inline-assembly
                                      assembly { size := extcodesize(account) }
                                      return size > 0;
                                  }
                                  /**
                                   * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
                                   * `recipient`, forwarding all available gas and reverting on errors.
                                   *
                                   * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
                                   * of certain opcodes, possibly making contracts go over the 2300 gas limit
                                   * imposed by `transfer`, making them unable to receive funds via
                                   * `transfer`. {sendValue} removes this limitation.
                                   *
                                   * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
                                   *
                                   * IMPORTANT: because control is transferred to `recipient`, care must be
                                   * taken to not create reentrancy vulnerabilities. Consider using
                                   * {ReentrancyGuard} or the
                                   * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
                                   */
                                  function sendValue(address payable recipient, uint256 amount) internal {
                                      require(address(this).balance >= amount, "Address: insufficient balance");
                                      // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
                                      (bool success, ) = recipient.call{ value: amount }("");
                                      require(success, "Address: unable to send value, recipient may have reverted");
                                  }
                                  /**
                                   * @dev Performs a Solidity function call using a low level `call`. A
                                   * plain`call` is an unsafe replacement for a function call: use this
                                   * function instead.
                                   *
                                   * If `target` reverts with a revert reason, it is bubbled up by this
                                   * function (like regular Solidity function calls).
                                   *
                                   * Returns the raw returned data. To convert to the expected return value,
                                   * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
                                   *
                                   * Requirements:
                                   *
                                   * - `target` must be a contract.
                                   * - calling `target` with `data` must not revert.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCall(address target, bytes memory data) internal returns (bytes memory) {
                                    return functionCall(target, data, "Address: low-level call failed");
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
                                   * `errorMessage` as a fallback revert reason when `target` reverts.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                      return functionCallWithValue(target, data, 0, errorMessage);
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but also transferring `value` wei to `target`.
                                   *
                                   * Requirements:
                                   *
                                   * - the calling contract must have an ETH balance of at least `value`.
                                   * - the called Solidity function must be `payable`.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
                                      return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
                                   * with `errorMessage` as a fallback revert reason when `target` reverts.
                                   *
                                   * _Available since v3.1._
                                   */
                                  function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
                                      require(address(this).balance >= value, "Address: insufficient balance for call");
                                      require(isContract(target), "Address: call to non-contract");
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, bytes memory returndata) = target.call{ value: value }(data);
                                      return _verifyCallResult(success, returndata, errorMessage);
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but performing a static call.
                                   *
                                   * _Available since v3.3._
                                   */
                                  function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
                                      return functionStaticCall(target, data, "Address: low-level static call failed");
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                                   * but performing a static call.
                                   *
                                   * _Available since v3.3._
                                   */
                                  function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
                                      require(isContract(target), "Address: static call to non-contract");
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, bytes memory returndata) = target.staticcall(data);
                                      return _verifyCallResult(success, returndata, errorMessage);
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
                                   * but performing a delegate call.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
                                      return functionDelegateCall(target, data, "Address: low-level delegate call failed");
                                  }
                                  /**
                                   * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
                                   * but performing a delegate call.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
                                      require(isContract(target), "Address: delegate call to non-contract");
                                      // solhint-disable-next-line avoid-low-level-calls
                                      (bool success, bytes memory returndata) = target.delegatecall(data);
                                      return _verifyCallResult(success, returndata, errorMessage);
                                  }
                                  function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
                                      if (success) {
                                          return returndata;
                                      } else {
                                          // Look for revert reason and bubble it up if present
                                          if (returndata.length > 0) {
                                              // The easiest way to bubble the revert reason is using memory via assembly
                                              // solhint-disable-next-line no-inline-assembly
                                              assembly {
                                                  let returndata_size := mload(returndata)
                                                  revert(add(32, returndata), returndata_size)
                                              }
                                          } else {
                                              revert(errorMessage);
                                          }
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <0.8.0;
                              import "./IERC20.sol";
                              import "../../math/SafeMath.sol";
                              import "../../utils/Address.sol";
                              /**
                               * @title SafeERC20
                               * @dev Wrappers around ERC20 operations that throw on failure (when the token
                               * contract returns false). Tokens that return no value (and instead revert or
                               * throw on failure) are also supported, non-reverting calls are assumed to be
                               * successful.
                               * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
                               * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
                               */
                              library SafeERC20 {
                                  using SafeMath for uint256;
                                  using Address for address;
                                  function safeTransfer(IERC20 token, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
                                  }
                                  function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
                                  }
                                  /**
                                   * @dev Deprecated. This function has issues similar to the ones found in
                                   * {IERC20-approve}, and its usage is discouraged.
                                   *
                                   * Whenever possible, use {safeIncreaseAllowance} and
                                   * {safeDecreaseAllowance} instead.
                                   */
                                  function safeApprove(IERC20 token, address spender, uint256 value) internal {
                                      // safeApprove should only be called when setting an initial allowance,
                                      // or when resetting it to zero. To increase and decrease it, use
                                      // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
                                      // solhint-disable-next-line max-line-length
                                      require((value == 0) || (token.allowance(address(this), spender) == 0),
                                          "SafeERC20: approve from non-zero to non-zero allowance"
                                      );
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
                                  }
                                  function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).add(value);
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                  }
                                  function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
                                      uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
                                      _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
                                  }
                                  /**
                                   * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
                                   * on the return value: the return value is optional (but if data is returned, it must not be false).
                                   * @param token The token targeted by the call.
                                   * @param data The call data (encoded using abi.encode or one of its variants).
                                   */
                                  function _callOptionalReturn(IERC20 token, bytes memory data) private {
                                      // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
                                      // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
                                      // the target address contains contract code and also asserts for success in the low-level call.
                                      bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
                                      if (returndata.length > 0) { // Return data is optional
                                          // solhint-disable-next-line max-line-length
                                          require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
                                      }
                                  }
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <0.8.0;
                              /**
                               * @dev Interface of the ERC20 standard as defined in the EIP.
                               */
                              interface IERC20 {
                                  /**
                                   * @dev Returns the amount of tokens in existence.
                                   */
                                  function totalSupply() external view returns (uint256);
                                  /**
                                   * @dev Returns the amount of tokens owned by `account`.
                                   */
                                  function balanceOf(address account) external view returns (uint256);
                                  /**
                                   * @dev Moves `amount` tokens from the caller's account to `recipient`.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transfer(address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Returns the remaining number of tokens that `spender` will be
                                   * allowed to spend on behalf of `owner` through {transferFrom}. This is
                                   * zero by default.
                                   *
                                   * This value changes when {approve} or {transferFrom} are called.
                                   */
                                  function allowance(address owner, address spender) external view returns (uint256);
                                  /**
                                   * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * IMPORTANT: Beware that changing an allowance with this method brings the risk
                                   * that someone may use both the old and the new allowance by unfortunate
                                   * transaction ordering. One possible solution to mitigate this race
                                   * condition is to first reduce the spender's allowance to 0 and set the
                                   * desired value afterwards:
                                   * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
                                   *
                                   * Emits an {Approval} event.
                                   */
                                  function approve(address spender, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Moves `amount` tokens from `sender` to `recipient` using the
                                   * allowance mechanism. `amount` is then deducted from the caller's
                                   * allowance.
                                   *
                                   * Returns a boolean value indicating whether the operation succeeded.
                                   *
                                   * Emits a {Transfer} event.
                                   */
                                  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
                                  /**
                                   * @dev Emitted when `value` tokens are moved from one account (`from`) to
                                   * another (`to`).
                                   *
                                   * Note that `value` may be zero.
                                   */
                                  event Transfer(address indexed from, address indexed to, uint256 value);
                                  /**
                                   * @dev Emitted when the allowance of a `spender` for an `owner` is set by
                                   * a call to {approve}. `value` is the new allowance.
                                   */
                                  event Approval(address indexed owner, address indexed spender, uint256 value);
                              }
                              // SPDX-License-Identifier: MIT
                              pragma solidity >=0.6.0 <0.8.0;
                              /**
                               * @dev Wrappers over Solidity's arithmetic operations with added overflow
                               * checks.
                               *
                               * Arithmetic operations in Solidity wrap on overflow. This can easily result
                               * in bugs, because programmers usually assume that an overflow raises an
                               * error, which is the standard behavior in high level programming languages.
                               * `SafeMath` restores this intuition by reverting the transaction when an
                               * operation overflows.
                               *
                               * Using this library instead of the unchecked operations eliminates an entire
                               * class of bugs, so it's recommended to use it always.
                               */
                              library SafeMath {
                                  /**
                                   * @dev Returns the addition of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      uint256 c = a + b;
                                      if (c < a) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the substraction of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b > a) return (false, 0);
                                      return (true, a - b);
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
                                      // benefit is lost if 'b' is also tested.
                                      // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
                                      if (a == 0) return (true, 0);
                                      uint256 c = a * b;
                                      if (c / a != b) return (false, 0);
                                      return (true, c);
                                  }
                                  /**
                                   * @dev Returns the division of two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a / b);
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
                                   *
                                   * _Available since v3.4._
                                   */
                                  function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
                                      if (b == 0) return (false, 0);
                                      return (true, a % b);
                                  }
                                  /**
                                   * @dev Returns the addition of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `+` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Addition cannot overflow.
                                   */
                                  function add(uint256 a, uint256 b) internal pure returns (uint256) {
                                      uint256 c = a + b;
                                      require(c >= a, "SafeMath: addition overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting on
                                   * overflow (when the result is negative).
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b <= a, "SafeMath: subtraction overflow");
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the multiplication of two unsigned integers, reverting on
                                   * overflow.
                                   *
                                   * Counterpart to Solidity's `*` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Multiplication cannot overflow.
                                   */
                                  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
                                      if (a == 0) return 0;
                                      uint256 c = a * b;
                                      require(c / a == b, "SafeMath: multiplication overflow");
                                      return c;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: division by zero");
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting when dividing by zero.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
                                      require(b > 0, "SafeMath: modulo by zero");
                                      return a % b;
                                  }
                                  /**
                                   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
                                   * overflow (when the result is negative).
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {trySub}.
                                   *
                                   * Counterpart to Solidity's `-` operator.
                                   *
                                   * Requirements:
                                   *
                                   * - Subtraction cannot overflow.
                                   */
                                  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b <= a, errorMessage);
                                      return a - b;
                                  }
                                  /**
                                   * @dev Returns the integer division of two unsigned integers, reverting with custom message on
                                   * division by zero. The result is rounded towards zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryDiv}.
                                   *
                                   * Counterpart to Solidity's `/` operator. Note: this function uses a
                                   * `revert` opcode (which leaves remaining gas untouched) while Solidity
                                   * uses an invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a / b;
                                  }
                                  /**
                                   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
                                   * reverting with custom message when dividing by zero.
                                   *
                                   * CAUTION: This function is deprecated because it requires allocating memory for the error
                                   * message unnecessarily. For custom revert reasons use {tryMod}.
                                   *
                                   * Counterpart to Solidity's `%` operator. This function uses a `revert`
                                   * opcode (which leaves remaining gas untouched) while Solidity uses an
                                   * invalid opcode to revert (consuming all remaining gas).
                                   *
                                   * Requirements:
                                   *
                                   * - The divisor cannot be zero.
                                   */
                                  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
                                      require(b > 0, errorMessage);
                                      return a % b;
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { FiatTokenV2 } from "./FiatTokenV2.sol";
                              // solhint-disable func-name-mixedcase
                              /**
                               * @title FiatToken V2.1
                               * @notice ERC20 Token backed by fiat reserves, version 2.1
                               */
                              contract FiatTokenV2_1 is FiatTokenV2 {
                                  /**
                                   * @notice Initialize v2.1
                                   * @param lostAndFound  The address to which the locked funds are sent
                                   */
                                  function initializeV2_1(address lostAndFound) external {
                                      // solhint-disable-next-line reason-string
                                      require(_initializedVersion == 1);
                                      uint256 lockedAmount = _balanceOf(address(this));
                                      if (lockedAmount > 0) {
                                          _transfer(address(this), lostAndFound, lockedAmount);
                                      }
                                      _blacklist(address(this));
                                      _initializedVersion = 2;
                                  }
                                  /**
                                   * @notice Version string for the EIP712 domain separator
                                   * @return Version string
                                   */
                                  function version() external pure returns (string memory) {
                                      return "2";
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { FiatTokenV1_1 } from "../v1.1/FiatTokenV1_1.sol";
                              import { EIP712 } from "../util/EIP712.sol";
                              import { EIP3009 } from "./EIP3009.sol";
                              import { EIP2612 } from "./EIP2612.sol";
                              /**
                               * @title FiatToken V2
                               * @notice ERC20 Token backed by fiat reserves, version 2
                               */
                              contract FiatTokenV2 is FiatTokenV1_1, EIP3009, EIP2612 {
                                  uint8 internal _initializedVersion;
                                  /**
                                   * @notice Initialize v2
                                   * @param newName   New token name
                                   */
                                  function initializeV2(string calldata newName) external {
                                      // solhint-disable-next-line reason-string
                                      require(initialized && _initializedVersion == 0);
                                      name = newName;
                                      _DEPRECATED_CACHED_DOMAIN_SEPARATOR = EIP712.makeDomainSeparator(
                                          newName,
                                          "2"
                                      );
                                      _initializedVersion = 1;
                                  }
                                  /**
                                   * @notice Increase the allowance by a given increment
                                   * @param spender   Spender's address
                                   * @param increment Amount of increase in allowance
                                   * @return True if successful
                                   */
                                  function increaseAllowance(address spender, uint256 increment)
                                      external
                                      virtual
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(spender)
                                      returns (bool)
                                  {
                                      _increaseAllowance(msg.sender, spender, increment);
                                      return true;
                                  }
                                  /**
                                   * @notice Decrease the allowance by a given decrement
                                   * @param spender   Spender's address
                                   * @param decrement Amount of decrease in allowance
                                   * @return True if successful
                                   */
                                  function decreaseAllowance(address spender, uint256 decrement)
                                      external
                                      virtual
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(spender)
                                      returns (bool)
                                  {
                                      _decreaseAllowance(msg.sender, spender, decrement);
                                      return true;
                                  }
                                  /**
                                   * @notice Execute a transfer with a signed authorization
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function transferWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                      _transferWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          v,
                                          r,
                                          s
                                      );
                                  }
                                  /**
                                   * @notice Receive a transfer with a signed authorization from the payer
                                   * @dev This has an additional check to ensure that the payee's address
                                   * matches the caller of this function to prevent front-running attacks.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function receiveWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused notBlacklisted(from) notBlacklisted(to) {
                                      _receiveWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          v,
                                          r,
                                          s
                                      );
                                  }
                                  /**
                                   * @notice Attempt to cancel an authorization
                                   * @dev Works only if the authorization is not yet used.
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function cancelAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) external whenNotPaused {
                                      _cancelAuthorization(authorizer, nonce, v, r, s);
                                  }
                                  /**
                                   * @notice Update allowance with a signed permit
                                   * @param owner       Token owner's address (Authorizer)
                                   * @param spender     Spender's address
                                   * @param value       Amount of allowance
                                   * @param deadline    The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                                   * @param v           v of the signature
                                   * @param r           r of the signature
                                   * @param s           s of the signature
                                   */
                                  function permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  )
                                      external
                                      virtual
                                      whenNotPaused
                                      notBlacklisted(owner)
                                      notBlacklisted(spender)
                                  {
                                      _permit(owner, spender, value, deadline, v, r, s);
                                  }
                                  /**
                                   * @dev Internal function to increase the allowance by a given increment
                                   * @param owner     Token owner's address
                                   * @param spender   Spender's address
                                   * @param increment Amount of increase
                                   */
                                  function _increaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 increment
                                  ) internal override {
                                      _approve(owner, spender, allowed[owner][spender].add(increment));
                                  }
                                  /**
                                   * @dev Internal function to decrease the allowance by a given decrement
                                   * @param owner     Token owner's address
                                   * @param spender   Spender's address
                                   * @param decrement Amount of decrease
                                   */
                                  function _decreaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 decrement
                                  ) internal override {
                                      _approve(
                                          owner,
                                          spender,
                                          allowed[owner][spender].sub(
                                              decrement,
                                              "ERC20: decreased allowance below zero"
                                          )
                                      );
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              // solhint-disable func-name-mixedcase
                              /**
                               * @title EIP712 Domain
                               */
                              contract EIP712Domain {
                                  // was originally DOMAIN_SEPARATOR
                                  // but that has been moved to a method so we can override it in V2_2+
                                  bytes32 internal _DEPRECATED_CACHED_DOMAIN_SEPARATOR;
                                  /**
                                   * @notice Get the EIP712 Domain Separator.
                                   * @return The bytes32 EIP712 domain separator.
                                   */
                                  function DOMAIN_SEPARATOR() external view returns (bytes32) {
                                      return _domainSeparator();
                                  }
                                  /**
                                   * @dev Internal method to get the EIP712 Domain Separator.
                                   * @return The bytes32 EIP712 domain separator.
                                   */
                                  function _domainSeparator() internal virtual view returns (bytes32) {
                                      return _DEPRECATED_CACHED_DOMAIN_SEPARATOR;
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
                              import { EIP712Domain } from "./EIP712Domain.sol";
                              import { SignatureChecker } from "../util/SignatureChecker.sol";
                              import { MessageHashUtils } from "../util/MessageHashUtils.sol";
                              /**
                               * @title EIP-3009
                               * @notice Provide internal implementation for gas-abstracted transfers
                               * @dev Contracts that inherit from this must wrap these with publicly
                               * accessible functions, optionally adding modifiers where necessary
                               */
                              abstract contract EIP3009 is AbstractFiatTokenV2, EIP712Domain {
                                  // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                                  bytes32
                                      public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267;
                                  // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)")
                                  bytes32
                                      public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8;
                                  // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)")
                                  bytes32
                                      public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429;
                                  /**
                                   * @dev authorizer address => nonce => bool (true if nonce is used)
                                   */
                                  mapping(address => mapping(bytes32 => bool)) private _authorizationStates;
                                  event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
                                  event AuthorizationCanceled(
                                      address indexed authorizer,
                                      bytes32 indexed nonce
                                  );
                                  /**
                                   * @notice Returns the state of an authorization
                                   * @dev Nonces are randomly generated 32-byte data unique to the
                                   * authorizer's address
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @return True if the nonce is used
                                   */
                                  function authorizationState(address authorizer, bytes32 nonce)
                                      external
                                      view
                                      returns (bool)
                                  {
                                      return _authorizationStates[authorizer][nonce];
                                  }
                                  /**
                                   * @notice Execute a transfer with a signed authorization
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function _transferWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      _transferWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          abi.encodePacked(r, s, v)
                                      );
                                  }
                                  /**
                                   * @notice Execute a transfer with a signed authorization
                                   * @dev EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                                   */
                                  function _transferWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      bytes memory signature
                                  ) internal {
                                      _requireValidAuthorization(from, nonce, validAfter, validBefore);
                                      _requireValidSignature(
                                          from,
                                          keccak256(
                                              abi.encode(
                                                  TRANSFER_WITH_AUTHORIZATION_TYPEHASH,
                                                  from,
                                                  to,
                                                  value,
                                                  validAfter,
                                                  validBefore,
                                                  nonce
                                              )
                                          ),
                                          signature
                                      );
                                      _markAuthorizationAsUsed(from, nonce);
                                      _transfer(from, to, value);
                                  }
                                  /**
                                   * @notice Receive a transfer with a signed authorization from the payer
                                   * @dev This has an additional check to ensure that the payee's address
                                   * matches the caller of this function to prevent front-running attacks.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function _receiveWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      _receiveWithAuthorization(
                                          from,
                                          to,
                                          value,
                                          validAfter,
                                          validBefore,
                                          nonce,
                                          abi.encodePacked(r, s, v)
                                      );
                                  }
                                  /**
                                   * @notice Receive a transfer with a signed authorization from the payer
                                   * @dev This has an additional check to ensure that the payee's address
                                   * matches the caller of this function to prevent front-running attacks.
                                   * EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param from          Payer's address (Authorizer)
                                   * @param to            Payee's address
                                   * @param value         Amount to be transferred
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   * @param nonce         Unique nonce
                                   * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                                   */
                                  function _receiveWithAuthorization(
                                      address from,
                                      address to,
                                      uint256 value,
                                      uint256 validAfter,
                                      uint256 validBefore,
                                      bytes32 nonce,
                                      bytes memory signature
                                  ) internal {
                                      require(to == msg.sender, "FiatTokenV2: caller must be the payee");
                                      _requireValidAuthorization(from, nonce, validAfter, validBefore);
                                      _requireValidSignature(
                                          from,
                                          keccak256(
                                              abi.encode(
                                                  RECEIVE_WITH_AUTHORIZATION_TYPEHASH,
                                                  from,
                                                  to,
                                                  value,
                                                  validAfter,
                                                  validBefore,
                                                  nonce
                                              )
                                          ),
                                          signature
                                      );
                                      _markAuthorizationAsUsed(from, nonce);
                                      _transfer(from, to, value);
                                  }
                                  /**
                                   * @notice Attempt to cancel an authorization
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param v             v of the signature
                                   * @param r             r of the signature
                                   * @param s             s of the signature
                                   */
                                  function _cancelAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      _cancelAuthorization(authorizer, nonce, abi.encodePacked(r, s, v));
                                  }
                                  /**
                                   * @notice Attempt to cancel an authorization
                                   * @dev EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                                   */
                                  function _cancelAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      bytes memory signature
                                  ) internal {
                                      _requireUnusedAuthorization(authorizer, nonce);
                                      _requireValidSignature(
                                          authorizer,
                                          keccak256(
                                              abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, authorizer, nonce)
                                          ),
                                          signature
                                      );
                                      _authorizationStates[authorizer][nonce] = true;
                                      emit AuthorizationCanceled(authorizer, nonce);
                                  }
                                  /**
                                   * @notice Validates that signature against input data struct
                                   * @param signer        Signer's address
                                   * @param dataHash      Hash of encoded data struct
                                   * @param signature     Signature byte array produced by an EOA wallet or a contract wallet
                                   */
                                  function _requireValidSignature(
                                      address signer,
                                      bytes32 dataHash,
                                      bytes memory signature
                                  ) private view {
                                      require(
                                          SignatureChecker.isValidSignatureNow(
                                              signer,
                                              MessageHashUtils.toTypedDataHash(_domainSeparator(), dataHash),
                                              signature
                                          ),
                                          "FiatTokenV2: invalid signature"
                                      );
                                  }
                                  /**
                                   * @notice Check that an authorization is unused
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   */
                                  function _requireUnusedAuthorization(address authorizer, bytes32 nonce)
                                      private
                                      view
                                  {
                                      require(
                                          !_authorizationStates[authorizer][nonce],
                                          "FiatTokenV2: authorization is used or canceled"
                                      );
                                  }
                                  /**
                                   * @notice Check that authorization is valid
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   * @param validAfter    The time after which this is valid (unix time)
                                   * @param validBefore   The time before which this is valid (unix time)
                                   */
                                  function _requireValidAuthorization(
                                      address authorizer,
                                      bytes32 nonce,
                                      uint256 validAfter,
                                      uint256 validBefore
                                  ) private view {
                                      require(
                                          now > validAfter,
                                          "FiatTokenV2: authorization is not yet valid"
                                      );
                                      require(now < validBefore, "FiatTokenV2: authorization is expired");
                                      _requireUnusedAuthorization(authorizer, nonce);
                                  }
                                  /**
                                   * @notice Mark an authorization as used
                                   * @param authorizer    Authorizer's address
                                   * @param nonce         Nonce of the authorization
                                   */
                                  function _markAuthorizationAsUsed(address authorizer, bytes32 nonce)
                                      private
                                  {
                                      _authorizationStates[authorizer][nonce] = true;
                                      emit AuthorizationUsed(authorizer, nonce);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { AbstractFiatTokenV2 } from "./AbstractFiatTokenV2.sol";
                              import { EIP712Domain } from "./EIP712Domain.sol";
                              import { MessageHashUtils } from "../util/MessageHashUtils.sol";
                              import { SignatureChecker } from "../util/SignatureChecker.sol";
                              /**
                               * @title EIP-2612
                               * @notice Provide internal implementation for gas-abstracted approvals
                               */
                              abstract contract EIP2612 is AbstractFiatTokenV2, EIP712Domain {
                                  // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)")
                                  bytes32
                                      public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
                                  mapping(address => uint256) private _permitNonces;
                                  /**
                                   * @notice Nonces for permit
                                   * @param owner Token owner's address (Authorizer)
                                   * @return Next nonce
                                   */
                                  function nonces(address owner) external view returns (uint256) {
                                      return _permitNonces[owner];
                                  }
                                  /**
                                   * @notice Verify a signed approval permit and execute if valid
                                   * @param owner     Token owner's address (Authorizer)
                                   * @param spender   Spender's address
                                   * @param value     Amount of allowance
                                   * @param deadline  The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                                   * @param v         v of the signature
                                   * @param r         r of the signature
                                   * @param s         s of the signature
                                   */
                                  function _permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal {
                                      _permit(owner, spender, value, deadline, abi.encodePacked(r, s, v));
                                  }
                                  /**
                                   * @notice Verify a signed approval permit and execute if valid
                                   * @dev EOA wallet signatures should be packed in the order of r, s, v.
                                   * @param owner      Token owner's address (Authorizer)
                                   * @param spender    Spender's address
                                   * @param value      Amount of allowance
                                   * @param deadline   The time at which the signature expires (unix time), or max uint256 value to signal no expiration
                                   * @param signature  Signature byte array signed by an EOA wallet or a contract wallet
                                   */
                                  function _permit(
                                      address owner,
                                      address spender,
                                      uint256 value,
                                      uint256 deadline,
                                      bytes memory signature
                                  ) internal {
                                      require(
                                          deadline == type(uint256).max || deadline >= now,
                                          "FiatTokenV2: permit is expired"
                                      );
                                      bytes32 typedDataHash = MessageHashUtils.toTypedDataHash(
                                          _domainSeparator(),
                                          keccak256(
                                              abi.encode(
                                                  PERMIT_TYPEHASH,
                                                  owner,
                                                  spender,
                                                  value,
                                                  _permitNonces[owner]++,
                                                  deadline
                                              )
                                          )
                                      );
                                      require(
                                          SignatureChecker.isValidSignatureNow(
                                              owner,
                                              typedDataHash,
                                              signature
                                          ),
                                          "EIP2612: invalid signature"
                                      );
                                      _approve(owner, spender, value);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { AbstractFiatTokenV1 } from "../v1/AbstractFiatTokenV1.sol";
                              abstract contract AbstractFiatTokenV2 is AbstractFiatTokenV1 {
                                  function _increaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 increment
                                  ) internal virtual;
                                  function _decreaseAllowance(
                                      address owner,
                                      address spender,
                                      uint256 decrement
                                  ) internal virtual;
                              }
                              /**
                               * SPDX-License-Identifier: MIT
                               *
                               * Copyright (c) 2016 Smart Contract Solutions, Inc.
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              pragma solidity 0.6.12;
                              import { Ownable } from "./Ownable.sol";
                              /**
                               * @notice Base contract which allows children to implement an emergency stop
                               * mechanism
                               * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/feb665136c0dae9912e08397c1a21c4af3651ef3/contracts/lifecycle/Pausable.sol
                               * Modifications:
                               * 1. Added pauser role, switched pause/unpause to be onlyPauser (6/14/2018)
                               * 2. Removed whenNotPause/whenPaused from pause/unpause (6/14/2018)
                               * 3. Removed whenPaused (6/14/2018)
                               * 4. Switches ownable library to use ZeppelinOS (7/12/18)
                               * 5. Remove constructor (7/13/18)
                               * 6. Reformat, conform to Solidity 0.6 syntax and add error messages (5/13/20)
                               * 7. Make public functions external (5/27/20)
                               */
                              contract Pausable is Ownable {
                                  event Pause();
                                  event Unpause();
                                  event PauserChanged(address indexed newAddress);
                                  address public pauser;
                                  bool public paused = false;
                                  /**
                                   * @dev Modifier to make a function callable only when the contract is not paused.
                                   */
                                  modifier whenNotPaused() {
                                      require(!paused, "Pausable: paused");
                                      _;
                                  }
                                  /**
                                   * @dev throws if called by any account other than the pauser
                                   */
                                  modifier onlyPauser() {
                                      require(msg.sender == pauser, "Pausable: caller is not the pauser");
                                      _;
                                  }
                                  /**
                                   * @dev called by the owner to pause, triggers stopped state
                                   */
                                  function pause() external onlyPauser {
                                      paused = true;
                                      emit Pause();
                                  }
                                  /**
                                   * @dev called by the owner to unpause, returns to normal state
                                   */
                                  function unpause() external onlyPauser {
                                      paused = false;
                                      emit Unpause();
                                  }
                                  /**
                                   * @notice Updates the pauser address.
                                   * @param _newPauser The address of the new pauser.
                                   */
                                  function updatePauser(address _newPauser) external onlyOwner {
                                      require(
                                          _newPauser != address(0),
                                          "Pausable: new pauser is the zero address"
                                      );
                                      pauser = _newPauser;
                                      emit PauserChanged(pauser);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: MIT
                               *
                               * Copyright (c) 2018 zOS Global Limited.
                               * Copyright (c) 2018-2020 CENTRE SECZ
                               *
                               * Permission is hereby granted, free of charge, to any person obtaining a copy
                               * of this software and associated documentation files (the "Software"), to deal
                               * in the Software without restriction, including without limitation the rights
                               * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
                               * copies of the Software, and to permit persons to whom the Software is
                               * furnished to do so, subject to the following conditions:
                               *
                               * The above copyright notice and this permission notice shall be included in
                               * copies or substantial portions of the Software.
                               *
                               * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
                               * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
                               * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
                               * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
                               * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
                               * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
                               * SOFTWARE.
                               */
                              pragma solidity 0.6.12;
                              /**
                               * @notice The Ownable contract has an owner address, and provides basic
                               * authorization control functions
                               * @dev Forked from https://github.com/OpenZeppelin/openzeppelin-labs/blob/3887ab77b8adafba4a26ace002f3a684c1a3388b/upgradeability_ownership/contracts/ownership/Ownable.sol
                               * Modifications:
                               * 1. Consolidate OwnableStorage into this contract (7/13/18)
                               * 2. Reformat, conform to Solidity 0.6 syntax, and add error messages (5/13/20)
                               * 3. Make public functions external (5/27/20)
                               */
                              contract Ownable {
                                  // Owner of the contract
                                  address private _owner;
                                  /**
                                   * @dev Event to show ownership has been transferred
                                   * @param previousOwner representing the address of the previous owner
                                   * @param newOwner representing the address of the new owner
                                   */
                                  event OwnershipTransferred(address previousOwner, address newOwner);
                                  /**
                                   * @dev The constructor sets the original owner of the contract to the sender account.
                                   */
                                  constructor() public {
                                      setOwner(msg.sender);
                                  }
                                  /**
                                   * @dev Tells the address of the owner
                                   * @return the address of the owner
                                   */
                                  function owner() external view returns (address) {
                                      return _owner;
                                  }
                                  /**
                                   * @dev Sets a new owner address
                                   */
                                  function setOwner(address newOwner) internal {
                                      _owner = newOwner;
                                  }
                                  /**
                                   * @dev Throws if called by any account other than the owner.
                                   */
                                  modifier onlyOwner() {
                                      require(msg.sender == _owner, "Ownable: caller is not the owner");
                                      _;
                                  }
                                  /**
                                   * @dev Allows the current owner to transfer control of the contract to a newOwner.
                                   * @param newOwner The address to transfer ownership to.
                                   */
                                  function transferOwnership(address newOwner) external onlyOwner {
                                      require(
                                          newOwner != address(0),
                                          "Ownable: new owner is the zero address"
                                      );
                                      emit OwnershipTransferred(_owner, newOwner);
                                      setOwner(newOwner);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
                              import { AbstractFiatTokenV1 } from "./AbstractFiatTokenV1.sol";
                              import { Ownable } from "./Ownable.sol";
                              import { Pausable } from "./Pausable.sol";
                              import { Blacklistable } from "./Blacklistable.sol";
                              /**
                               * @title FiatToken
                               * @dev ERC20 Token backed by fiat reserves
                               */
                              contract FiatTokenV1 is AbstractFiatTokenV1, Ownable, Pausable, Blacklistable {
                                  using SafeMath for uint256;
                                  string public name;
                                  string public symbol;
                                  uint8 public decimals;
                                  string public currency;
                                  address public masterMinter;
                                  bool internal initialized;
                                  /// @dev A mapping that stores the balance and blacklist states for a given address.
                                  /// The first bit defines whether the address is blacklisted (1 if blacklisted, 0 otherwise).
                                  /// The last 255 bits define the balance for the address.
                                  mapping(address => uint256) internal balanceAndBlacklistStates;
                                  mapping(address => mapping(address => uint256)) internal allowed;
                                  uint256 internal totalSupply_ = 0;
                                  mapping(address => bool) internal minters;
                                  mapping(address => uint256) internal minterAllowed;
                                  event Mint(address indexed minter, address indexed to, uint256 amount);
                                  event Burn(address indexed burner, uint256 amount);
                                  event MinterConfigured(address indexed minter, uint256 minterAllowedAmount);
                                  event MinterRemoved(address indexed oldMinter);
                                  event MasterMinterChanged(address indexed newMasterMinter);
                                  /**
                                   * @notice Initializes the fiat token contract.
                                   * @param tokenName       The name of the fiat token.
                                   * @param tokenSymbol     The symbol of the fiat token.
                                   * @param tokenCurrency   The fiat currency that the token represents.
                                   * @param tokenDecimals   The number of decimals that the token uses.
                                   * @param newMasterMinter The masterMinter address for the fiat token.
                                   * @param newPauser       The pauser address for the fiat token.
                                   * @param newBlacklister  The blacklister address for the fiat token.
                                   * @param newOwner        The owner of the fiat token.
                                   */
                                  function initialize(
                                      string memory tokenName,
                                      string memory tokenSymbol,
                                      string memory tokenCurrency,
                                      uint8 tokenDecimals,
                                      address newMasterMinter,
                                      address newPauser,
                                      address newBlacklister,
                                      address newOwner
                                  ) public {
                                      require(!initialized, "FiatToken: contract is already initialized");
                                      require(
                                          newMasterMinter != address(0),
                                          "FiatToken: new masterMinter is the zero address"
                                      );
                                      require(
                                          newPauser != address(0),
                                          "FiatToken: new pauser is the zero address"
                                      );
                                      require(
                                          newBlacklister != address(0),
                                          "FiatToken: new blacklister is the zero address"
                                      );
                                      require(
                                          newOwner != address(0),
                                          "FiatToken: new owner is the zero address"
                                      );
                                      name = tokenName;
                                      symbol = tokenSymbol;
                                      currency = tokenCurrency;
                                      decimals = tokenDecimals;
                                      masterMinter = newMasterMinter;
                                      pauser = newPauser;
                                      blacklister = newBlacklister;
                                      setOwner(newOwner);
                                      initialized = true;
                                  }
                                  /**
                                   * @dev Throws if called by any account other than a minter.
                                   */
                                  modifier onlyMinters() {
                                      require(minters[msg.sender], "FiatToken: caller is not a minter");
                                      _;
                                  }
                                  /**
                                   * @notice Mints fiat tokens to an address.
                                   * @param _to The address that will receive the minted tokens.
                                   * @param _amount The amount of tokens to mint. Must be less than or equal
                                   * to the minterAllowance of the caller.
                                   * @return True if the operation was successful.
                                   */
                                  function mint(address _to, uint256 _amount)
                                      external
                                      whenNotPaused
                                      onlyMinters
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(_to)
                                      returns (bool)
                                  {
                                      require(_to != address(0), "FiatToken: mint to the zero address");
                                      require(_amount > 0, "FiatToken: mint amount not greater than 0");
                                      uint256 mintingAllowedAmount = minterAllowed[msg.sender];
                                      require(
                                          _amount <= mintingAllowedAmount,
                                          "FiatToken: mint amount exceeds minterAllowance"
                                      );
                                      totalSupply_ = totalSupply_.add(_amount);
                                      _setBalance(_to, _balanceOf(_to).add(_amount));
                                      minterAllowed[msg.sender] = mintingAllowedAmount.sub(_amount);
                                      emit Mint(msg.sender, _to, _amount);
                                      emit Transfer(address(0), _to, _amount);
                                      return true;
                                  }
                                  /**
                                   * @dev Throws if called by any account other than the masterMinter
                                   */
                                  modifier onlyMasterMinter() {
                                      require(
                                          msg.sender == masterMinter,
                                          "FiatToken: caller is not the masterMinter"
                                      );
                                      _;
                                  }
                                  /**
                                   * @notice Gets the minter allowance for an account.
                                   * @param minter The address to check.
                                   * @return The remaining minter allowance for the account.
                                   */
                                  function minterAllowance(address minter) external view returns (uint256) {
                                      return minterAllowed[minter];
                                  }
                                  /**
                                   * @notice Checks if an account is a minter.
                                   * @param account The address to check.
                                   * @return True if the account is a minter, false if the account is not a minter.
                                   */
                                  function isMinter(address account) external view returns (bool) {
                                      return minters[account];
                                  }
                                  /**
                                   * @notice Gets the remaining amount of fiat tokens a spender is allowed to transfer on
                                   * behalf of the token owner.
                                   * @param owner   The token owner's address.
                                   * @param spender The spender's address.
                                   * @return The remaining allowance.
                                   */
                                  function allowance(address owner, address spender)
                                      external
                                      override
                                      view
                                      returns (uint256)
                                  {
                                      return allowed[owner][spender];
                                  }
                                  /**
                                   * @notice Gets the totalSupply of the fiat token.
                                   * @return The totalSupply of the fiat token.
                                   */
                                  function totalSupply() external override view returns (uint256) {
                                      return totalSupply_;
                                  }
                                  /**
                                   * @notice Gets the fiat token balance of an account.
                                   * @param account  The address to check.
                                   * @return balance The fiat token balance of the account.
                                   */
                                  function balanceOf(address account)
                                      external
                                      override
                                      view
                                      returns (uint256)
                                  {
                                      return _balanceOf(account);
                                  }
                                  /**
                                   * @notice Sets a fiat token allowance for a spender to spend on behalf of the caller.
                                   * @param spender The spender's address.
                                   * @param value   The allowance amount.
                                   * @return True if the operation was successful.
                                   */
                                  function approve(address spender, uint256 value)
                                      external
                                      virtual
                                      override
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(spender)
                                      returns (bool)
                                  {
                                      _approve(msg.sender, spender, value);
                                      return true;
                                  }
                                  /**
                                   * @dev Internal function to set allowance.
                                   * @param owner     Token owner's address.
                                   * @param spender   Spender's address.
                                   * @param value     Allowance amount.
                                   */
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) internal override {
                                      require(owner != address(0), "ERC20: approve from the zero address");
                                      require(spender != address(0), "ERC20: approve to the zero address");
                                      allowed[owner][spender] = value;
                                      emit Approval(owner, spender, value);
                                  }
                                  /**
                                   * @notice Transfers tokens from an address to another by spending the caller's allowance.
                                   * @dev The caller must have some fiat token allowance on the payer's tokens.
                                   * @param from  Payer's address.
                                   * @param to    Payee's address.
                                   * @param value Transfer amount.
                                   * @return True if the operation was successful.
                                   */
                                  function transferFrom(
                                      address from,
                                      address to,
                                      uint256 value
                                  )
                                      external
                                      override
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(from)
                                      notBlacklisted(to)
                                      returns (bool)
                                  {
                                      require(
                                          value <= allowed[from][msg.sender],
                                          "ERC20: transfer amount exceeds allowance"
                                      );
                                      _transfer(from, to, value);
                                      allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
                                      return true;
                                  }
                                  /**
                                   * @notice Transfers tokens from the caller.
                                   * @param to    Payee's address.
                                   * @param value Transfer amount.
                                   * @return True if the operation was successful.
                                   */
                                  function transfer(address to, uint256 value)
                                      external
                                      override
                                      whenNotPaused
                                      notBlacklisted(msg.sender)
                                      notBlacklisted(to)
                                      returns (bool)
                                  {
                                      _transfer(msg.sender, to, value);
                                      return true;
                                  }
                                  /**
                                   * @dev Internal function to process transfers.
                                   * @param from  Payer's address.
                                   * @param to    Payee's address.
                                   * @param value Transfer amount.
                                   */
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) internal override {
                                      require(from != address(0), "ERC20: transfer from the zero address");
                                      require(to != address(0), "ERC20: transfer to the zero address");
                                      require(
                                          value <= _balanceOf(from),
                                          "ERC20: transfer amount exceeds balance"
                                      );
                                      _setBalance(from, _balanceOf(from).sub(value));
                                      _setBalance(to, _balanceOf(to).add(value));
                                      emit Transfer(from, to, value);
                                  }
                                  /**
                                   * @notice Adds or updates a new minter with a mint allowance.
                                   * @param minter The address of the minter.
                                   * @param minterAllowedAmount The minting amount allowed for the minter.
                                   * @return True if the operation was successful.
                                   */
                                  function configureMinter(address minter, uint256 minterAllowedAmount)
                                      external
                                      whenNotPaused
                                      onlyMasterMinter
                                      returns (bool)
                                  {
                                      minters[minter] = true;
                                      minterAllowed[minter] = minterAllowedAmount;
                                      emit MinterConfigured(minter, minterAllowedAmount);
                                      return true;
                                  }
                                  /**
                                   * @notice Removes a minter.
                                   * @param minter The address of the minter to remove.
                                   * @return True if the operation was successful.
                                   */
                                  function removeMinter(address minter)
                                      external
                                      onlyMasterMinter
                                      returns (bool)
                                  {
                                      minters[minter] = false;
                                      minterAllowed[minter] = 0;
                                      emit MinterRemoved(minter);
                                      return true;
                                  }
                                  /**
                                   * @notice Allows a minter to burn some of its own tokens.
                                   * @dev The caller must be a minter, must not be blacklisted, and the amount to burn
                                   * should be less than or equal to the account's balance.
                                   * @param _amount the amount of tokens to be burned.
                                   */
                                  function burn(uint256 _amount)
                                      external
                                      whenNotPaused
                                      onlyMinters
                                      notBlacklisted(msg.sender)
                                  {
                                      uint256 balance = _balanceOf(msg.sender);
                                      require(_amount > 0, "FiatToken: burn amount not greater than 0");
                                      require(balance >= _amount, "FiatToken: burn amount exceeds balance");
                                      totalSupply_ = totalSupply_.sub(_amount);
                                      _setBalance(msg.sender, balance.sub(_amount));
                                      emit Burn(msg.sender, _amount);
                                      emit Transfer(msg.sender, address(0), _amount);
                                  }
                                  /**
                                   * @notice Updates the master minter address.
                                   * @param _newMasterMinter The address of the new master minter.
                                   */
                                  function updateMasterMinter(address _newMasterMinter) external onlyOwner {
                                      require(
                                          _newMasterMinter != address(0),
                                          "FiatToken: new masterMinter is the zero address"
                                      );
                                      masterMinter = _newMasterMinter;
                                      emit MasterMinterChanged(masterMinter);
                                  }
                                  /**
                                   * @inheritdoc Blacklistable
                                   */
                                  function _blacklist(address _account) internal override {
                                      _setBlacklistState(_account, true);
                                  }
                                  /**
                                   * @inheritdoc Blacklistable
                                   */
                                  function _unBlacklist(address _account) internal override {
                                      _setBlacklistState(_account, false);
                                  }
                                  /**
                                   * @dev Helper method that sets the blacklist state of an account.
                                   * @param _account         The address of the account.
                                   * @param _shouldBlacklist True if the account should be blacklisted, false if the account should be unblacklisted.
                                   */
                                  function _setBlacklistState(address _account, bool _shouldBlacklist)
                                      internal
                                      virtual
                                  {
                                      _deprecatedBlacklisted[_account] = _shouldBlacklist;
                                  }
                                  /**
                                   * @dev Helper method that sets the balance of an account.
                                   * @param _account The address of the account.
                                   * @param _balance The new fiat token balance of the account.
                                   */
                                  function _setBalance(address _account, uint256 _balance) internal virtual {
                                      balanceAndBlacklistStates[_account] = _balance;
                                  }
                                  /**
                                   * @inheritdoc Blacklistable
                                   */
                                  function _isBlacklisted(address _account)
                                      internal
                                      virtual
                                      override
                                      view
                                      returns (bool)
                                  {
                                      return _deprecatedBlacklisted[_account];
                                  }
                                  /**
                                   * @dev Helper method to obtain the balance of an account.
                                   * @param _account  The address of the account.
                                   * @return          The fiat token balance of the account.
                                   */
                                  function _balanceOf(address _account)
                                      internal
                                      virtual
                                      view
                                      returns (uint256)
                                  {
                                      return balanceAndBlacklistStates[_account];
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { Ownable } from "./Ownable.sol";
                              /**
                               * @title Blacklistable Token
                               * @dev Allows accounts to be blacklisted by a "blacklister" role
                               */
                              abstract contract Blacklistable is Ownable {
                                  address public blacklister;
                                  mapping(address => bool) internal _deprecatedBlacklisted;
                                  event Blacklisted(address indexed _account);
                                  event UnBlacklisted(address indexed _account);
                                  event BlacklisterChanged(address indexed newBlacklister);
                                  /**
                                   * @dev Throws if called by any account other than the blacklister.
                                   */
                                  modifier onlyBlacklister() {
                                      require(
                                          msg.sender == blacklister,
                                          "Blacklistable: caller is not the blacklister"
                                      );
                                      _;
                                  }
                                  /**
                                   * @dev Throws if argument account is blacklisted.
                                   * @param _account The address to check.
                                   */
                                  modifier notBlacklisted(address _account) {
                                      require(
                                          !_isBlacklisted(_account),
                                          "Blacklistable: account is blacklisted"
                                      );
                                      _;
                                  }
                                  /**
                                   * @notice Checks if account is blacklisted.
                                   * @param _account The address to check.
                                   * @return True if the account is blacklisted, false if the account is not blacklisted.
                                   */
                                  function isBlacklisted(address _account) external view returns (bool) {
                                      return _isBlacklisted(_account);
                                  }
                                  /**
                                   * @notice Adds account to blacklist.
                                   * @param _account The address to blacklist.
                                   */
                                  function blacklist(address _account) external onlyBlacklister {
                                      _blacklist(_account);
                                      emit Blacklisted(_account);
                                  }
                                  /**
                                   * @notice Removes account from blacklist.
                                   * @param _account The address to remove from the blacklist.
                                   */
                                  function unBlacklist(address _account) external onlyBlacklister {
                                      _unBlacklist(_account);
                                      emit UnBlacklisted(_account);
                                  }
                                  /**
                                   * @notice Updates the blacklister address.
                                   * @param _newBlacklister The address of the new blacklister.
                                   */
                                  function updateBlacklister(address _newBlacklister) external onlyOwner {
                                      require(
                                          _newBlacklister != address(0),
                                          "Blacklistable: new blacklister is the zero address"
                                      );
                                      blacklister = _newBlacklister;
                                      emit BlacklisterChanged(blacklister);
                                  }
                                  /**
                                   * @dev Checks if account is blacklisted.
                                   * @param _account The address to check.
                                   * @return true if the account is blacklisted, false otherwise.
                                   */
                                  function _isBlacklisted(address _account)
                                      internal
                                      virtual
                                      view
                                      returns (bool);
                                  /**
                                   * @dev Helper method that blacklists an account.
                                   * @param _account The address to blacklist.
                                   */
                                  function _blacklist(address _account) internal virtual;
                                  /**
                                   * @dev Helper method that unblacklists an account.
                                   * @param _account The address to unblacklist.
                                   */
                                  function _unBlacklist(address _account) internal virtual;
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              abstract contract AbstractFiatTokenV1 is IERC20 {
                                  function _approve(
                                      address owner,
                                      address spender,
                                      uint256 value
                                  ) internal virtual;
                                  function _transfer(
                                      address from,
                                      address to,
                                      uint256 value
                                  ) internal virtual;
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { Ownable } from "../v1/Ownable.sol";
                              import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
                              import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
                              contract Rescuable is Ownable {
                                  using SafeERC20 for IERC20;
                                  address private _rescuer;
                                  event RescuerChanged(address indexed newRescuer);
                                  /**
                                   * @notice Returns current rescuer
                                   * @return Rescuer's address
                                   */
                                  function rescuer() external view returns (address) {
                                      return _rescuer;
                                  }
                                  /**
                                   * @notice Revert if called by any account other than the rescuer.
                                   */
                                  modifier onlyRescuer() {
                                      require(msg.sender == _rescuer, "Rescuable: caller is not the rescuer");
                                      _;
                                  }
                                  /**
                                   * @notice Rescue ERC20 tokens locked up in this contract.
                                   * @param tokenContract ERC20 token contract address
                                   * @param to        Recipient address
                                   * @param amount    Amount to withdraw
                                   */
                                  function rescueERC20(
                                      IERC20 tokenContract,
                                      address to,
                                      uint256 amount
                                  ) external onlyRescuer {
                                      tokenContract.safeTransfer(to, amount);
                                  }
                                  /**
                                   * @notice Updates the rescuer address.
                                   * @param newRescuer The address of the new rescuer.
                                   */
                                  function updateRescuer(address newRescuer) external onlyOwner {
                                      require(
                                          newRescuer != address(0),
                                          "Rescuable: new rescuer is the zero address"
                                      );
                                      _rescuer = newRescuer;
                                      emit RescuerChanged(newRescuer);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { FiatTokenV1 } from "../v1/FiatTokenV1.sol";
                              import { Rescuable } from "./Rescuable.sol";
                              /**
                               * @title FiatTokenV1_1
                               * @dev ERC20 Token backed by fiat reserves
                               */
                              contract FiatTokenV1_1 is FiatTokenV1, Rescuable {
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              import { ECRecover } from "./ECRecover.sol";
                              import { IERC1271 } from "../interface/IERC1271.sol";
                              /**
                               * @dev Signature verification helper that can be used instead of `ECRecover.recover` to seamlessly support both ECDSA
                               * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets.
                               *
                               * Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/21bb89ef5bfc789b9333eb05e3ba2b7b284ac77c/contracts/utils/cryptography/SignatureChecker.sol
                               */
                              library SignatureChecker {
                                  /**
                                   * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the
                                   * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECRecover.recover`.
                                   * @param signer        Address of the claimed signer
                                   * @param digest        Keccak-256 hash digest of the signed message
                                   * @param signature     Signature byte array associated with hash
                                   */
                                  function isValidSignatureNow(
                                      address signer,
                                      bytes32 digest,
                                      bytes memory signature
                                  ) external view returns (bool) {
                                      if (!isContract(signer)) {
                                          return ECRecover.recover(digest, signature) == signer;
                                      }
                                      return isValidERC1271SignatureNow(signer, digest, signature);
                                  }
                                  /**
                                   * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated
                                   * against the signer smart contract using ERC1271.
                                   * @param signer        Address of the claimed signer
                                   * @param digest        Keccak-256 hash digest of the signed message
                                   * @param signature     Signature byte array associated with hash
                                   *
                                   * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus
                                   * change through time. It could return true at block N and false at block N+1 (or the opposite).
                                   */
                                  function isValidERC1271SignatureNow(
                                      address signer,
                                      bytes32 digest,
                                      bytes memory signature
                                  ) internal view returns (bool) {
                                      (bool success, bytes memory result) = signer.staticcall(
                                          abi.encodeWithSelector(
                                              IERC1271.isValidSignature.selector,
                                              digest,
                                              signature
                                          )
                                      );
                                      return (success &&
                                          result.length >= 32 &&
                                          abi.decode(result, (bytes32)) ==
                                          bytes32(IERC1271.isValidSignature.selector));
                                  }
                                  /**
                                   * @dev Checks if the input address is a smart contract.
                                   */
                                  function isContract(address addr) internal view returns (bool) {
                                      uint256 size;
                                      assembly {
                                          size := extcodesize(addr)
                                      }
                                      return size > 0;
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              /**
                               * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
                               *
                               * The library provides methods for generating a hash of a message that conforms to the
                               * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
                               * specifications.
                               */
                              library MessageHashUtils {
                                  /**
                                   * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`).
                                   * Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/21bb89ef5bfc789b9333eb05e3ba2b7b284ac77c/contracts/utils/cryptography/MessageHashUtils.sol
                                   *
                                   * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
                                   * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the
                                   * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
                                   *
                                   * @param domainSeparator    Domain separator
                                   * @param structHash         Hashed EIP-712 data struct
                                   * @return digest            The keccak256 digest of an EIP-712 typed data
                                   */
                                  function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash)
                                      internal
                                      pure
                                      returns (bytes32 digest)
                                  {
                                      assembly {
                                          let ptr := mload(0x40)
                                          mstore(ptr, "\\x19\\x01")
                                          mstore(add(ptr, 0x02), domainSeparator)
                                          mstore(add(ptr, 0x22), structHash)
                                          digest := keccak256(ptr, 0x42)
                                      }
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              /**
                               * @title EIP712
                               * @notice A library that provides EIP712 helper functions
                               */
                              library EIP712 {
                                  /**
                                   * @notice Make EIP712 domain separator
                                   * @param name      Contract name
                                   * @param version   Contract version
                                   * @param chainId   Blockchain ID
                                   * @return Domain separator
                                   */
                                  function makeDomainSeparator(
                                      string memory name,
                                      string memory version,
                                      uint256 chainId
                                  ) internal view returns (bytes32) {
                                      return
                                          keccak256(
                                              abi.encode(
                                                  // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")
                                                  0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
                                                  keccak256(bytes(name)),
                                                  keccak256(bytes(version)),
                                                  chainId,
                                                  address(this)
                                              )
                                          );
                                  }
                                  /**
                                   * @notice Make EIP712 domain separator
                                   * @param name      Contract name
                                   * @param version   Contract version
                                   * @return Domain separator
                                   */
                                  function makeDomainSeparator(string memory name, string memory version)
                                      internal
                                      view
                                      returns (bytes32)
                                  {
                                      uint256 chainId;
                                      assembly {
                                          chainId := chainid()
                                      }
                                      return makeDomainSeparator(name, version, chainId);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              /**
                               * @title ECRecover
                               * @notice A library that provides a safe ECDSA recovery function
                               */
                              library ECRecover {
                                  /**
                                   * @notice Recover signer's address from a signed message
                                   * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/65e4ffde586ec89af3b7e9140bdc9235d1254853/contracts/cryptography/ECDSA.sol
                                   * Modifications: Accept v, r, and s as separate arguments
                                   * @param digest    Keccak-256 hash digest of the signed message
                                   * @param v         v of the signature
                                   * @param r         r of the signature
                                   * @param s         s of the signature
                                   * @return Signer address
                                   */
                                  function recover(
                                      bytes32 digest,
                                      uint8 v,
                                      bytes32 r,
                                      bytes32 s
                                  ) internal pure returns (address) {
                                      // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
                                      // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
                                      // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
                                      // signatures from current libraries generate a unique signature with an s-value in the lower half order.
                                      //
                                      // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
                                      // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
                                      // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
                                      // these malleable signatures as well.
                                      if (
                                          uint256(s) >
                                          0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
                                      ) {
                                          revert("ECRecover: invalid signature 's' value");
                                      }
                                      if (v != 27 && v != 28) {
                                          revert("ECRecover: invalid signature 'v' value");
                                      }
                                      // If the signature is valid (and not malleable), return the signer address
                                      address signer = ecrecover(digest, v, r, s);
                                      require(signer != address(0), "ECRecover: invalid signature");
                                      return signer;
                                  }
                                  /**
                                   * @notice Recover signer's address from a signed message
                                   * @dev Adapted from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/0053ee040a7ff1dbc39691c9e67a69f564930a88/contracts/utils/cryptography/ECDSA.sol
                                   * @param digest    Keccak-256 hash digest of the signed message
                                   * @param signature Signature byte array associated with hash
                                   * @return Signer address
                                   */
                                  function recover(bytes32 digest, bytes memory signature)
                                      internal
                                      pure
                                      returns (address)
                                  {
                                      require(signature.length == 65, "ECRecover: invalid signature length");
                                      bytes32 r;
                                      bytes32 s;
                                      uint8 v;
                                      // ecrecover takes the signature parameters, and the only way to get them
                                      // currently is to use assembly.
                                      /// @solidity memory-safe-assembly
                                      assembly {
                                          r := mload(add(signature, 0x20))
                                          s := mload(add(signature, 0x40))
                                          v := byte(0, mload(add(signature, 0x60)))
                                      }
                                      return recover(digest, v, r, s);
                                  }
                              }
                              /**
                               * SPDX-License-Identifier: Apache-2.0
                               *
                               * Copyright (c) 2023, Circle Internet Financial, LLC.
                               *
                               * Licensed under the Apache License, Version 2.0 (the "License");
                               * you may not use this file except in compliance with the License.
                               * You may obtain a copy of the License at
                               *
                               * http://www.apache.org/licenses/LICENSE-2.0
                               *
                               * Unless required by applicable law or agreed to in writing, software
                               * distributed under the License is distributed on an "AS IS" BASIS,
                               * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
                               * See the License for the specific language governing permissions and
                               * limitations under the License.
                               */
                              pragma solidity 0.6.12;
                              /**
                               * @dev Interface of the ERC1271 standard signature validation method for
                               * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
                               */
                              interface IERC1271 {
                                  /**
                                   * @dev Should return whether the signature provided is valid for the provided data
                                   * @param hash          Hash of the data to be signed
                                   * @param signature     Signature byte array associated with the provided data hash
                                   * @return magicValue   bytes4 magic value 0x1626ba7e when function passes
                                   */
                                  function isValidSignature(bytes32 hash, bytes memory signature)
                                      external
                                      view
                                      returns (bytes4 magicValue);
                              }