ETH Price: $2,023.18 (+0.09%)

Transaction Decoder

Block:
21592400 at Jan-10-2025 06:50:59 AM +UTC
Transaction Fee:
0.000379573702216628 ETH $0.77
Gas Used:
107,572 Gas / 3.528554849 Gwei

Emitted Events:

642 WETH9.Transfer( src=[Sender] 0x85b2189cd68fed3918f8c6ecdfdca204b9c78aea, dst=BoringVault, wad=553245407723575844 )
643 BoringVault.Transfer( from=0x0000000000000000000000000000000000000000, to=[Sender] 0x85b2189cd68fed3918f8c6ecdfdca204b9c78aea, amount=553012175374575661 )
644 BoringVault.Enter( from=[Sender] 0x85b2189cd68fed3918f8c6ecdfdca204b9c78aea, asset=WETH9, amount=553245407723575844, to=[Sender] 0x85b2189cd68fed3918f8c6ecdfdca204b9c78aea, shares=553012175374575661 )
645 TellerWithMultiAssetSupport.Deposit( nonce=4075, receiver=[Sender] 0x85b2189cd68fed3918f8c6ecdfdca204b9c78aea, depositAsset=WETH9, depositAmount=553245407723575844, shareAmount=553012175374575661, depositTimestamp=1736491859, shareLockPeriodAtTimeOfDeposit=0 )

Account State Difference:

  Address   Before After State Difference Code
0x83599937...86486b410
0x85b2189C...4B9c78AEa
0.007864101149638413 Eth
Nonce: 49
0.007484527447421785 Eth
Nonce: 50
0.000379573702216628
(beaverbuild)
9.297999375164227115 Eth9.297999579551027115 Eth0.0000002043868
0xC02aaA39...83C756Cc2
0xCbc0D283...eE0E9d807

Execution Trace

TellerWithMultiAssetSupport.deposit( depositAsset=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, depositAmount=553245407723575844, minimumMint=0 ) => ( shares=553012175374575661 )
  • RolesAuthority.canCall( user=0x85b2189Cd68FED3918F8C6ECdFdCa204B9c78AEa, target=0xCbc0D2838256919e55eB302Ce8c46d7eE0E9d807, functionSig=System.Byte[] ) => ( True )
  • AccountantWithRateProviders.getRateInQuoteSafe( quote=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ) => ( rateInQuote=1000421749030827767 )
  • BoringVault.enter( from=0x85b2189Cd68FED3918F8C6ECdFdCa204B9c78AEa, asset=0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, assetAmount=553245407723575844, to=0x85b2189Cd68FED3918F8C6ECdFdCa204B9c78AEa, shareAmount=553012175374575661 )
    • RolesAuthority.canCall( user=0xCbc0D2838256919e55eB302Ce8c46d7eE0E9d807, target=0x83599937c2C9bEA0E0E8ac096c6f32e86486b410, functionSig=System.Byte[] ) => ( True )
    • WETH9.transferFrom( src=0x85b2189Cd68FED3918F8C6ECdFdCa204B9c78AEa, dst=0x83599937c2C9bEA0E0E8ac096c6f32e86486b410, wad=553245407723575844 ) => ( True )
      File 1 of 5: TellerWithMultiAssetSupport
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      import {ERC20} from "@solmate/tokens/ERC20.sol";
      import {WETH} from "@solmate/tokens/WETH.sol";
      import {BoringVault} from "src/base/BoringVault.sol";
      import {AccountantWithRateProviders} from "src/base/Roles/AccountantWithRateProviders.sol";
      import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
      import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
      import {BeforeTransferHook} from "src/interfaces/BeforeTransferHook.sol";
      import {Auth, Authority} from "@solmate/auth/Auth.sol";
      import {ReentrancyGuard} from "@solmate/utils/ReentrancyGuard.sol";
      import {IPausable} from "src/interfaces/IPausable.sol";
      contract TellerWithMultiAssetSupport is Auth, BeforeTransferHook, ReentrancyGuard, IPausable {
          using FixedPointMathLib for uint256;
          using SafeTransferLib for ERC20;
          using SafeTransferLib for WETH;
          // ========================================= STRUCTS =========================================
          /**
           * @param allowDeposits bool indicating whether or not deposits are allowed for this asset.
           * @param allowWithdraws bool indicating whether or not withdraws are allowed for this asset.
           * @param sharePremium uint16 indicating the premium to apply to the shares minted.
           *        where 40 represents a 40bps reduction in shares minted using this asset.
           */
          struct Asset {
              bool allowDeposits;
              bool allowWithdraws;
              uint16 sharePremium;
          }
          // ========================================= CONSTANTS =========================================
          /**
           * @notice Native address used to tell the contract to handle native asset deposits.
           */
          address internal constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
          /**
           * @notice The maximum possible share lock period.
           */
          uint256 internal constant MAX_SHARE_LOCK_PERIOD = 3 days;
          /**
           * @notice The maximum possible share premium that can be set using `updateAssetData`.
           * @dev 1,000 or 10%
           */
          uint16 internal constant MAX_SHARE_PREMIUM = 1_000;
          // ========================================= STATE =========================================
          /**
           * @notice Mapping ERC20s to their assetData.
           */
          mapping(ERC20 => Asset) public assetData;
          /**
           * @notice The deposit nonce used to map to a deposit hash.
           */
          uint96 public depositNonce;
          /**
           * @notice After deposits, shares are locked to the msg.sender's address
           *         for `shareLockPeriod`.
           * @dev During this time all trasnfers from msg.sender will revert, and
           *      deposits are refundable.
           */
          uint64 public shareLockPeriod;
          /**
           * @notice Used to pause calls to `deposit` and `depositWithPermit`.
           */
          bool public isPaused;
          /**
           * @dev Maps deposit nonce to keccak256(address receiver, address depositAsset, uint256 depositAmount, uint256 shareAmount, uint256 timestamp, uint256 shareLockPeriod).
           */
          mapping(uint256 => bytes32) public publicDepositHistory;
          /**
           * @notice Maps user address to the time their shares will be unlocked.
           */
          mapping(address => uint256) public shareUnlockTime;
          /**
           * @notice Mapping `from` address to a bool to deny them from transferring shares.
           */
          mapping(address => bool) public fromDenyList;
          /**
           * @notice Mapping `to` address to a bool to deny them from receiving shares.
           */
          mapping(address => bool) public toDenyList;
          /**
           * @notice Mapping `opeartor` address to a bool to deny them from calling `transfer` or `transferFrom`.
           */
          mapping(address => bool) public operatorDenyList;
          //============================== ERRORS ===============================
          error TellerWithMultiAssetSupport__ShareLockPeriodTooLong();
          error TellerWithMultiAssetSupport__SharesAreLocked();
          error TellerWithMultiAssetSupport__SharesAreUnLocked();
          error TellerWithMultiAssetSupport__BadDepositHash();
          error TellerWithMultiAssetSupport__AssetNotSupported();
          error TellerWithMultiAssetSupport__ZeroAssets();
          error TellerWithMultiAssetSupport__MinimumMintNotMet();
          error TellerWithMultiAssetSupport__MinimumAssetsNotMet();
          error TellerWithMultiAssetSupport__PermitFailedAndAllowanceTooLow();
          error TellerWithMultiAssetSupport__ZeroShares();
          error TellerWithMultiAssetSupport__DualDeposit();
          error TellerWithMultiAssetSupport__Paused();
          error TellerWithMultiAssetSupport__TransferDenied(address from, address to, address operator);
          error TellerWithMultiAssetSupport__SharePremiumTooLarge();
          error TellerWithMultiAssetSupport__CannotDepositNative();
          //============================== EVENTS ===============================
          event Paused();
          event Unpaused();
          event AssetDataUpdated(address indexed asset, bool allowDeposits, bool allowWithdraws, uint16 sharePremium);
          event Deposit(
              uint256 indexed nonce,
              address indexed receiver,
              address indexed depositAsset,
              uint256 depositAmount,
              uint256 shareAmount,
              uint256 depositTimestamp,
              uint256 shareLockPeriodAtTimeOfDeposit
          );
          event BulkDeposit(address indexed asset, uint256 depositAmount);
          event BulkWithdraw(address indexed asset, uint256 shareAmount);
          event DepositRefunded(uint256 indexed nonce, bytes32 depositHash, address indexed user);
          event DenyFrom(address indexed user);
          event DenyTo(address indexed user);
          event DenyOperator(address indexed user);
          event AllowFrom(address indexed user);
          event AllowTo(address indexed user);
          event AllowOperator(address indexed user);
          // =============================== MODIFIERS ===============================
          /**
           * @notice Reverts if the deposit asset is the native asset.
           */
          modifier revertOnNativeDeposit(address depositAsset) {
              if (depositAsset == NATIVE) revert TellerWithMultiAssetSupport__CannotDepositNative();
              _;
          }
          //============================== IMMUTABLES ===============================
          /**
           * @notice The BoringVault this contract is working with.
           */
          BoringVault public immutable vault;
          /**
           * @notice The AccountantWithRateProviders this contract is working with.
           */
          AccountantWithRateProviders public immutable accountant;
          /**
           * @notice One share of the BoringVault.
           */
          uint256 internal immutable ONE_SHARE;
          /**
           * @notice The native wrapper contract.
           */
          WETH public immutable nativeWrapper;
          constructor(address _owner, address _vault, address _accountant, address _weth)
              Auth(_owner, Authority(address(0)))
          {
              vault = BoringVault(payable(_vault));
              ONE_SHARE = 10 ** vault.decimals();
              accountant = AccountantWithRateProviders(_accountant);
              nativeWrapper = WETH(payable(_weth));
          }
          // ========================================= ADMIN FUNCTIONS =========================================
          /**
           * @notice Pause this contract, which prevents future calls to `deposit` and `depositWithPermit`.
           * @dev Callable by MULTISIG_ROLE.
           */
          function pause() external requiresAuth {
              isPaused = true;
              emit Paused();
          }
          /**
           * @notice Unpause this contract, which allows future calls to `deposit` and `depositWithPermit`.
           * @dev Callable by MULTISIG_ROLE.
           */
          function unpause() external requiresAuth {
              isPaused = false;
              emit Unpaused();
          }
          /**
           * @notice Updates the asset data for a given asset.
           * @dev The accountant must also support pricing this asset, else the `deposit` call will revert.
           * @dev Callable by OWNER_ROLE.
           */
          function updateAssetData(ERC20 asset, bool allowDeposits, bool allowWithdraws, uint16 sharePremium)
              external
              requiresAuth
          {
              if (sharePremium > MAX_SHARE_PREMIUM) revert TellerWithMultiAssetSupport__SharePremiumTooLarge();
              assetData[asset] = Asset(allowDeposits, allowWithdraws, sharePremium);
              emit AssetDataUpdated(address(asset), allowDeposits, allowWithdraws, sharePremium);
          }
          /**
           * @notice Sets the share lock period.
           * @dev This not only locks shares to the user address, but also serves as the pending deposit period, where deposits can be reverted.
           * @dev If a new shorter share lock period is set, users with pending share locks could make a new deposit to receive 1 wei shares,
           *      and have their shares unlock sooner than their original deposit allows. This state would allow for the user deposit to be refunded,
           *      but only if they have not transferred their shares out of there wallet. This is an accepted limitation, and should be known when decreasing
           *      the share lock period.
           * @dev Callable by OWNER_ROLE.
           */
          function setShareLockPeriod(uint64 _shareLockPeriod) external requiresAuth {
              if (_shareLockPeriod > MAX_SHARE_LOCK_PERIOD) revert TellerWithMultiAssetSupport__ShareLockPeriodTooLong();
              shareLockPeriod = _shareLockPeriod;
          }
          /**
           * @notice Deny a user from transferring or receiving shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function denyAll(address user) external requiresAuth {
              fromDenyList[user] = true;
              toDenyList[user] = true;
              operatorDenyList[user] = true;
              emit DenyFrom(user);
              emit DenyTo(user);
              emit DenyOperator(user);
          }
          /**
           * @notice Allow a user to transfer or receive shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function allowAll(address user) external requiresAuth {
              fromDenyList[user] = false;
              toDenyList[user] = false;
              operatorDenyList[user] = false;
              emit AllowFrom(user);
              emit AllowTo(user);
              emit AllowOperator(user);
          }
          /**
           * @notice Deny a user from transferring shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function denyFrom(address user) external requiresAuth {
              fromDenyList[user] = true;
              emit DenyFrom(user);
          }
          /**
           * @notice Allow a user to transfer shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function allowFrom(address user) external requiresAuth {
              fromDenyList[user] = false;
              emit AllowFrom(user);
          }
          /**
           * @notice Deny a user from receiving shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function denyTo(address user) external requiresAuth {
              toDenyList[user] = true;
              emit DenyTo(user);
          }
          /**
           * @notice Allow a user to receive shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function allowTo(address user) external requiresAuth {
              toDenyList[user] = false;
              emit AllowTo(user);
          }
          /**
           * @notice Deny an operator from transferring shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function denyOperator(address user) external requiresAuth {
              operatorDenyList[user] = true;
              emit DenyOperator(user);
          }
          /**
           * @notice Allow an operator to transfer shares.
           * @dev Callable by OWNER_ROLE, and DENIER_ROLE.
           */
          function allowOperator(address user) external requiresAuth {
              operatorDenyList[user] = false;
              emit AllowOperator(user);
          }
          // ========================================= BeforeTransferHook FUNCTIONS =========================================
          /**
           * @notice Implement beforeTransfer hook to check if shares are locked, or if `from`, `to`, or `operator` are on the deny list.
           * @notice If share lock period is set to zero, then users will be able to mint and transfer in the same tx.
           *         if this behavior is not desired then a share lock period of >=1 should be used.
           */
          function beforeTransfer(address from, address to, address operator) public view virtual {
              if (fromDenyList[from] || toDenyList[to] || operatorDenyList[operator]) {
                  revert TellerWithMultiAssetSupport__TransferDenied(from, to, operator);
              }
              if (shareUnlockTime[from] > block.timestamp) revert TellerWithMultiAssetSupport__SharesAreLocked();
          }
          // ========================================= REVERT DEPOSIT FUNCTIONS =========================================
          /**
           * @notice Allows DEPOSIT_REFUNDER_ROLE to revert a pending deposit.
           * @dev Once a deposit share lock period has passed, it can no longer be reverted.
           * @dev It is possible the admin does not setup the BoringVault to call the transfer hook,
           *      but this contract can still be saving share lock state. In the event this happens
           *      deposits are still refundable if the user has not transferred their shares.
           *      But there is no guarantee that the user has not transferred their shares.
           * @dev Callable by STRATEGIST_MULTISIG_ROLE.
           */
          function refundDeposit(
              uint256 nonce,
              address receiver,
              address depositAsset,
              uint256 depositAmount,
              uint256 shareAmount,
              uint256 depositTimestamp,
              uint256 shareLockUpPeriodAtTimeOfDeposit
          ) external requiresAuth {
              if ((block.timestamp - depositTimestamp) >= shareLockUpPeriodAtTimeOfDeposit) {
                  // Shares are already unlocked, so we can not revert deposit.
                  revert TellerWithMultiAssetSupport__SharesAreUnLocked();
              }
              bytes32 depositHash = keccak256(
                  abi.encode(
                      receiver, depositAsset, depositAmount, shareAmount, depositTimestamp, shareLockUpPeriodAtTimeOfDeposit
                  )
              );
              if (publicDepositHistory[nonce] != depositHash) revert TellerWithMultiAssetSupport__BadDepositHash();
              // Delete hash to prevent refund gas.
              delete publicDepositHistory[nonce];
              // If deposit used native asset, send user back wrapped native asset.
              depositAsset = depositAsset == NATIVE ? address(nativeWrapper) : depositAsset;
              // Burn shares and refund assets to receiver.
              vault.exit(receiver, ERC20(depositAsset), depositAmount, receiver, shareAmount);
              emit DepositRefunded(nonce, depositHash, receiver);
          }
          // ========================================= USER FUNCTIONS =========================================
          /**
           * @notice Allows users to deposit into the BoringVault, if this contract is not paused.
           * @dev Publicly callable.
           */
          function deposit(ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint)
              external
              payable
              requiresAuth
              nonReentrant
              returns (uint256 shares)
          {
              Asset memory asset = _beforeDeposit(depositAsset);
              address from;
              if (address(depositAsset) == NATIVE) {
                  if (msg.value == 0) revert TellerWithMultiAssetSupport__ZeroAssets();
                  nativeWrapper.deposit{value: msg.value}();
                  // Set depositAmount to msg.value.
                  depositAmount = msg.value;
                  nativeWrapper.safeApprove(address(vault), depositAmount);
                  // Update depositAsset to nativeWrapper.
                  depositAsset = nativeWrapper;
                  // Set from to this address since user transferred value.
                  from = address(this);
              } else {
                  if (msg.value > 0) revert TellerWithMultiAssetSupport__DualDeposit();
                  from = msg.sender;
              }
              shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, from, msg.sender, asset);
              _afterPublicDeposit(msg.sender, depositAsset, depositAmount, shares, shareLockPeriod);
          }
          /**
           * @notice Allows users to deposit into BoringVault using permit.
           * @dev Publicly callable.
           */
          function depositWithPermit(
              ERC20 depositAsset,
              uint256 depositAmount,
              uint256 minimumMint,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) external requiresAuth nonReentrant revertOnNativeDeposit(address(depositAsset)) returns (uint256 shares) {
              Asset memory asset = _beforeDeposit(depositAsset);
              _handlePermit(depositAsset, depositAmount, deadline, v, r, s);
              shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, msg.sender, msg.sender, asset);
              _afterPublicDeposit(msg.sender, depositAsset, depositAmount, shares, shareLockPeriod);
          }
          /**
           * @notice Allows on ramp role to deposit into this contract.
           * @dev Does NOT support native deposits.
           * @dev Callable by SOLVER_ROLE.
           */
          function bulkDeposit(ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint, address to)
              external
              requiresAuth
              nonReentrant
              returns (uint256 shares)
          {
              Asset memory asset = _beforeDeposit(depositAsset);
              shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, msg.sender, to, asset);
              emit BulkDeposit(address(depositAsset), depositAmount);
          }
          /**
           * @notice Allows off ramp role to withdraw from this contract.
           * @dev Callable by SOLVER_ROLE.
           */
          function bulkWithdraw(ERC20 withdrawAsset, uint256 shareAmount, uint256 minimumAssets, address to)
              external
              requiresAuth
              returns (uint256 assetsOut)
          {
              if (isPaused) revert TellerWithMultiAssetSupport__Paused();
              Asset memory asset = assetData[withdrawAsset];
              if (!asset.allowWithdraws) revert TellerWithMultiAssetSupport__AssetNotSupported();
              if (shareAmount == 0) revert TellerWithMultiAssetSupport__ZeroShares();
              assetsOut = shareAmount.mulDivDown(accountant.getRateInQuoteSafe(withdrawAsset), ONE_SHARE);
              if (assetsOut < minimumAssets) revert TellerWithMultiAssetSupport__MinimumAssetsNotMet();
              vault.exit(to, withdrawAsset, assetsOut, msg.sender, shareAmount);
              emit BulkWithdraw(address(withdrawAsset), shareAmount);
          }
          // ========================================= INTERNAL HELPER FUNCTIONS =========================================
          /**
           * @notice Implements a common ERC20 deposit into BoringVault.
           */
          function _erc20Deposit(
              ERC20 depositAsset,
              uint256 depositAmount,
              uint256 minimumMint,
              address from,
              address to,
              Asset memory asset
          ) internal returns (uint256 shares) {
              if (depositAmount == 0) revert TellerWithMultiAssetSupport__ZeroAssets();
              shares = depositAmount.mulDivDown(ONE_SHARE, accountant.getRateInQuoteSafe(depositAsset));
              shares = asset.sharePremium > 0 ? shares.mulDivDown(1e4 - asset.sharePremium, 1e4) : shares;
              if (shares < minimumMint) revert TellerWithMultiAssetSupport__MinimumMintNotMet();
              vault.enter(from, depositAsset, depositAmount, to, shares);
          }
          /**
           * @notice Handle pre-deposit checks.
           */
          function _beforeDeposit(ERC20 depositAsset) internal view returns (Asset memory asset) {
              if (isPaused) revert TellerWithMultiAssetSupport__Paused();
              asset = assetData[depositAsset];
              if (!asset.allowDeposits) revert TellerWithMultiAssetSupport__AssetNotSupported();
          }
          /**
           * @notice Handle share lock logic, and event.
           */
          function _afterPublicDeposit(
              address user,
              ERC20 depositAsset,
              uint256 depositAmount,
              uint256 shares,
              uint256 currentShareLockPeriod
          ) internal {
              // Increment then assign as its slightly more gas efficient.
              uint256 nonce = ++depositNonce;
              // Only set share unlock time and history if share lock period is greater than 0.
              if (currentShareLockPeriod > 0) {
                  shareUnlockTime[user] = block.timestamp + currentShareLockPeriod;
                  publicDepositHistory[nonce] = keccak256(
                      abi.encode(user, depositAsset, depositAmount, shares, block.timestamp, currentShareLockPeriod)
                  );
              }
              emit Deposit(nonce, user, address(depositAsset), depositAmount, shares, block.timestamp, currentShareLockPeriod);
          }
          /**
           * @notice Handle permit logic.
           */
          function _handlePermit(ERC20 depositAsset, uint256 depositAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
              internal
          {
              try depositAsset.permit(msg.sender, address(vault), depositAmount, deadline, v, r, s) {}
              catch {
                  if (depositAsset.allowance(msg.sender, address(vault)) < depositAmount) {
                      revert TellerWithMultiAssetSupport__PermitFailedAndAllowanceTooLow();
                  }
              }
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
      /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
      /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
      abstract contract ERC20 {
          /*//////////////////////////////////////////////////////////////
                                       EVENTS
          //////////////////////////////////////////////////////////////*/
          event Transfer(address indexed from, address indexed to, uint256 amount);
          event Approval(address indexed owner, address indexed spender, uint256 amount);
          /*//////////////////////////////////////////////////////////////
                                  METADATA STORAGE
          //////////////////////////////////////////////////////////////*/
          string public name;
          string public symbol;
          uint8 public immutable decimals;
          /*//////////////////////////////////////////////////////////////
                                    ERC20 STORAGE
          //////////////////////////////////////////////////////////////*/
          uint256 public totalSupply;
          mapping(address => uint256) public balanceOf;
          mapping(address => mapping(address => uint256)) public allowance;
          /*//////////////////////////////////////////////////////////////
                                  EIP-2612 STORAGE
          //////////////////////////////////////////////////////////////*/
          uint256 internal immutable INITIAL_CHAIN_ID;
          bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
          mapping(address => uint256) public nonces;
          /*//////////////////////////////////////////////////////////////
                                     CONSTRUCTOR
          //////////////////////////////////////////////////////////////*/
          constructor(
              string memory _name,
              string memory _symbol,
              uint8 _decimals
          ) {
              name = _name;
              symbol = _symbol;
              decimals = _decimals;
              INITIAL_CHAIN_ID = block.chainid;
              INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
          }
          /*//////////////////////////////////////////////////////////////
                                     ERC20 LOGIC
          //////////////////////////////////////////////////////////////*/
          function approve(address spender, uint256 amount) public virtual returns (bool) {
              allowance[msg.sender][spender] = amount;
              emit Approval(msg.sender, spender, amount);
              return true;
          }
          function transfer(address to, uint256 amount) public virtual returns (bool) {
              balanceOf[msg.sender] -= amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(msg.sender, to, amount);
              return true;
          }
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) public virtual returns (bool) {
              uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
              if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
              balanceOf[from] -= amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(from, to, amount);
              return true;
          }
          /*//////////////////////////////////////////////////////////////
                                   EIP-2612 LOGIC
          //////////////////////////////////////////////////////////////*/
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) public virtual {
              require(deadline >= block.timestamp, "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,
                                      nonces[owner]++,
                                      deadline
                                  )
                              )
                          )
                      ),
                      v,
                      r,
                      s
                  );
                  require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                  allowance[recoveredAddress][spender] = value;
              }
              emit Approval(owner, spender, value);
          }
          function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
              return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
          }
          function computeDomainSeparator() internal view virtual returns (bytes32) {
              return
                  keccak256(
                      abi.encode(
                          keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                          keccak256(bytes(name)),
                          keccak256("1"),
                          block.chainid,
                          address(this)
                      )
                  );
          }
          /*//////////////////////////////////////////////////////////////
                              INTERNAL MINT/BURN LOGIC
          //////////////////////////////////////////////////////////////*/
          function _mint(address to, uint256 amount) internal virtual {
              totalSupply += amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(address(0), to, amount);
          }
          function _burn(address from, uint256 amount) internal virtual {
              balanceOf[from] -= amount;
              // Cannot underflow because a user's balance
              // will never be larger than the total supply.
              unchecked {
                  totalSupply -= amount;
              }
              emit Transfer(from, address(0), amount);
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      import {ERC20} from "./ERC20.sol";
      import {SafeTransferLib} from "../utils/SafeTransferLib.sol";
      /// @notice Minimalist and modern Wrapped Ether implementation.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
      /// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
      contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
          using SafeTransferLib for address;
          event Deposit(address indexed from, uint256 amount);
          event Withdrawal(address indexed to, uint256 amount);
          function deposit() public payable virtual {
              _mint(msg.sender, msg.value);
              emit Deposit(msg.sender, msg.value);
          }
          function withdraw(uint256 amount) public virtual {
              _burn(msg.sender, amount);
              emit Withdrawal(msg.sender, amount);
              msg.sender.safeTransferETH(amount);
          }
          receive() external payable virtual {
              deposit();
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      import {Address} from "@openzeppelin/contracts/utils/Address.sol";
      import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
      import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
      import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
      import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
      import {ERC20} from "@solmate/tokens/ERC20.sol";
      import {BeforeTransferHook} from "src/interfaces/BeforeTransferHook.sol";
      import {Auth, Authority} from "@solmate/auth/Auth.sol";
      contract BoringVault is ERC20, Auth, ERC721Holder, ERC1155Holder {
          using Address for address;
          using SafeTransferLib for ERC20;
          using FixedPointMathLib for uint256;
          // ========================================= STATE =========================================
          /**
           * @notice Contract responsbile for implementing `beforeTransfer`.
           */
          BeforeTransferHook public hook;
          //============================== EVENTS ===============================
          event Enter(address indexed from, address indexed asset, uint256 amount, address indexed to, uint256 shares);
          event Exit(address indexed to, address indexed asset, uint256 amount, address indexed from, uint256 shares);
          //============================== CONSTRUCTOR ===============================
          constructor(address _owner, string memory _name, string memory _symbol, uint8 _decimals)
              ERC20(_name, _symbol, _decimals)
              Auth(_owner, Authority(address(0)))
          {}
          //============================== MANAGE ===============================
          /**
           * @notice Allows manager to make an arbitrary function call from this contract.
           * @dev Callable by MANAGER_ROLE.
           */
          function manage(address target, bytes calldata data, uint256 value)
              external
              requiresAuth
              returns (bytes memory result)
          {
              result = target.functionCallWithValue(data, value);
          }
          /**
           * @notice Allows manager to make arbitrary function calls from this contract.
           * @dev Callable by MANAGER_ROLE.
           */
          function manage(address[] calldata targets, bytes[] calldata data, uint256[] calldata values)
              external
              requiresAuth
              returns (bytes[] memory results)
          {
              uint256 targetsLength = targets.length;
              results = new bytes[](targetsLength);
              for (uint256 i; i < targetsLength; ++i) {
                  results[i] = targets[i].functionCallWithValue(data[i], values[i]);
              }
          }
          //============================== ENTER ===============================
          /**
           * @notice Allows minter to mint shares, in exchange for assets.
           * @dev If assetAmount is zero, no assets are transferred in.
           * @dev Callable by MINTER_ROLE.
           */
          function enter(address from, ERC20 asset, uint256 assetAmount, address to, uint256 shareAmount)
              external
              requiresAuth
          {
              // Transfer assets in
              if (assetAmount > 0) asset.safeTransferFrom(from, address(this), assetAmount);
              // Mint shares.
              _mint(to, shareAmount);
              emit Enter(from, address(asset), assetAmount, to, shareAmount);
          }
          //============================== EXIT ===============================
          /**
           * @notice Allows burner to burn shares, in exchange for assets.
           * @dev If assetAmount is zero, no assets are transferred out.
           * @dev Callable by BURNER_ROLE.
           */
          function exit(address to, ERC20 asset, uint256 assetAmount, address from, uint256 shareAmount)
              external
              requiresAuth
          {
              // Burn shares.
              _burn(from, shareAmount);
              // Transfer assets out.
              if (assetAmount > 0) asset.safeTransfer(to, assetAmount);
              emit Exit(to, address(asset), assetAmount, from, shareAmount);
          }
          //============================== BEFORE TRANSFER HOOK ===============================
          /**
           * @notice Sets the share locker.
           * @notice If set to zero address, the share locker logic is disabled.
           * @dev Callable by OWNER_ROLE.
           */
          function setBeforeTransferHook(address _hook) external requiresAuth {
              hook = BeforeTransferHook(_hook);
          }
          /**
           * @notice Call `beforeTransferHook` passing in `from` `to`, and `msg.sender`.
           */
          function _callBeforeTransfer(address from, address to) internal view {
              if (address(hook) != address(0)) hook.beforeTransfer(from, to, msg.sender);
          }
          function transfer(address to, uint256 amount) public override returns (bool) {
              _callBeforeTransfer(msg.sender, to);
              return super.transfer(to, amount);
          }
          function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
              _callBeforeTransfer(from, to);
              return super.transferFrom(from, to, amount);
          }
          //============================== RECEIVE ===============================
          receive() external payable {}
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
      import {IRateProvider} from "src/interfaces/IRateProvider.sol";
      import {ERC20} from "@solmate/tokens/ERC20.sol";
      import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
      import {BoringVault} from "src/base/BoringVault.sol";
      import {Auth, Authority} from "@solmate/auth/Auth.sol";
      import {IPausable} from "src/interfaces/IPausable.sol";
      contract AccountantWithRateProviders is Auth, IRateProvider, IPausable {
          using FixedPointMathLib for uint256;
          using SafeTransferLib for ERC20;
          // ========================================= STRUCTS =========================================
          /**
           * @param payoutAddress the address `claimFees` sends fees to
           * @param highwaterMark the highest value of the BoringVault's share price
           * @param feesOwedInBase total pending fees owed in terms of base
           * @param totalSharesLastUpdate total amount of shares the last exchange rate update
           * @param exchangeRate the current exchange rate in terms of base
           * @param allowedExchangeRateChangeUpper the max allowed change to exchange rate from an update
           * @param allowedExchangeRateChangeLower the min allowed change to exchange rate from an update
           * @param lastUpdateTimestamp the block timestamp of the last exchange rate update
           * @param isPaused whether or not this contract is paused
           * @param minimumUpdateDelayInSeconds the minimum amount of time that must pass between
           *        exchange rate updates, such that the update won't trigger the contract to be paused
           * @param platformFee the platform fee
           * @param performanceFee the performance fee
           */
          struct AccountantState {
              address payoutAddress;
              uint96 highwaterMark;
              uint128 feesOwedInBase;
              uint128 totalSharesLastUpdate;
              uint96 exchangeRate;
              uint16 allowedExchangeRateChangeUpper;
              uint16 allowedExchangeRateChangeLower;
              uint64 lastUpdateTimestamp;
              bool isPaused;
              uint24 minimumUpdateDelayInSeconds;
              uint16 platformFee;
              uint16 performanceFee;
          }
          /**
           * @param isPeggedToBase whether or not the asset is 1:1 with the base asset
           * @param rateProvider the rate provider for this asset if `isPeggedToBase` is false
           */
          struct RateProviderData {
              bool isPeggedToBase;
              IRateProvider rateProvider;
          }
          // ========================================= STATE =========================================
          /**
           * @notice Store the accountant state in 3 packed slots.
           */
          AccountantState public accountantState;
          /**
           * @notice Maps ERC20s to their RateProviderData.
           */
          mapping(ERC20 => RateProviderData) public rateProviderData;
          //============================== ERRORS ===============================
          error AccountantWithRateProviders__UpperBoundTooSmall();
          error AccountantWithRateProviders__LowerBoundTooLarge();
          error AccountantWithRateProviders__PlatformFeeTooLarge();
          error AccountantWithRateProviders__PerformanceFeeTooLarge();
          error AccountantWithRateProviders__Paused();
          error AccountantWithRateProviders__ZeroFeesOwed();
          error AccountantWithRateProviders__OnlyCallableByBoringVault();
          error AccountantWithRateProviders__UpdateDelayTooLarge();
          error AccountantWithRateProviders__ExchangeRateAboveHighwaterMark();
          //============================== EVENTS ===============================
          event Paused();
          event Unpaused();
          event DelayInSecondsUpdated(uint24 oldDelay, uint24 newDelay);
          event UpperBoundUpdated(uint16 oldBound, uint16 newBound);
          event LowerBoundUpdated(uint16 oldBound, uint16 newBound);
          event PlatformFeeUpdated(uint16 oldFee, uint16 newFee);
          event PerformanceFeeUpdated(uint16 oldFee, uint16 newFee);
          event PayoutAddressUpdated(address oldPayout, address newPayout);
          event RateProviderUpdated(address asset, bool isPegged, address rateProvider);
          event ExchangeRateUpdated(uint96 oldRate, uint96 newRate, uint64 currentTime);
          event FeesClaimed(address indexed feeAsset, uint256 amount);
          event HighwaterMarkReset();
          //============================== IMMUTABLES ===============================
          /**
           * @notice The base asset rates are provided in.
           */
          ERC20 public immutable base;
          /**
           * @notice The decimals rates are provided in.
           */
          uint8 public immutable decimals;
          /**
           * @notice The BoringVault this accountant is working with.
           *         Used to determine share supply for fee calculation.
           */
          BoringVault public immutable vault;
          /**
           * @notice One share of the BoringVault.
           */
          uint256 internal immutable ONE_SHARE;
          constructor(
              address _owner,
              address _vault,
              address payoutAddress,
              uint96 startingExchangeRate,
              address _base,
              uint16 allowedExchangeRateChangeUpper,
              uint16 allowedExchangeRateChangeLower,
              uint24 minimumUpdateDelayInSeconds,
              uint16 platformFee,
              uint16 performanceFee
          ) Auth(_owner, Authority(address(0))) {
              base = ERC20(_base);
              decimals = ERC20(_base).decimals();
              vault = BoringVault(payable(_vault));
              ONE_SHARE = 10 ** vault.decimals();
              accountantState = AccountantState({
                  payoutAddress: payoutAddress,
                  highwaterMark: startingExchangeRate,
                  feesOwedInBase: 0,
                  totalSharesLastUpdate: uint128(vault.totalSupply()),
                  exchangeRate: startingExchangeRate,
                  allowedExchangeRateChangeUpper: allowedExchangeRateChangeUpper,
                  allowedExchangeRateChangeLower: allowedExchangeRateChangeLower,
                  lastUpdateTimestamp: uint64(block.timestamp),
                  isPaused: false,
                  minimumUpdateDelayInSeconds: minimumUpdateDelayInSeconds,
                  platformFee: platformFee,
                  performanceFee: performanceFee
              });
          }
          // ========================================= ADMIN FUNCTIONS =========================================
          /**
           * @notice Pause this contract, which prevents future calls to `updateExchangeRate`, and any safe rate
           *         calls will revert.
           * @dev Callable by MULTISIG_ROLE.
           */
          function pause() external requiresAuth {
              accountantState.isPaused = true;
              emit Paused();
          }
          /**
           * @notice Unpause this contract, which allows future calls to `updateExchangeRate`, and any safe rate
           *         calls will stop reverting.
           * @dev Callable by MULTISIG_ROLE.
           */
          function unpause() external requiresAuth {
              accountantState.isPaused = false;
              emit Unpaused();
          }
          /**
           * @notice Update the minimum time delay between `updateExchangeRate` calls.
           * @dev There are no input requirements, as it is possible the admin would want
           *      the exchange rate updated as frequently as needed.
           * @dev Callable by OWNER_ROLE.
           */
          function updateDelay(uint24 minimumUpdateDelayInSeconds) external requiresAuth {
              if (minimumUpdateDelayInSeconds > 14 days) revert AccountantWithRateProviders__UpdateDelayTooLarge();
              uint24 oldDelay = accountantState.minimumUpdateDelayInSeconds;
              accountantState.minimumUpdateDelayInSeconds = minimumUpdateDelayInSeconds;
              emit DelayInSecondsUpdated(oldDelay, minimumUpdateDelayInSeconds);
          }
          /**
           * @notice Update the allowed upper bound change of exchange rate between `updateExchangeRateCalls`.
           * @dev Callable by OWNER_ROLE.
           */
          function updateUpper(uint16 allowedExchangeRateChangeUpper) external requiresAuth {
              if (allowedExchangeRateChangeUpper < 1e4) revert AccountantWithRateProviders__UpperBoundTooSmall();
              uint16 oldBound = accountantState.allowedExchangeRateChangeUpper;
              accountantState.allowedExchangeRateChangeUpper = allowedExchangeRateChangeUpper;
              emit UpperBoundUpdated(oldBound, allowedExchangeRateChangeUpper);
          }
          /**
           * @notice Update the allowed lower bound change of exchange rate between `updateExchangeRateCalls`.
           * @dev Callable by OWNER_ROLE.
           */
          function updateLower(uint16 allowedExchangeRateChangeLower) external requiresAuth {
              if (allowedExchangeRateChangeLower > 1e4) revert AccountantWithRateProviders__LowerBoundTooLarge();
              uint16 oldBound = accountantState.allowedExchangeRateChangeLower;
              accountantState.allowedExchangeRateChangeLower = allowedExchangeRateChangeLower;
              emit LowerBoundUpdated(oldBound, allowedExchangeRateChangeLower);
          }
          /**
           * @notice Update the platform fee to a new value.
           * @dev Callable by OWNER_ROLE.
           */
          function updatePlatformFee(uint16 platformFee) external requiresAuth {
              if (platformFee > 0.2e4) revert AccountantWithRateProviders__PlatformFeeTooLarge();
              uint16 oldFee = accountantState.platformFee;
              accountantState.platformFee = platformFee;
              emit PlatformFeeUpdated(oldFee, platformFee);
          }
          /**
           * @notice Update the performance fee to a new value.
           * @dev Callable by OWNER_ROLE.
           */
          function updatePerformanceFee(uint16 performanceFee) external requiresAuth {
              if (performanceFee > 0.5e4) revert AccountantWithRateProviders__PerformanceFeeTooLarge();
              uint16 oldFee = accountantState.performanceFee;
              accountantState.performanceFee = performanceFee;
              emit PerformanceFeeUpdated(oldFee, performanceFee);
          }
          /**
           * @notice Update the payout address fees are sent to.
           * @dev Callable by OWNER_ROLE.
           */
          function updatePayoutAddress(address payoutAddress) external requiresAuth {
              address oldPayout = accountantState.payoutAddress;
              accountantState.payoutAddress = payoutAddress;
              emit PayoutAddressUpdated(oldPayout, payoutAddress);
          }
          /**
           * @notice Update the rate provider data for a specific `asset`.
           * @dev Rate providers must return rates in terms of `base` or
           * an asset pegged to base and they must use the same decimals
           * as `asset`.
           * @dev Callable by OWNER_ROLE.
           */
          function setRateProviderData(ERC20 asset, bool isPeggedToBase, address rateProvider) external requiresAuth {
              rateProviderData[asset] =
                  RateProviderData({isPeggedToBase: isPeggedToBase, rateProvider: IRateProvider(rateProvider)});
              emit RateProviderUpdated(address(asset), isPeggedToBase, rateProvider);
          }
          /**
           * @notice Reset the highwater mark to the current exchange rate.
           * @dev Callable by OWNER_ROLE.
           */
          function resetHighwaterMark() external virtual requiresAuth {
              AccountantState storage state = accountantState;
              if (state.exchangeRate > state.highwaterMark) {
                  revert AccountantWithRateProviders__ExchangeRateAboveHighwaterMark();
              }
              uint64 currentTime = uint64(block.timestamp);
              uint256 currentTotalShares = vault.totalSupply();
              _calculateFeesOwed(state, state.exchangeRate, state.exchangeRate, currentTotalShares, currentTime);
              state.totalSharesLastUpdate = uint128(currentTotalShares);
              state.highwaterMark = accountantState.exchangeRate;
              state.lastUpdateTimestamp = currentTime;
              emit HighwaterMarkReset();
          }
          // ========================================= UPDATE EXCHANGE RATE/FEES FUNCTIONS =========================================
          /**
           * @notice Updates this contract exchangeRate.
           * @dev If new exchange rate is outside of accepted bounds, or if not enough time has passed, this
           *      will pause the contract, and this function will NOT calculate fees owed.
           * @dev Callable by UPDATE_EXCHANGE_RATE_ROLE.
           */
          function updateExchangeRate(uint96 newExchangeRate) external virtual requiresAuth {
              (
                  bool shouldPause,
                  AccountantState storage state,
                  uint64 currentTime,
                  uint256 currentExchangeRate,
                  uint256 currentTotalShares
              ) = _beforeUpdateExchangeRate(newExchangeRate);
              if (shouldPause) {
                  // Instead of reverting, pause the contract. This way the exchange rate updater is able to update the exchange rate
                  // to a better value, and pause it.
                  state.isPaused = true;
              } else {
                  _calculateFeesOwed(state, newExchangeRate, currentExchangeRate, currentTotalShares, currentTime);
              }
              newExchangeRate = _setExchangeRate(newExchangeRate, state);
              state.totalSharesLastUpdate = uint128(currentTotalShares);
              state.lastUpdateTimestamp = currentTime;
              emit ExchangeRateUpdated(uint96(currentExchangeRate), newExchangeRate, currentTime);
          }
          /**
           * @notice Claim pending fees.
           * @dev This function must be called by the BoringVault.
           * @dev This function will lose precision if the exchange rate
           *      decimals is greater than the feeAsset's decimals.
           */
          function claimFees(ERC20 feeAsset) external {
              if (msg.sender != address(vault)) revert AccountantWithRateProviders__OnlyCallableByBoringVault();
              AccountantState storage state = accountantState;
              if (state.isPaused) revert AccountantWithRateProviders__Paused();
              if (state.feesOwedInBase == 0) revert AccountantWithRateProviders__ZeroFeesOwed();
              // Determine amount of fees owed in feeAsset.
              uint256 feesOwedInFeeAsset;
              RateProviderData memory data = rateProviderData[feeAsset];
              if (address(feeAsset) == address(base)) {
                  feesOwedInFeeAsset = state.feesOwedInBase;
              } else {
                  uint8 feeAssetDecimals = ERC20(feeAsset).decimals();
                  uint256 feesOwedInBaseUsingFeeAssetDecimals =
                      _changeDecimals(state.feesOwedInBase, decimals, feeAssetDecimals);
                  if (data.isPeggedToBase) {
                      feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals;
                  } else {
                      uint256 rate = data.rateProvider.getRate();
                      feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals.mulDivDown(10 ** feeAssetDecimals, rate);
                  }
              }
              // Zero out fees owed.
              state.feesOwedInBase = 0;
              // Transfer fee asset to payout address.
              feeAsset.safeTransferFrom(msg.sender, state.payoutAddress, feesOwedInFeeAsset);
              emit FeesClaimed(address(feeAsset), feesOwedInFeeAsset);
          }
          // ========================================= VIEW FUNCTIONS =========================================
          /**
           * @notice Get this BoringVault's current rate in the base.
           */
          function getRate() public view returns (uint256 rate) {
              rate = accountantState.exchangeRate;
          }
          /**
           * @notice Get this BoringVault's current rate in the base.
           * @dev Revert if paused.
           */
          function getRateSafe() external view returns (uint256 rate) {
              if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
              rate = getRate();
          }
          /**
           * @notice Get this BoringVault's current rate in the provided quote.
           * @dev `quote` must have its RateProviderData set, else this will revert.
           * @dev This function will lose precision if the exchange rate
           *      decimals is greater than the quote's decimals.
           */
          function getRateInQuote(ERC20 quote) public view returns (uint256 rateInQuote) {
              if (address(quote) == address(base)) {
                  rateInQuote = accountantState.exchangeRate;
              } else {
                  RateProviderData memory data = rateProviderData[quote];
                  uint8 quoteDecimals = ERC20(quote).decimals();
                  uint256 exchangeRateInQuoteDecimals = _changeDecimals(accountantState.exchangeRate, decimals, quoteDecimals);
                  if (data.isPeggedToBase) {
                      rateInQuote = exchangeRateInQuoteDecimals;
                  } else {
                      uint256 quoteRate = data.rateProvider.getRate();
                      uint256 oneQuote = 10 ** quoteDecimals;
                      rateInQuote = oneQuote.mulDivDown(exchangeRateInQuoteDecimals, quoteRate);
                  }
              }
          }
          /**
           * @notice Get this BoringVault's current rate in the provided quote.
           * @dev `quote` must have its RateProviderData set, else this will revert.
           * @dev Revert if paused.
           */
          function getRateInQuoteSafe(ERC20 quote) external view returns (uint256 rateInQuote) {
              if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
              rateInQuote = getRateInQuote(quote);
          }
          /**
           * @notice Preview the result of an update to the exchange rate.
           * @return updateWillPause Whether the update will pause the contract.
           * @return newFeesOwedInBase The new fees owed in base.
           * @return totalFeesOwedInBase The total fees owed in base.
           */
          function previewUpdateExchangeRate(uint96 newExchangeRate)
              external
              view
              virtual
              returns (bool updateWillPause, uint256 newFeesOwedInBase, uint256 totalFeesOwedInBase)
          {
              (
                  bool shouldPause,
                  AccountantState storage state,
                  uint64 currentTime,
                  uint256 currentExchangeRate,
                  uint256 currentTotalShares
              ) = _beforeUpdateExchangeRate(newExchangeRate);
              updateWillPause = shouldPause;
              totalFeesOwedInBase = state.feesOwedInBase;
              if (!shouldPause) {
                  (uint256 platformFeesOwedInBase, uint256 shareSupplyToUse) = _calculatePlatformFee(
                      state.totalSharesLastUpdate,
                      state.lastUpdateTimestamp,
                      state.platformFee,
                      newExchangeRate,
                      currentExchangeRate,
                      currentTotalShares,
                      currentTime
                  );
                  uint256 performanceFeesOwedInBase;
                  if (newExchangeRate > state.highwaterMark) {
                      (performanceFeesOwedInBase,) = _calculatePerformanceFee(
                          newExchangeRate, shareSupplyToUse, state.highwaterMark, state.performanceFee
                      );
                  }
                  newFeesOwedInBase = platformFeesOwedInBase + performanceFeesOwedInBase;
                  totalFeesOwedInBase += newFeesOwedInBase;
              }
          }
          // ========================================= INTERNAL HELPER FUNCTIONS =========================================
          /**
           * @notice Used to change the decimals of precision used for an amount.
           */
          function _changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
              if (fromDecimals == toDecimals) {
                  return amount;
              } else if (fromDecimals < toDecimals) {
                  return amount * 10 ** (toDecimals - fromDecimals);
              } else {
                  return amount / 10 ** (fromDecimals - toDecimals);
              }
          }
          /**
           * @notice Check if the new exchange rate is outside of the allowed bounds or if not enough time has passed.
           */
          function _beforeUpdateExchangeRate(uint96 newExchangeRate)
              internal
              view
              returns (
                  bool shouldPause,
                  AccountantState storage state,
                  uint64 currentTime,
                  uint256 currentExchangeRate,
                  uint256 currentTotalShares
              )
          {
              state = accountantState;
              if (state.isPaused) revert AccountantWithRateProviders__Paused();
              currentTime = uint64(block.timestamp);
              currentExchangeRate = state.exchangeRate;
              currentTotalShares = vault.totalSupply();
              shouldPause = currentTime < state.lastUpdateTimestamp + state.minimumUpdateDelayInSeconds
                  || newExchangeRate > currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeUpper, 1e4)
                  || newExchangeRate < currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeLower, 1e4);
          }
          /**
           * @notice Set the exchange rate.
           */
          function _setExchangeRate(uint96 newExchangeRate, AccountantState storage state)
              internal
              virtual
              returns (uint96)
          {
              state.exchangeRate = newExchangeRate;
              return newExchangeRate;
          }
          /**
           * @notice Calculate platform fees.
           */
          function _calculatePlatformFee(
              uint128 totalSharesLastUpdate,
              uint64 lastUpdateTimestamp,
              uint16 platformFee,
              uint96 newExchangeRate,
              uint256 currentExchangeRate,
              uint256 currentTotalShares,
              uint64 currentTime
          ) internal view returns (uint256 platformFeesOwedInBase, uint256 shareSupplyToUse) {
              shareSupplyToUse = currentTotalShares;
              // Use the minimum between current total supply and total supply for last update.
              if (totalSharesLastUpdate < shareSupplyToUse) {
                  shareSupplyToUse = totalSharesLastUpdate;
              }
              // Determine platform fees owned.
              if (platformFee > 0) {
                  uint256 timeDelta = currentTime - lastUpdateTimestamp;
                  uint256 minimumAssets = newExchangeRate > currentExchangeRate
                      ? shareSupplyToUse.mulDivDown(currentExchangeRate, ONE_SHARE)
                      : shareSupplyToUse.mulDivDown(newExchangeRate, ONE_SHARE);
                  uint256 platformFeesAnnual = minimumAssets.mulDivDown(platformFee, 1e4);
                  platformFeesOwedInBase = platformFeesAnnual.mulDivDown(timeDelta, 365 days);
              }
          }
          /**
           * @notice Calculate performance fees.
           */
          function _calculatePerformanceFee(
              uint96 newExchangeRate,
              uint256 shareSupplyToUse,
              uint96 datum,
              uint16 performanceFee
          ) internal view returns (uint256 performanceFeesOwedInBase, uint256 yieldEarned) {
              uint256 changeInExchangeRate = newExchangeRate - datum;
              yieldEarned = changeInExchangeRate.mulDivDown(shareSupplyToUse, ONE_SHARE);
              if (performanceFee > 0) {
                  performanceFeesOwedInBase = yieldEarned.mulDivDown(performanceFee, 1e4);
              }
          }
          /**
           * @notice Calculate fees owed in base.
           * @dev This function will update the highwater mark if the new exchange rate is higher.
           */
          function _calculateFeesOwed(
              AccountantState storage state,
              uint96 newExchangeRate,
              uint256 currentExchangeRate,
              uint256 currentTotalShares,
              uint64 currentTime
          ) internal virtual {
              // Only update fees if we are not paused.
              // Update fee accounting.
              (uint256 newFeesOwedInBase, uint256 shareSupplyToUse) = _calculatePlatformFee(
                  state.totalSharesLastUpdate,
                  state.lastUpdateTimestamp,
                  state.platformFee,
                  newExchangeRate,
                  currentExchangeRate,
                  currentTotalShares,
                  currentTime
              );
              // Account for performance fees.
              if (newExchangeRate > state.highwaterMark) {
                  (uint256 performanceFeesOwedInBase,) =
                      _calculatePerformanceFee(newExchangeRate, shareSupplyToUse, state.highwaterMark, state.performanceFee);
                  // Add performance fees to fees owed.
                  newFeesOwedInBase += performanceFeesOwedInBase;
                  // Always update the highwater mark if the new exchange rate is higher.
                  // This way if we are not iniitiall taking performance fees, we can start taking them
                  // without back charging them on past performance.
                  state.highwaterMark = newExchangeRate;
              }
              state.feesOwedInBase += uint128(newFeesOwedInBase);
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Arithmetic library with operations for fixed-point numbers.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
      /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
      library FixedPointMathLib {
          /*//////////////////////////////////////////////////////////////
                          SIMPLIFIED FIXED POINT OPERATIONS
          //////////////////////////////////////////////////////////////*/
          uint256 internal constant MAX_UINT256 = 2**256 - 1;
          uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
          function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
          }
          function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
          }
          function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
          }
          function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
          }
          /*//////////////////////////////////////////////////////////////
                          LOW LEVEL FIXED POINT OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function mulDivDown(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
                  if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                      revert(0, 0)
                  }
                  // Divide x * y by the denominator.
                  z := div(mul(x, y), denominator)
              }
          }
          function mulDivUp(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
                  if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                      revert(0, 0)
                  }
                  // If x * y modulo the denominator is strictly greater than 0,
                  // 1 is added to round up the division of x * y by the denominator.
                  z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
              }
          }
          function rpow(
              uint256 x,
              uint256 n,
              uint256 scalar
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  switch x
                  case 0 {
                      switch n
                      case 0 {
                          // 0 ** 0 = 1
                          z := scalar
                      }
                      default {
                          // 0 ** n = 0
                          z := 0
                      }
                  }
                  default {
                      switch mod(n, 2)
                      case 0 {
                          // If n is even, store scalar in z for now.
                          z := scalar
                      }
                      default {
                          // If n is odd, store x in z for now.
                          z := x
                      }
                      // Shifting right by 1 is like dividing by 2.
                      let half := shr(1, scalar)
                      for {
                          // Shift n right by 1 before looping to halve it.
                          n := shr(1, n)
                      } n {
                          // Shift n right by 1 each iteration to halve it.
                          n := shr(1, n)
                      } {
                          // Revert immediately if x ** 2 would overflow.
                          // Equivalent to iszero(eq(div(xx, x), x)) here.
                          if shr(128, x) {
                              revert(0, 0)
                          }
                          // Store x squared.
                          let xx := mul(x, x)
                          // Round to the nearest number.
                          let xxRound := add(xx, half)
                          // Revert if xx + half overflowed.
                          if lt(xxRound, xx) {
                              revert(0, 0)
                          }
                          // Set x to scaled xxRound.
                          x := div(xxRound, scalar)
                          // If n is even:
                          if mod(n, 2) {
                              // Compute z * x.
                              let zx := mul(z, x)
                              // If z * x overflowed:
                              if iszero(eq(div(zx, x), z)) {
                                  // Revert if x is non-zero.
                                  if iszero(iszero(x)) {
                                      revert(0, 0)
                                  }
                              }
                              // Round to the nearest number.
                              let zxRound := add(zx, half)
                              // Revert if zx + half overflowed.
                              if lt(zxRound, zx) {
                                  revert(0, 0)
                              }
                              // Return properly scaled zxRound.
                              z := div(zxRound, scalar)
                          }
                      }
                  }
              }
          }
          /*//////////////////////////////////////////////////////////////
                              GENERAL NUMBER UTILITIES
          //////////////////////////////////////////////////////////////*/
          function sqrt(uint256 x) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  let y := x // We start y at x, which will help us make our initial estimate.
                  z := 181 // The "correct" value is 1, but this saves a multiplication later.
                  // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                  // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                  // We check y >= 2^(k + 8) but shift right by k bits
                  // each branch to ensure that if x >= 256, then y >= 256.
                  if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                      y := shr(128, y)
                      z := shl(64, z)
                  }
                  if iszero(lt(y, 0x1000000000000000000)) {
                      y := shr(64, y)
                      z := shl(32, z)
                  }
                  if iszero(lt(y, 0x10000000000)) {
                      y := shr(32, y)
                      z := shl(16, z)
                  }
                  if iszero(lt(y, 0x1000000)) {
                      y := shr(16, y)
                      z := shl(8, z)
                  }
                  // Goal was to get z*z*y within a small factor of x. More iterations could
                  // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
                  // We ensured y >= 256 so that the relative difference between y and y+1 is small.
                  // That's not possible if x < 256 but we can just verify those cases exhaustively.
                  // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
                  // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
                  // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
                  // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
                  // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
                  // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
                  // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
                  // There is no overflow risk here since y < 2^136 after the first branch above.
                  z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
                  // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  // If x+1 is a perfect square, the Babylonian method cycles between
                  // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
                  // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                  // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
                  // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
                  z := sub(z, lt(div(x, z), z))
              }
          }
          function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Mod x by y. Note this will return
                  // 0 instead of reverting if y is zero.
                  z := mod(x, y)
              }
          }
          function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Divide x by y. Note this will return
                  // 0 instead of reverting if y is zero.
                  r := div(x, y)
              }
          }
          function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Add 1 to x * y if x % y > 0. Note this will
                  // return 0 instead of reverting if y is zero.
                  z := add(gt(mod(x, y), 0), div(x, y))
              }
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      import {ERC20} from "../tokens/ERC20.sol";
      /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
      /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
      /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
      library SafeTransferLib {
          /*//////////////////////////////////////////////////////////////
                                   ETH OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function safeTransferETH(address to, uint256 amount) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Transfer the ETH and store if it succeeded or not.
                  success := call(gas(), to, amount, 0, 0, 0, 0)
              }
              require(success, "ETH_TRANSFER_FAILED");
          }
          /*//////////////////////////////////////////////////////////////
                                  ERC20 OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function safeTransferFrom(
              ERC20 token,
              address from,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
                  mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
                  )
              }
              require(success, "TRANSFER_FROM_FAILED");
          }
          function safeTransfer(
              ERC20 token,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                  )
              }
              require(success, "TRANSFER_FAILED");
          }
          function safeApprove(
              ERC20 token,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                  )
              }
              require(success, "APPROVE_FAILED");
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      interface BeforeTransferHook {
          function beforeTransfer(address from, address to, address operator) external view;
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      abstract contract Auth {
          event OwnershipTransferred(address indexed user, address indexed newOwner);
          event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
          address public owner;
          Authority public authority;
          constructor(address _owner, Authority _authority) {
              owner = _owner;
              authority = _authority;
              emit OwnershipTransferred(msg.sender, _owner);
              emit AuthorityUpdated(msg.sender, _authority);
          }
          modifier requiresAuth() virtual {
              require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
              _;
          }
          function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
              Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
              // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
              // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
              return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
          }
          function setAuthority(Authority newAuthority) public virtual {
              // We check if the caller is the owner first because we want to ensure they can
              // always swap out the authority even if it's reverting or using up a lot of gas.
              require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
              authority = newAuthority;
              emit AuthorityUpdated(msg.sender, newAuthority);
          }
          function transferOwnership(address newOwner) public virtual requiresAuth {
              owner = newOwner;
              emit OwnershipTransferred(msg.sender, newOwner);
          }
      }
      /// @notice A generic interface for a contract which provides authorization data to an Auth instance.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      interface Authority {
          function canCall(
              address user,
              address target,
              bytes4 functionSig
          ) external view returns (bool);
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Gas optimized reentrancy protection for smart contracts.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
      /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
      abstract contract ReentrancyGuard {
          uint256 private locked = 1;
          modifier nonReentrant() virtual {
              require(locked == 1, "REENTRANCY");
              locked = 2;
              _;
              locked = 1;
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      interface IPausable {
          function pause() external;
          function unpause() external;
      }
      // 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) (token/ERC721/utils/ERC721Holder.sol)
      pragma solidity ^0.8.20;
      import {IERC721Receiver} from "../IERC721Receiver.sol";
      /**
       * @dev Implementation of the {IERC721Receiver} interface.
       *
       * Accepts all token transfers.
       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
       * {IERC721-setApprovalForAll}.
       */
      abstract contract ERC721Holder is IERC721Receiver {
          /**
           * @dev See {IERC721Receiver-onERC721Received}.
           *
           * Always returns `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
              return this.onERC721Received.selector;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)
      pragma solidity ^0.8.20;
      import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
      import {IERC1155Receiver} from "../IERC1155Receiver.sol";
      /**
       * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
       *
       * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
       * stuck.
       */
      abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
          }
          function onERC1155Received(
              address,
              address,
              uint256,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155Received.selector;
          }
          function onERC1155BatchReceived(
              address,
              address,
              uint256[] memory,
              uint256[] memory,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155BatchReceived.selector;
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      // This program is free software: you can redistribute it and/or modify
      // it under the terms of the GNU General Public License as published by
      // the Free Software Foundation, either version 3 of the License, or
      // (at your option) any later version.
      // This program is distributed in the hope that it will be useful,
      // but WITHOUT ANY WARRANTY; without even the implied warranty of
      // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      // GNU General Public License for more details.
      // You should have received a copy of the GNU General Public License
      // along with this program.  If not, see <http://www.gnu.org/licenses/>.
      pragma solidity ^0.8.0;
      interface IRateProvider {
          function getRate() external view returns (uint256);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
      pragma solidity ^0.8.20;
      /**
       * @title ERC721 token receiver interface
       * @dev Interface for any contract that wants to support safeTransfers
       * from ERC721 asset contracts.
       */
      interface IERC721Receiver {
          /**
           * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
           * by `operator` from `from`, this function is called.
           *
           * It must return its Solidity selector to confirm the token transfer.
           * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
           * reverted.
           *
           * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.20;
      import {IERC165} from "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
       * for the additional interface id that will be supported. For example:
       *
       * ```solidity
       * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
       *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
       * }
       * ```
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)
      pragma solidity ^0.8.20;
      import {IERC165} from "../../utils/introspection/IERC165.sol";
      /**
       * @dev Interface that must be implemented by smart contracts in order to receive
       * ERC-1155 token transfers.
       */
      interface IERC1155Receiver is IERC165 {
          /**
           * @dev Handles the receipt of a single ERC1155 token type. This function is
           * called at the end of a `safeTransferFrom` after the balance has been updated.
           *
           * NOTE: To accept the transfer, this must return
           * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
           * (i.e. 0xf23a6e61, or its own function selector).
           *
           * @param operator The address which initiated the transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param id The ID of the token being transferred
           * @param value The amount of tokens being transferred
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
           */
          function onERC1155Received(
              address operator,
              address from,
              uint256 id,
              uint256 value,
              bytes calldata data
          ) external returns (bytes4);
          /**
           * @dev Handles the receipt of a multiple ERC1155 token types. This function
           * is called at the end of a `safeBatchTransferFrom` after the balances have
           * been updated.
           *
           * NOTE: To accept the transfer(s), this must return
           * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
           * (i.e. 0xbc197c81, or its own function selector).
           *
           * @param operator The address which initiated the batch transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param ids An array containing ids of each token being transferred (order and length must match values array)
           * @param values An array containing amounts of each token being transferred (order and length must match ids array)
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
           */
          function onERC1155BatchReceived(
              address operator,
              address from,
              uint256[] calldata ids,
              uint256[] calldata values,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.20;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * Implementers can declare support of contract interfaces, which can then be
       * queried by others ({ERC165Checker}).
       *
       * For an implementation, see {ERC165}.
       */
      interface IERC165 {
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30 000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
      }
      

      File 2 of 5: BoringVault
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      import {Address} from "@openzeppelin/contracts/utils/Address.sol";
      import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
      import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
      import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
      import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
      import {ERC20} from "@solmate/tokens/ERC20.sol";
      import {BeforeTransferHook} from "src/interfaces/BeforeTransferHook.sol";
      import {Auth, Authority} from "@solmate/auth/Auth.sol";
      contract BoringVault is ERC20, Auth, ERC721Holder, ERC1155Holder {
          using Address for address;
          using SafeTransferLib for ERC20;
          using FixedPointMathLib for uint256;
          // ========================================= STATE =========================================
          /**
           * @notice Contract responsbile for implementing `beforeTransfer`.
           */
          BeforeTransferHook public hook;
          //============================== EVENTS ===============================
          event Enter(address indexed from, address indexed asset, uint256 amount, address indexed to, uint256 shares);
          event Exit(address indexed to, address indexed asset, uint256 amount, address indexed from, uint256 shares);
          //============================== CONSTRUCTOR ===============================
          constructor(address _owner, string memory _name, string memory _symbol, uint8 _decimals)
              ERC20(_name, _symbol, _decimals)
              Auth(_owner, Authority(address(0)))
          {}
          //============================== MANAGE ===============================
          /**
           * @notice Allows manager to make an arbitrary function call from this contract.
           * @dev Callable by MANAGER_ROLE.
           */
          function manage(address target, bytes calldata data, uint256 value)
              external
              requiresAuth
              returns (bytes memory result)
          {
              result = target.functionCallWithValue(data, value);
          }
          /**
           * @notice Allows manager to make arbitrary function calls from this contract.
           * @dev Callable by MANAGER_ROLE.
           */
          function manage(address[] calldata targets, bytes[] calldata data, uint256[] calldata values)
              external
              requiresAuth
              returns (bytes[] memory results)
          {
              uint256 targetsLength = targets.length;
              results = new bytes[](targetsLength);
              for (uint256 i; i < targetsLength; ++i) {
                  results[i] = targets[i].functionCallWithValue(data[i], values[i]);
              }
          }
          //============================== ENTER ===============================
          /**
           * @notice Allows minter to mint shares, in exchange for assets.
           * @dev If assetAmount is zero, no assets are transferred in.
           * @dev Callable by MINTER_ROLE.
           */
          function enter(address from, ERC20 asset, uint256 assetAmount, address to, uint256 shareAmount)
              external
              requiresAuth
          {
              // Transfer assets in
              if (assetAmount > 0) asset.safeTransferFrom(from, address(this), assetAmount);
              // Mint shares.
              _mint(to, shareAmount);
              emit Enter(from, address(asset), assetAmount, to, shareAmount);
          }
          //============================== EXIT ===============================
          /**
           * @notice Allows burner to burn shares, in exchange for assets.
           * @dev If assetAmount is zero, no assets are transferred out.
           * @dev Callable by BURNER_ROLE.
           */
          function exit(address to, ERC20 asset, uint256 assetAmount, address from, uint256 shareAmount)
              external
              requiresAuth
          {
              // Burn shares.
              _burn(from, shareAmount);
              // Transfer assets out.
              if (assetAmount > 0) asset.safeTransfer(to, assetAmount);
              emit Exit(to, address(asset), assetAmount, from, shareAmount);
          }
          //============================== BEFORE TRANSFER HOOK ===============================
          /**
           * @notice Sets the share locker.
           * @notice If set to zero address, the share locker logic is disabled.
           * @dev Callable by OWNER_ROLE.
           */
          function setBeforeTransferHook(address _hook) external requiresAuth {
              hook = BeforeTransferHook(_hook);
          }
          /**
           * @notice Call `beforeTransferHook` passing in `from` `to`, and `msg.sender`.
           */
          function _callBeforeTransfer(address from, address to) internal view {
              if (address(hook) != address(0)) hook.beforeTransfer(from, to, msg.sender);
          }
          function transfer(address to, uint256 amount) public override returns (bool) {
              _callBeforeTransfer(msg.sender, to);
              return super.transfer(to, amount);
          }
          function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
              _callBeforeTransfer(from, to);
              return super.transferFrom(from, to, amount);
          }
          //============================== RECEIVE ===============================
          receive() external payable {}
      }
      // 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) (token/ERC721/utils/ERC721Holder.sol)
      pragma solidity ^0.8.20;
      import {IERC721Receiver} from "../IERC721Receiver.sol";
      /**
       * @dev Implementation of the {IERC721Receiver} interface.
       *
       * Accepts all token transfers.
       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
       * {IERC721-setApprovalForAll}.
       */
      abstract contract ERC721Holder is IERC721Receiver {
          /**
           * @dev See {IERC721Receiver-onERC721Received}.
           *
           * Always returns `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
              return this.onERC721Received.selector;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)
      pragma solidity ^0.8.20;
      import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
      import {IERC1155Receiver} from "../IERC1155Receiver.sol";
      /**
       * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
       *
       * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
       * stuck.
       */
      abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
          }
          function onERC1155Received(
              address,
              address,
              uint256,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155Received.selector;
          }
          function onERC1155BatchReceived(
              address,
              address,
              uint256[] memory,
              uint256[] memory,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155BatchReceived.selector;
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Arithmetic library with operations for fixed-point numbers.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
      /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
      library FixedPointMathLib {
          /*//////////////////////////////////////////////////////////////
                          SIMPLIFIED FIXED POINT OPERATIONS
          //////////////////////////////////////////////////////////////*/
          uint256 internal constant MAX_UINT256 = 2**256 - 1;
          uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
          function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
          }
          function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
          }
          function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
          }
          function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
          }
          /*//////////////////////////////////////////////////////////////
                          LOW LEVEL FIXED POINT OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function mulDivDown(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
                  if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                      revert(0, 0)
                  }
                  // Divide x * y by the denominator.
                  z := div(mul(x, y), denominator)
              }
          }
          function mulDivUp(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
                  if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                      revert(0, 0)
                  }
                  // If x * y modulo the denominator is strictly greater than 0,
                  // 1 is added to round up the division of x * y by the denominator.
                  z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
              }
          }
          function rpow(
              uint256 x,
              uint256 n,
              uint256 scalar
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  switch x
                  case 0 {
                      switch n
                      case 0 {
                          // 0 ** 0 = 1
                          z := scalar
                      }
                      default {
                          // 0 ** n = 0
                          z := 0
                      }
                  }
                  default {
                      switch mod(n, 2)
                      case 0 {
                          // If n is even, store scalar in z for now.
                          z := scalar
                      }
                      default {
                          // If n is odd, store x in z for now.
                          z := x
                      }
                      // Shifting right by 1 is like dividing by 2.
                      let half := shr(1, scalar)
                      for {
                          // Shift n right by 1 before looping to halve it.
                          n := shr(1, n)
                      } n {
                          // Shift n right by 1 each iteration to halve it.
                          n := shr(1, n)
                      } {
                          // Revert immediately if x ** 2 would overflow.
                          // Equivalent to iszero(eq(div(xx, x), x)) here.
                          if shr(128, x) {
                              revert(0, 0)
                          }
                          // Store x squared.
                          let xx := mul(x, x)
                          // Round to the nearest number.
                          let xxRound := add(xx, half)
                          // Revert if xx + half overflowed.
                          if lt(xxRound, xx) {
                              revert(0, 0)
                          }
                          // Set x to scaled xxRound.
                          x := div(xxRound, scalar)
                          // If n is even:
                          if mod(n, 2) {
                              // Compute z * x.
                              let zx := mul(z, x)
                              // If z * x overflowed:
                              if iszero(eq(div(zx, x), z)) {
                                  // Revert if x is non-zero.
                                  if iszero(iszero(x)) {
                                      revert(0, 0)
                                  }
                              }
                              // Round to the nearest number.
                              let zxRound := add(zx, half)
                              // Revert if zx + half overflowed.
                              if lt(zxRound, zx) {
                                  revert(0, 0)
                              }
                              // Return properly scaled zxRound.
                              z := div(zxRound, scalar)
                          }
                      }
                  }
              }
          }
          /*//////////////////////////////////////////////////////////////
                              GENERAL NUMBER UTILITIES
          //////////////////////////////////////////////////////////////*/
          function sqrt(uint256 x) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  let y := x // We start y at x, which will help us make our initial estimate.
                  z := 181 // The "correct" value is 1, but this saves a multiplication later.
                  // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                  // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                  // We check y >= 2^(k + 8) but shift right by k bits
                  // each branch to ensure that if x >= 256, then y >= 256.
                  if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                      y := shr(128, y)
                      z := shl(64, z)
                  }
                  if iszero(lt(y, 0x1000000000000000000)) {
                      y := shr(64, y)
                      z := shl(32, z)
                  }
                  if iszero(lt(y, 0x10000000000)) {
                      y := shr(32, y)
                      z := shl(16, z)
                  }
                  if iszero(lt(y, 0x1000000)) {
                      y := shr(16, y)
                      z := shl(8, z)
                  }
                  // Goal was to get z*z*y within a small factor of x. More iterations could
                  // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
                  // We ensured y >= 256 so that the relative difference between y and y+1 is small.
                  // That's not possible if x < 256 but we can just verify those cases exhaustively.
                  // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
                  // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
                  // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
                  // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
                  // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
                  // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
                  // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
                  // There is no overflow risk here since y < 2^136 after the first branch above.
                  z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
                  // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  // If x+1 is a perfect square, the Babylonian method cycles between
                  // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
                  // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                  // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
                  // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
                  z := sub(z, lt(div(x, z), z))
              }
          }
          function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Mod x by y. Note this will return
                  // 0 instead of reverting if y is zero.
                  z := mod(x, y)
              }
          }
          function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Divide x by y. Note this will return
                  // 0 instead of reverting if y is zero.
                  r := div(x, y)
              }
          }
          function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Add 1 to x * y if x % y > 0. Note this will
                  // return 0 instead of reverting if y is zero.
                  z := add(gt(mod(x, y), 0), div(x, y))
              }
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      import {ERC20} from "../tokens/ERC20.sol";
      /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
      /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
      /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
      library SafeTransferLib {
          /*//////////////////////////////////////////////////////////////
                                   ETH OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function safeTransferETH(address to, uint256 amount) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Transfer the ETH and store if it succeeded or not.
                  success := call(gas(), to, amount, 0, 0, 0, 0)
              }
              require(success, "ETH_TRANSFER_FAILED");
          }
          /*//////////////////////////////////////////////////////////////
                                  ERC20 OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function safeTransferFrom(
              ERC20 token,
              address from,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
                  mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
                  )
              }
              require(success, "TRANSFER_FROM_FAILED");
          }
          function safeTransfer(
              ERC20 token,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                  )
              }
              require(success, "TRANSFER_FAILED");
          }
          function safeApprove(
              ERC20 token,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                  )
              }
              require(success, "APPROVE_FAILED");
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
      /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
      /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
      abstract contract ERC20 {
          /*//////////////////////////////////////////////////////////////
                                       EVENTS
          //////////////////////////////////////////////////////////////*/
          event Transfer(address indexed from, address indexed to, uint256 amount);
          event Approval(address indexed owner, address indexed spender, uint256 amount);
          /*//////////////////////////////////////////////////////////////
                                  METADATA STORAGE
          //////////////////////////////////////////////////////////////*/
          string public name;
          string public symbol;
          uint8 public immutable decimals;
          /*//////////////////////////////////////////////////////////////
                                    ERC20 STORAGE
          //////////////////////////////////////////////////////////////*/
          uint256 public totalSupply;
          mapping(address => uint256) public balanceOf;
          mapping(address => mapping(address => uint256)) public allowance;
          /*//////////////////////////////////////////////////////////////
                                  EIP-2612 STORAGE
          //////////////////////////////////////////////////////////////*/
          uint256 internal immutable INITIAL_CHAIN_ID;
          bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
          mapping(address => uint256) public nonces;
          /*//////////////////////////////////////////////////////////////
                                     CONSTRUCTOR
          //////////////////////////////////////////////////////////////*/
          constructor(
              string memory _name,
              string memory _symbol,
              uint8 _decimals
          ) {
              name = _name;
              symbol = _symbol;
              decimals = _decimals;
              INITIAL_CHAIN_ID = block.chainid;
              INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
          }
          /*//////////////////////////////////////////////////////////////
                                     ERC20 LOGIC
          //////////////////////////////////////////////////////////////*/
          function approve(address spender, uint256 amount) public virtual returns (bool) {
              allowance[msg.sender][spender] = amount;
              emit Approval(msg.sender, spender, amount);
              return true;
          }
          function transfer(address to, uint256 amount) public virtual returns (bool) {
              balanceOf[msg.sender] -= amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(msg.sender, to, amount);
              return true;
          }
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) public virtual returns (bool) {
              uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
              if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
              balanceOf[from] -= amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(from, to, amount);
              return true;
          }
          /*//////////////////////////////////////////////////////////////
                                   EIP-2612 LOGIC
          //////////////////////////////////////////////////////////////*/
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) public virtual {
              require(deadline >= block.timestamp, "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,
                                      nonces[owner]++,
                                      deadline
                                  )
                              )
                          )
                      ),
                      v,
                      r,
                      s
                  );
                  require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                  allowance[recoveredAddress][spender] = value;
              }
              emit Approval(owner, spender, value);
          }
          function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
              return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
          }
          function computeDomainSeparator() internal view virtual returns (bytes32) {
              return
                  keccak256(
                      abi.encode(
                          keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                          keccak256(bytes(name)),
                          keccak256("1"),
                          block.chainid,
                          address(this)
                      )
                  );
          }
          /*//////////////////////////////////////////////////////////////
                              INTERNAL MINT/BURN LOGIC
          //////////////////////////////////////////////////////////////*/
          function _mint(address to, uint256 amount) internal virtual {
              totalSupply += amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(address(0), to, amount);
          }
          function _burn(address from, uint256 amount) internal virtual {
              balanceOf[from] -= amount;
              // Cannot underflow because a user's balance
              // will never be larger than the total supply.
              unchecked {
                  totalSupply -= amount;
              }
              emit Transfer(from, address(0), amount);
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      interface BeforeTransferHook {
          function beforeTransfer(address from, address to, address operator) external view;
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      abstract contract Auth {
          event OwnershipTransferred(address indexed user, address indexed newOwner);
          event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
          address public owner;
          Authority public authority;
          constructor(address _owner, Authority _authority) {
              owner = _owner;
              authority = _authority;
              emit OwnershipTransferred(msg.sender, _owner);
              emit AuthorityUpdated(msg.sender, _authority);
          }
          modifier requiresAuth() virtual {
              require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
              _;
          }
          function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
              Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
              // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
              // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
              return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
          }
          function setAuthority(Authority newAuthority) public virtual {
              // We check if the caller is the owner first because we want to ensure they can
              // always swap out the authority even if it's reverting or using up a lot of gas.
              require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
              authority = newAuthority;
              emit AuthorityUpdated(msg.sender, newAuthority);
          }
          function transferOwnership(address newOwner) public virtual requiresAuth {
              owner = newOwner;
              emit OwnershipTransferred(msg.sender, newOwner);
          }
      }
      /// @notice A generic interface for a contract which provides authorization data to an Auth instance.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      interface Authority {
          function canCall(
              address user,
              address target,
              bytes4 functionSig
          ) external view returns (bool);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
      pragma solidity ^0.8.20;
      /**
       * @title ERC721 token receiver interface
       * @dev Interface for any contract that wants to support safeTransfers
       * from ERC721 asset contracts.
       */
      interface IERC721Receiver {
          /**
           * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
           * by `operator` from `from`, this function is called.
           *
           * It must return its Solidity selector to confirm the token transfer.
           * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
           * reverted.
           *
           * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.20;
      import {IERC165} from "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
       * for the additional interface id that will be supported. For example:
       *
       * ```solidity
       * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
       *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
       * }
       * ```
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)
      pragma solidity ^0.8.20;
      import {IERC165} from "../../utils/introspection/IERC165.sol";
      /**
       * @dev Interface that must be implemented by smart contracts in order to receive
       * ERC-1155 token transfers.
       */
      interface IERC1155Receiver is IERC165 {
          /**
           * @dev Handles the receipt of a single ERC1155 token type. This function is
           * called at the end of a `safeTransferFrom` after the balance has been updated.
           *
           * NOTE: To accept the transfer, this must return
           * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
           * (i.e. 0xf23a6e61, or its own function selector).
           *
           * @param operator The address which initiated the transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param id The ID of the token being transferred
           * @param value The amount of tokens being transferred
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
           */
          function onERC1155Received(
              address operator,
              address from,
              uint256 id,
              uint256 value,
              bytes calldata data
          ) external returns (bytes4);
          /**
           * @dev Handles the receipt of a multiple ERC1155 token types. This function
           * is called at the end of a `safeBatchTransferFrom` after the balances have
           * been updated.
           *
           * NOTE: To accept the transfer(s), this must return
           * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
           * (i.e. 0xbc197c81, or its own function selector).
           *
           * @param operator The address which initiated the batch transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param ids An array containing ids of each token being transferred (order and length must match values array)
           * @param values An array containing amounts of each token being transferred (order and length must match ids array)
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
           */
          function onERC1155BatchReceived(
              address operator,
              address from,
              uint256[] calldata ids,
              uint256[] calldata values,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.20;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * Implementers can declare support of contract interfaces, which can then be
       * queried by others ({ERC165Checker}).
       *
       * For an implementation, see {ERC165}.
       */
      interface IERC165 {
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30 000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
      }
      

      File 3 of 5: WETH9
      // Copyright (C) 2015, 2016, 2017 Dapphub
      
      // This program is free software: you can redistribute it and/or modify
      // it under the terms of the GNU General Public License as published by
      // the Free Software Foundation, either version 3 of the License, or
      // (at your option) any later version.
      
      // This program is distributed in the hope that it will be useful,
      // but WITHOUT ANY WARRANTY; without even the implied warranty of
      // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      // GNU General Public License for more details.
      
      // You should have received a copy of the GNU General Public License
      // along with this program.  If not, see <http://www.gnu.org/licenses/>.
      
      pragma solidity ^0.4.18;
      
      contract WETH9 {
          string public name     = "Wrapped Ether";
          string public symbol   = "WETH";
          uint8  public decimals = 18;
      
          event  Approval(address indexed src, address indexed guy, uint wad);
          event  Transfer(address indexed src, address indexed dst, uint wad);
          event  Deposit(address indexed dst, uint wad);
          event  Withdrawal(address indexed src, uint wad);
      
          mapping (address => uint)                       public  balanceOf;
          mapping (address => mapping (address => uint))  public  allowance;
      
          function() public payable {
              deposit();
          }
          function deposit() public payable {
              balanceOf[msg.sender] += msg.value;
              Deposit(msg.sender, msg.value);
          }
          function withdraw(uint wad) public {
              require(balanceOf[msg.sender] >= wad);
              balanceOf[msg.sender] -= wad;
              msg.sender.transfer(wad);
              Withdrawal(msg.sender, wad);
          }
      
          function totalSupply() public view returns (uint) {
              return this.balance;
          }
      
          function approve(address guy, uint wad) public returns (bool) {
              allowance[msg.sender][guy] = wad;
              Approval(msg.sender, guy, wad);
              return true;
          }
      
          function transfer(address dst, uint wad) public returns (bool) {
              return transferFrom(msg.sender, dst, wad);
          }
      
          function transferFrom(address src, address dst, uint wad)
              public
              returns (bool)
          {
              require(balanceOf[src] >= wad);
      
              if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
                  require(allowance[src][msg.sender] >= wad);
                  allowance[src][msg.sender] -= wad;
              }
      
              balanceOf[src] -= wad;
              balanceOf[dst] += wad;
      
              Transfer(src, dst, wad);
      
              return true;
          }
      }
      
      
      /*
                          GNU GENERAL PUBLIC LICENSE
                             Version 3, 29 June 2007
      
       Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
       Everyone is permitted to copy and distribute verbatim copies
       of this license document, but changing it is not allowed.
      
                                  Preamble
      
        The GNU General Public License is a free, copyleft license for
      software and other kinds of works.
      
        The licenses for most software and other practical works are designed
      to take away your freedom to share and change the works.  By contrast,
      the GNU General Public License is intended to guarantee your freedom to
      share and change all versions of a program--to make sure it remains free
      software for all its users.  We, the Free Software Foundation, use the
      GNU General Public License for most of our software; it applies also to
      any other work released this way by its authors.  You can apply it to
      your programs, too.
      
        When we speak of free software, we are referring to freedom, not
      price.  Our General Public Licenses are designed to make sure that you
      have the freedom to distribute copies of free software (and charge for
      them if you wish), that you receive source code or can get it if you
      want it, that you can change the software or use pieces of it in new
      free programs, and that you know you can do these things.
      
        To protect your rights, we need to prevent others from denying you
      these rights or asking you to surrender the rights.  Therefore, you have
      certain responsibilities if you distribute copies of the software, or if
      you modify it: responsibilities to respect the freedom of others.
      
        For example, if you distribute copies of such a program, whether
      gratis or for a fee, you must pass on to the recipients the same
      freedoms that you received.  You must make sure that they, too, receive
      or can get the source code.  And you must show them these terms so they
      know their rights.
      
        Developers that use the GNU GPL protect your rights with two steps:
      (1) assert copyright on the software, and (2) offer you this License
      giving you legal permission to copy, distribute and/or modify it.
      
        For the developers' and authors' protection, the GPL clearly explains
      that there is no warranty for this free software.  For both users' and
      authors' sake, the GPL requires that modified versions be marked as
      changed, so that their problems will not be attributed erroneously to
      authors of previous versions.
      
        Some devices are designed to deny users access to install or run
      modified versions of the software inside them, although the manufacturer
      can do so.  This is fundamentally incompatible with the aim of
      protecting users' freedom to change the software.  The systematic
      pattern of such abuse occurs in the area of products for individuals to
      use, which is precisely where it is most unacceptable.  Therefore, we
      have designed this version of the GPL to prohibit the practice for those
      products.  If such problems arise substantially in other domains, we
      stand ready to extend this provision to those domains in future versions
      of the GPL, as needed to protect the freedom of users.
      
        Finally, every program is threatened constantly by software patents.
      States should not allow patents to restrict development and use of
      software on general-purpose computers, but in those that do, we wish to
      avoid the special danger that patents applied to a free program could
      make it effectively proprietary.  To prevent this, the GPL assures that
      patents cannot be used to render the program non-free.
      
        The precise terms and conditions for copying, distribution and
      modification follow.
      
                             TERMS AND CONDITIONS
      
        0. Definitions.
      
        "This License" refers to version 3 of the GNU General Public License.
      
        "Copyright" also means copyright-like laws that apply to other kinds of
      works, such as semiconductor masks.
      
        "The Program" refers to any copyrightable work licensed under this
      License.  Each licensee is addressed as "you".  "Licensees" and
      "recipients" may be individuals or organizations.
      
        To "modify" a work means to copy from or adapt all or part of the work
      in a fashion requiring copyright permission, other than the making of an
      exact copy.  The resulting work is called a "modified version" of the
      earlier work or a work "based on" the earlier work.
      
        A "covered work" means either the unmodified Program or a work based
      on the Program.
      
        To "propagate" a work means to do anything with it that, without
      permission, would make you directly or secondarily liable for
      infringement under applicable copyright law, except executing it on a
      computer or modifying a private copy.  Propagation includes copying,
      distribution (with or without modification), making available to the
      public, and in some countries other activities as well.
      
        To "convey" a work means any kind of propagation that enables other
      parties to make or receive copies.  Mere interaction with a user through
      a computer network, with no transfer of a copy, is not conveying.
      
        An interactive user interface displays "Appropriate Legal Notices"
      to the extent that it includes a convenient and prominently visible
      feature that (1) displays an appropriate copyright notice, and (2)
      tells the user that there is no warranty for the work (except to the
      extent that warranties are provided), that licensees may convey the
      work under this License, and how to view a copy of this License.  If
      the interface presents a list of user commands or options, such as a
      menu, a prominent item in the list meets this criterion.
      
        1. Source Code.
      
        The "source code" for a work means the preferred form of the work
      for making modifications to it.  "Object code" means any non-source
      form of a work.
      
        A "Standard Interface" means an interface that either is an official
      standard defined by a recognized standards body, or, in the case of
      interfaces specified for a particular programming language, one that
      is widely used among developers working in that language.
      
        The "System Libraries" of an executable work include anything, other
      than the work as a whole, that (a) is included in the normal form of
      packaging a Major Component, but which is not part of that Major
      Component, and (b) serves only to enable use of the work with that
      Major Component, or to implement a Standard Interface for which an
      implementation is available to the public in source code form.  A
      "Major Component", in this context, means a major essential component
      (kernel, window system, and so on) of the specific operating system
      (if any) on which the executable work runs, or a compiler used to
      produce the work, or an object code interpreter used to run it.
      
        The "Corresponding Source" for a work in object code form means all
      the source code needed to generate, install, and (for an executable
      work) run the object code and to modify the work, including scripts to
      control those activities.  However, it does not include the work's
      System Libraries, or general-purpose tools or generally available free
      programs which are used unmodified in performing those activities but
      which are not part of the work.  For example, Corresponding Source
      includes interface definition files associated with source files for
      the work, and the source code for shared libraries and dynamically
      linked subprograms that the work is specifically designed to require,
      such as by intimate data communication or control flow between those
      subprograms and other parts of the work.
      
        The Corresponding Source need not include anything that users
      can regenerate automatically from other parts of the Corresponding
      Source.
      
        The Corresponding Source for a work in source code form is that
      same work.
      
        2. Basic Permissions.
      
        All rights granted under this License are granted for the term of
      copyright on the Program, and are irrevocable provided the stated
      conditions are met.  This License explicitly affirms your unlimited
      permission to run the unmodified Program.  The output from running a
      covered work is covered by this License only if the output, given its
      content, constitutes a covered work.  This License acknowledges your
      rights of fair use or other equivalent, as provided by copyright law.
      
        You may make, run and propagate covered works that you do not
      convey, without conditions so long as your license otherwise remains
      in force.  You may convey covered works to others for the sole purpose
      of having them make modifications exclusively for you, or provide you
      with facilities for running those works, provided that you comply with
      the terms of this License in conveying all material for which you do
      not control copyright.  Those thus making or running the covered works
      for you must do so exclusively on your behalf, under your direction
      and control, on terms that prohibit them from making any copies of
      your copyrighted material outside their relationship with you.
      
        Conveying under any other circumstances is permitted solely under
      the conditions stated below.  Sublicensing is not allowed; section 10
      makes it unnecessary.
      
        3. Protecting Users' Legal Rights From Anti-Circumvention Law.
      
        No covered work shall be deemed part of an effective technological
      measure under any applicable law fulfilling obligations under article
      11 of the WIPO copyright treaty adopted on 20 December 1996, or
      similar laws prohibiting or restricting circumvention of such
      measures.
      
        When you convey a covered work, you waive any legal power to forbid
      circumvention of technological measures to the extent such circumvention
      is effected by exercising rights under this License with respect to
      the covered work, and you disclaim any intention to limit operation or
      modification of the work as a means of enforcing, against the work's
      users, your or third parties' legal rights to forbid circumvention of
      technological measures.
      
        4. Conveying Verbatim Copies.
      
        You may convey verbatim copies of the Program's source code as you
      receive it, in any medium, provided that you conspicuously and
      appropriately publish on each copy an appropriate copyright notice;
      keep intact all notices stating that this License and any
      non-permissive terms added in accord with section 7 apply to the code;
      keep intact all notices of the absence of any warranty; and give all
      recipients a copy of this License along with the Program.
      
        You may charge any price or no price for each copy that you convey,
      and you may offer support or warranty protection for a fee.
      
        5. Conveying Modified Source Versions.
      
        You may convey a work based on the Program, or the modifications to
      produce it from the Program, in the form of source code under the
      terms of section 4, provided that you also meet all of these conditions:
      
          a) The work must carry prominent notices stating that you modified
          it, and giving a relevant date.
      
          b) The work must carry prominent notices stating that it is
          released under this License and any conditions added under section
          7.  This requirement modifies the requirement in section 4 to
          "keep intact all notices".
      
          c) You must license the entire work, as a whole, under this
          License to anyone who comes into possession of a copy.  This
          License will therefore apply, along with any applicable section 7
          additional terms, to the whole of the work, and all its parts,
          regardless of how they are packaged.  This License gives no
          permission to license the work in any other way, but it does not
          invalidate such permission if you have separately received it.
      
          d) If the work has interactive user interfaces, each must display
          Appropriate Legal Notices; however, if the Program has interactive
          interfaces that do not display Appropriate Legal Notices, your
          work need not make them do so.
      
        A compilation of a covered work with other separate and independent
      works, which are not by their nature extensions of the covered work,
      and which are not combined with it such as to form a larger program,
      in or on a volume of a storage or distribution medium, is called an
      "aggregate" if the compilation and its resulting copyright are not
      used to limit the access or legal rights of the compilation's users
      beyond what the individual works permit.  Inclusion of a covered work
      in an aggregate does not cause this License to apply to the other
      parts of the aggregate.
      
        6. Conveying Non-Source Forms.
      
        You may convey a covered work in object code form under the terms
      of sections 4 and 5, provided that you also convey the
      machine-readable Corresponding Source under the terms of this License,
      in one of these ways:
      
          a) Convey the object code in, or embodied in, a physical product
          (including a physical distribution medium), accompanied by the
          Corresponding Source fixed on a durable physical medium
          customarily used for software interchange.
      
          b) Convey the object code in, or embodied in, a physical product
          (including a physical distribution medium), accompanied by a
          written offer, valid for at least three years and valid for as
          long as you offer spare parts or customer support for that product
          model, to give anyone who possesses the object code either (1) a
          copy of the Corresponding Source for all the software in the
          product that is covered by this License, on a durable physical
          medium customarily used for software interchange, for a price no
          more than your reasonable cost of physically performing this
          conveying of source, or (2) access to copy the
          Corresponding Source from a network server at no charge.
      
          c) Convey individual copies of the object code with a copy of the
          written offer to provide the Corresponding Source.  This
          alternative is allowed only occasionally and noncommercially, and
          only if you received the object code with such an offer, in accord
          with subsection 6b.
      
          d) Convey the object code by offering access from a designated
          place (gratis or for a charge), and offer equivalent access to the
          Corresponding Source in the same way through the same place at no
          further charge.  You need not require recipients to copy the
          Corresponding Source along with the object code.  If the place to
          copy the object code is a network server, the Corresponding Source
          may be on a different server (operated by you or a third party)
          that supports equivalent copying facilities, provided you maintain
          clear directions next to the object code saying where to find the
          Corresponding Source.  Regardless of what server hosts the
          Corresponding Source, you remain obligated to ensure that it is
          available for as long as needed to satisfy these requirements.
      
          e) Convey the object code using peer-to-peer transmission, provided
          you inform other peers where the object code and Corresponding
          Source of the work are being offered to the general public at no
          charge under subsection 6d.
      
        A separable portion of the object code, whose source code is excluded
      from the Corresponding Source as a System Library, need not be
      included in conveying the object code work.
      
        A "User Product" is either (1) a "consumer product", which means any
      tangible personal property which is normally used for personal, family,
      or household purposes, or (2) anything designed or sold for incorporation
      into a dwelling.  In determining whether a product is a consumer product,
      doubtful cases shall be resolved in favor of coverage.  For a particular
      product received by a particular user, "normally used" refers to a
      typical or common use of that class of product, regardless of the status
      of the particular user or of the way in which the particular user
      actually uses, or expects or is expected to use, the product.  A product
      is a consumer product regardless of whether the product has substantial
      commercial, industrial or non-consumer uses, unless such uses represent
      the only significant mode of use of the product.
      
        "Installation Information" for a User Product means any methods,
      procedures, authorization keys, or other information required to install
      and execute modified versions of a covered work in that User Product from
      a modified version of its Corresponding Source.  The information must
      suffice to ensure that the continued functioning of the modified object
      code is in no case prevented or interfered with solely because
      modification has been made.
      
        If you convey an object code work under this section in, or with, or
      specifically for use in, a User Product, and the conveying occurs as
      part of a transaction in which the right of possession and use of the
      User Product is transferred to the recipient in perpetuity or for a
      fixed term (regardless of how the transaction is characterized), the
      Corresponding Source conveyed under this section must be accompanied
      by the Installation Information.  But this requirement does not apply
      if neither you nor any third party retains the ability to install
      modified object code on the User Product (for example, the work has
      been installed in ROM).
      
        The requirement to provide Installation Information does not include a
      requirement to continue to provide support service, warranty, or updates
      for a work that has been modified or installed by the recipient, or for
      the User Product in which it has been modified or installed.  Access to a
      network may be denied when the modification itself materially and
      adversely affects the operation of the network or violates the rules and
      protocols for communication across the network.
      
        Corresponding Source conveyed, and Installation Information provided,
      in accord with this section must be in a format that is publicly
      documented (and with an implementation available to the public in
      source code form), and must require no special password or key for
      unpacking, reading or copying.
      
        7. Additional Terms.
      
        "Additional permissions" are terms that supplement the terms of this
      License by making exceptions from one or more of its conditions.
      Additional permissions that are applicable to the entire Program shall
      be treated as though they were included in this License, to the extent
      that they are valid under applicable law.  If additional permissions
      apply only to part of the Program, that part may be used separately
      under those permissions, but the entire Program remains governed by
      this License without regard to the additional permissions.
      
        When you convey a copy of a covered work, you may at your option
      remove any additional permissions from that copy, or from any part of
      it.  (Additional permissions may be written to require their own
      removal in certain cases when you modify the work.)  You may place
      additional permissions on material, added by you to a covered work,
      for which you have or can give appropriate copyright permission.
      
        Notwithstanding any other provision of this License, for material you
      add to a covered work, you may (if authorized by the copyright holders of
      that material) supplement the terms of this License with terms:
      
          a) Disclaiming warranty or limiting liability differently from the
          terms of sections 15 and 16 of this License; or
      
          b) Requiring preservation of specified reasonable legal notices or
          author attributions in that material or in the Appropriate Legal
          Notices displayed by works containing it; or
      
          c) Prohibiting misrepresentation of the origin of that material, or
          requiring that modified versions of such material be marked in
          reasonable ways as different from the original version; or
      
          d) Limiting the use for publicity purposes of names of licensors or
          authors of the material; or
      
          e) Declining to grant rights under trademark law for use of some
          trade names, trademarks, or service marks; or
      
          f) Requiring indemnification of licensors and authors of that
          material by anyone who conveys the material (or modified versions of
          it) with contractual assumptions of liability to the recipient, for
          any liability that these contractual assumptions directly impose on
          those licensors and authors.
      
        All other non-permissive additional terms are considered "further
      restrictions" within the meaning of section 10.  If the Program as you
      received it, or any part of it, contains a notice stating that it is
      governed by this License along with a term that is a further
      restriction, you may remove that term.  If a license document contains
      a further restriction but permits relicensing or conveying under this
      License, you may add to a covered work material governed by the terms
      of that license document, provided that the further restriction does
      not survive such relicensing or conveying.
      
        If you add terms to a covered work in accord with this section, you
      must place, in the relevant source files, a statement of the
      additional terms that apply to those files, or a notice indicating
      where to find the applicable terms.
      
        Additional terms, permissive or non-permissive, may be stated in the
      form of a separately written license, or stated as exceptions;
      the above requirements apply either way.
      
        8. Termination.
      
        You may not propagate or modify a covered work except as expressly
      provided under this License.  Any attempt otherwise to propagate or
      modify it is void, and will automatically terminate your rights under
      this License (including any patent licenses granted under the third
      paragraph of section 11).
      
        However, if you cease all violation of this License, then your
      license from a particular copyright holder is reinstated (a)
      provisionally, unless and until the copyright holder explicitly and
      finally terminates your license, and (b) permanently, if the copyright
      holder fails to notify you of the violation by some reasonable means
      prior to 60 days after the cessation.
      
        Moreover, your license from a particular copyright holder is
      reinstated permanently if the copyright holder notifies you of the
      violation by some reasonable means, this is the first time you have
      received notice of violation of this License (for any work) from that
      copyright holder, and you cure the violation prior to 30 days after
      your receipt of the notice.
      
        Termination of your rights under this section does not terminate the
      licenses of parties who have received copies or rights from you under
      this License.  If your rights have been terminated and not permanently
      reinstated, you do not qualify to receive new licenses for the same
      material under section 10.
      
        9. Acceptance Not Required for Having Copies.
      
        You are not required to accept this License in order to receive or
      run a copy of the Program.  Ancillary propagation of a covered work
      occurring solely as a consequence of using peer-to-peer transmission
      to receive a copy likewise does not require acceptance.  However,
      nothing other than this License grants you permission to propagate or
      modify any covered work.  These actions infringe copyright if you do
      not accept this License.  Therefore, by modifying or propagating a
      covered work, you indicate your acceptance of this License to do so.
      
        10. Automatic Licensing of Downstream Recipients.
      
        Each time you convey a covered work, the recipient automatically
      receives a license from the original licensors, to run, modify and
      propagate that work, subject to this License.  You are not responsible
      for enforcing compliance by third parties with this License.
      
        An "entity transaction" is a transaction transferring control of an
      organization, or substantially all assets of one, or subdividing an
      organization, or merging organizations.  If propagation of a covered
      work results from an entity transaction, each party to that
      transaction who receives a copy of the work also receives whatever
      licenses to the work the party's predecessor in interest had or could
      give under the previous paragraph, plus a right to possession of the
      Corresponding Source of the work from the predecessor in interest, if
      the predecessor has it or can get it with reasonable efforts.
      
        You may not impose any further restrictions on the exercise of the
      rights granted or affirmed under this License.  For example, you may
      not impose a license fee, royalty, or other charge for exercise of
      rights granted under this License, and you may not initiate litigation
      (including a cross-claim or counterclaim in a lawsuit) alleging that
      any patent claim is infringed by making, using, selling, offering for
      sale, or importing the Program or any portion of it.
      
        11. Patents.
      
        A "contributor" is a copyright holder who authorizes use under this
      License of the Program or a work on which the Program is based.  The
      work thus licensed is called the contributor's "contributor version".
      
        A contributor's "essential patent claims" are all patent claims
      owned or controlled by the contributor, whether already acquired or
      hereafter acquired, that would be infringed by some manner, permitted
      by this License, of making, using, or selling its contributor version,
      but do not include claims that would be infringed only as a
      consequence of further modification of the contributor version.  For
      purposes of this definition, "control" includes the right to grant
      patent sublicenses in a manner consistent with the requirements of
      this License.
      
        Each contributor grants you a non-exclusive, worldwide, royalty-free
      patent license under the contributor's essential patent claims, to
      make, use, sell, offer for sale, import and otherwise run, modify and
      propagate the contents of its contributor version.
      
        In the following three paragraphs, a "patent license" is any express
      agreement or commitment, however denominated, not to enforce a patent
      (such as an express permission to practice a patent or covenant not to
      sue for patent infringement).  To "grant" such a patent license to a
      party means to make such an agreement or commitment not to enforce a
      patent against the party.
      
        If you convey a covered work, knowingly relying on a patent license,
      and the Corresponding Source of the work is not available for anyone
      to copy, free of charge and under the terms of this License, through a
      publicly available network server or other readily accessible means,
      then you must either (1) cause the Corresponding Source to be so
      available, or (2) arrange to deprive yourself of the benefit of the
      patent license for this particular work, or (3) arrange, in a manner
      consistent with the requirements of this License, to extend the patent
      license to downstream recipients.  "Knowingly relying" means you have
      actual knowledge that, but for the patent license, your conveying the
      covered work in a country, or your recipient's use of the covered work
      in a country, would infringe one or more identifiable patents in that
      country that you have reason to believe are valid.
      
        If, pursuant to or in connection with a single transaction or
      arrangement, you convey, or propagate by procuring conveyance of, a
      covered work, and grant a patent license to some of the parties
      receiving the covered work authorizing them to use, propagate, modify
      or convey a specific copy of the covered work, then the patent license
      you grant is automatically extended to all recipients of the covered
      work and works based on it.
      
        A patent license is "discriminatory" if it does not include within
      the scope of its coverage, prohibits the exercise of, or is
      conditioned on the non-exercise of one or more of the rights that are
      specifically granted under this License.  You may not convey a covered
      work if you are a party to an arrangement with a third party that is
      in the business of distributing software, under which you make payment
      to the third party based on the extent of your activity of conveying
      the work, and under which the third party grants, to any of the
      parties who would receive the covered work from you, a discriminatory
      patent license (a) in connection with copies of the covered work
      conveyed by you (or copies made from those copies), or (b) primarily
      for and in connection with specific products or compilations that
      contain the covered work, unless you entered into that arrangement,
      or that patent license was granted, prior to 28 March 2007.
      
        Nothing in this License shall be construed as excluding or limiting
      any implied license or other defenses to infringement that may
      otherwise be available to you under applicable patent law.
      
        12. No Surrender of Others' Freedom.
      
        If conditions are imposed on you (whether by court order, agreement or
      otherwise) that contradict the conditions of this License, they do not
      excuse you from the conditions of this License.  If you cannot convey a
      covered work so as to satisfy simultaneously your obligations under this
      License and any other pertinent obligations, then as a consequence you may
      not convey it at all.  For example, if you agree to terms that obligate you
      to collect a royalty for further conveying from those to whom you convey
      the Program, the only way you could satisfy both those terms and this
      License would be to refrain entirely from conveying the Program.
      
        13. Use with the GNU Affero General Public License.
      
        Notwithstanding any other provision of this License, you have
      permission to link or combine any covered work with a work licensed
      under version 3 of the GNU Affero General Public License into a single
      combined work, and to convey the resulting work.  The terms of this
      License will continue to apply to the part which is the covered work,
      but the special requirements of the GNU Affero General Public License,
      section 13, concerning interaction through a network will apply to the
      combination as such.
      
        14. Revised Versions of this License.
      
        The Free Software Foundation may publish revised and/or new versions of
      the GNU General Public License from time to time.  Such new versions will
      be similar in spirit to the present version, but may differ in detail to
      address new problems or concerns.
      
        Each version is given a distinguishing version number.  If the
      Program specifies that a certain numbered version of the GNU General
      Public License "or any later version" applies to it, you have the
      option of following the terms and conditions either of that numbered
      version or of any later version published by the Free Software
      Foundation.  If the Program does not specify a version number of the
      GNU General Public License, you may choose any version ever published
      by the Free Software Foundation.
      
        If the Program specifies that a proxy can decide which future
      versions of the GNU General Public License can be used, that proxy's
      public statement of acceptance of a version permanently authorizes you
      to choose that version for the Program.
      
        Later license versions may give you additional or different
      permissions.  However, no additional obligations are imposed on any
      author or copyright holder as a result of your choosing to follow a
      later version.
      
        15. Disclaimer of Warranty.
      
        THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
      APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
      HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
      OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
      THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
      PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
      IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
      ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
      
        16. Limitation of Liability.
      
        IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
      WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
      THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
      GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
      USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
      DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
      PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
      EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
      SUCH DAMAGES.
      
        17. Interpretation of Sections 15 and 16.
      
        If the disclaimer of warranty and limitation of liability provided
      above cannot be given local legal effect according to their terms,
      reviewing courts shall apply local law that most closely approximates
      an absolute waiver of all civil liability in connection with the
      Program, unless a warranty or assumption of liability accompanies a
      copy of the Program in return for a fee.
      
                           END OF TERMS AND CONDITIONS
      
                  How to Apply These Terms to Your New Programs
      
        If you develop a new program, and you want it to be of the greatest
      possible use to the public, the best way to achieve this is to make it
      free software which everyone can redistribute and change under these terms.
      
        To do so, attach the following notices to the program.  It is safest
      to attach them to the start of each source file to most effectively
      state the exclusion of warranty; and each file should have at least
      the "copyright" line and a pointer to where the full notice is found.
      
          <one line to give the program's name and a brief idea of what it does.>
          Copyright (C) <year>  <name of author>
      
          This program is free software: you can redistribute it and/or modify
          it under the terms of the GNU General Public License as published by
          the Free Software Foundation, either version 3 of the License, or
          (at your option) any later version.
      
          This program is distributed in the hope that it will be useful,
          but WITHOUT ANY WARRANTY; without even the implied warranty of
          MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
          GNU General Public License for more details.
      
          You should have received a copy of the GNU General Public License
          along with this program.  If not, see <http://www.gnu.org/licenses/>.
      
      Also add information on how to contact you by electronic and paper mail.
      
        If the program does terminal interaction, make it output a short
      notice like this when it starts in an interactive mode:
      
          <program>  Copyright (C) <year>  <name of author>
          This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
          This is free software, and you are welcome to redistribute it
          under certain conditions; type `show c' for details.
      
      The hypothetical commands `show w' and `show c' should show the appropriate
      parts of the General Public License.  Of course, your program's commands
      might be different; for a GUI interface, you would use an "about box".
      
        You should also get your employer (if you work as a programmer) or school,
      if any, to sign a "copyright disclaimer" for the program, if necessary.
      For more information on this, and how to apply and follow the GNU GPL, see
      <http://www.gnu.org/licenses/>.
      
        The GNU General Public License does not permit incorporating your program
      into proprietary programs.  If your program is a subroutine library, you
      may consider it more useful to permit linking proprietary applications with
      the library.  If this is what you want to do, use the GNU Lesser General
      Public License instead of this License.  But first, please read
      <http://www.gnu.org/philosophy/why-not-lgpl.html>.
      
      */

      File 4 of 5: RolesAuthority
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      import {Auth, Authority} from "../Auth.sol";
      /// @notice Role based Authority that supports up to 256 roles.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/authorities/RolesAuthority.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-roles/blob/master/src/roles.sol)
      contract RolesAuthority is Auth, Authority {
          /*//////////////////////////////////////////////////////////////
                                       EVENTS
          //////////////////////////////////////////////////////////////*/
          event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);
          event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled);
          event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled);
          /*//////////////////////////////////////////////////////////////
                                     CONSTRUCTOR
          //////////////////////////////////////////////////////////////*/
          constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}
          /*//////////////////////////////////////////////////////////////
                                  ROLE/USER STORAGE
          //////////////////////////////////////////////////////////////*/
          mapping(address => bytes32) public getUserRoles;
          mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic;
          mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability;
          function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {
              return (uint256(getUserRoles[user]) >> role) & 1 != 0;
          }
          function doesRoleHaveCapability(
              uint8 role,
              address target,
              bytes4 functionSig
          ) public view virtual returns (bool) {
              return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0;
          }
          /*//////////////////////////////////////////////////////////////
                                 AUTHORIZATION LOGIC
          //////////////////////////////////////////////////////////////*/
          function canCall(
              address user,
              address target,
              bytes4 functionSig
          ) public view virtual override returns (bool) {
              return
                  isCapabilityPublic[target][functionSig] ||
                  bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig];
          }
          /*//////////////////////////////////////////////////////////////
                         ROLE CAPABILITY CONFIGURATION LOGIC
          //////////////////////////////////////////////////////////////*/
          function setPublicCapability(
              address target,
              bytes4 functionSig,
              bool enabled
          ) public virtual requiresAuth {
              isCapabilityPublic[target][functionSig] = enabled;
              emit PublicCapabilityUpdated(target, functionSig, enabled);
          }
          function setRoleCapability(
              uint8 role,
              address target,
              bytes4 functionSig,
              bool enabled
          ) public virtual requiresAuth {
              if (enabled) {
                  getRolesWithCapability[target][functionSig] |= bytes32(1 << role);
              } else {
                  getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role);
              }
              emit RoleCapabilityUpdated(role, target, functionSig, enabled);
          }
          /*//////////////////////////////////////////////////////////////
                             USER ROLE ASSIGNMENT LOGIC
          //////////////////////////////////////////////////////////////*/
          function setUserRole(
              address user,
              uint8 role,
              bool enabled
          ) public virtual requiresAuth {
              if (enabled) {
                  getUserRoles[user] |= bytes32(1 << role);
              } else {
                  getUserRoles[user] &= ~bytes32(1 << role);
              }
              emit UserRoleUpdated(user, role, enabled);
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      abstract contract Auth {
          event OwnershipTransferred(address indexed user, address indexed newOwner);
          event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
          address public owner;
          Authority public authority;
          constructor(address _owner, Authority _authority) {
              owner = _owner;
              authority = _authority;
              emit OwnershipTransferred(msg.sender, _owner);
              emit AuthorityUpdated(msg.sender, _authority);
          }
          modifier requiresAuth() virtual {
              require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
              _;
          }
          function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
              Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
              // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
              // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
              return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
          }
          function setAuthority(Authority newAuthority) public virtual {
              // We check if the caller is the owner first because we want to ensure they can
              // always swap out the authority even if it's reverting or using up a lot of gas.
              require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
              authority = newAuthority;
              emit AuthorityUpdated(msg.sender, newAuthority);
          }
          function transferOwnership(address newOwner) public virtual requiresAuth {
              owner = newOwner;
              emit OwnershipTransferred(msg.sender, newOwner);
          }
      }
      /// @notice A generic interface for a contract which provides authorization data to an Auth instance.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      interface Authority {
          function canCall(
              address user,
              address target,
              bytes4 functionSig
          ) external view returns (bool);
      }
      

      File 5 of 5: AccountantWithRateProviders
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
      import {IRateProvider} from "src/interfaces/IRateProvider.sol";
      import {ERC20} from "@solmate/tokens/ERC20.sol";
      import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
      import {BoringVault} from "src/base/BoringVault.sol";
      import {Auth, Authority} from "@solmate/auth/Auth.sol";
      import {IPausable} from "src/interfaces/IPausable.sol";
      contract AccountantWithRateProviders is Auth, IRateProvider, IPausable {
          using FixedPointMathLib for uint256;
          using SafeTransferLib for ERC20;
          // ========================================= STRUCTS =========================================
          /**
           * @param payoutAddress the address `claimFees` sends fees to
           * @param highwaterMark the highest value of the BoringVault's share price
           * @param feesOwedInBase total pending fees owed in terms of base
           * @param totalSharesLastUpdate total amount of shares the last exchange rate update
           * @param exchangeRate the current exchange rate in terms of base
           * @param allowedExchangeRateChangeUpper the max allowed change to exchange rate from an update
           * @param allowedExchangeRateChangeLower the min allowed change to exchange rate from an update
           * @param lastUpdateTimestamp the block timestamp of the last exchange rate update
           * @param isPaused whether or not this contract is paused
           * @param minimumUpdateDelayInSeconds the minimum amount of time that must pass between
           *        exchange rate updates, such that the update won't trigger the contract to be paused
           * @param platformFee the platform fee
           * @param performanceFee the performance fee
           */
          struct AccountantState {
              address payoutAddress;
              uint96 highwaterMark;
              uint128 feesOwedInBase;
              uint128 totalSharesLastUpdate;
              uint96 exchangeRate;
              uint16 allowedExchangeRateChangeUpper;
              uint16 allowedExchangeRateChangeLower;
              uint64 lastUpdateTimestamp;
              bool isPaused;
              uint24 minimumUpdateDelayInSeconds;
              uint16 platformFee;
              uint16 performanceFee;
          }
          /**
           * @param isPeggedToBase whether or not the asset is 1:1 with the base asset
           * @param rateProvider the rate provider for this asset if `isPeggedToBase` is false
           */
          struct RateProviderData {
              bool isPeggedToBase;
              IRateProvider rateProvider;
          }
          // ========================================= STATE =========================================
          /**
           * @notice Store the accountant state in 3 packed slots.
           */
          AccountantState public accountantState;
          /**
           * @notice Maps ERC20s to their RateProviderData.
           */
          mapping(ERC20 => RateProviderData) public rateProviderData;
          //============================== ERRORS ===============================
          error AccountantWithRateProviders__UpperBoundTooSmall();
          error AccountantWithRateProviders__LowerBoundTooLarge();
          error AccountantWithRateProviders__PlatformFeeTooLarge();
          error AccountantWithRateProviders__PerformanceFeeTooLarge();
          error AccountantWithRateProviders__Paused();
          error AccountantWithRateProviders__ZeroFeesOwed();
          error AccountantWithRateProviders__OnlyCallableByBoringVault();
          error AccountantWithRateProviders__UpdateDelayTooLarge();
          error AccountantWithRateProviders__ExchangeRateAboveHighwaterMark();
          //============================== EVENTS ===============================
          event Paused();
          event Unpaused();
          event DelayInSecondsUpdated(uint24 oldDelay, uint24 newDelay);
          event UpperBoundUpdated(uint16 oldBound, uint16 newBound);
          event LowerBoundUpdated(uint16 oldBound, uint16 newBound);
          event PlatformFeeUpdated(uint16 oldFee, uint16 newFee);
          event PerformanceFeeUpdated(uint16 oldFee, uint16 newFee);
          event PayoutAddressUpdated(address oldPayout, address newPayout);
          event RateProviderUpdated(address asset, bool isPegged, address rateProvider);
          event ExchangeRateUpdated(uint96 oldRate, uint96 newRate, uint64 currentTime);
          event FeesClaimed(address indexed feeAsset, uint256 amount);
          event HighwaterMarkReset();
          //============================== IMMUTABLES ===============================
          /**
           * @notice The base asset rates are provided in.
           */
          ERC20 public immutable base;
          /**
           * @notice The decimals rates are provided in.
           */
          uint8 public immutable decimals;
          /**
           * @notice The BoringVault this accountant is working with.
           *         Used to determine share supply for fee calculation.
           */
          BoringVault public immutable vault;
          /**
           * @notice One share of the BoringVault.
           */
          uint256 internal immutable ONE_SHARE;
          constructor(
              address _owner,
              address _vault,
              address payoutAddress,
              uint96 startingExchangeRate,
              address _base,
              uint16 allowedExchangeRateChangeUpper,
              uint16 allowedExchangeRateChangeLower,
              uint24 minimumUpdateDelayInSeconds,
              uint16 platformFee,
              uint16 performanceFee
          ) Auth(_owner, Authority(address(0))) {
              base = ERC20(_base);
              decimals = ERC20(_base).decimals();
              vault = BoringVault(payable(_vault));
              ONE_SHARE = 10 ** vault.decimals();
              accountantState = AccountantState({
                  payoutAddress: payoutAddress,
                  highwaterMark: startingExchangeRate,
                  feesOwedInBase: 0,
                  totalSharesLastUpdate: uint128(vault.totalSupply()),
                  exchangeRate: startingExchangeRate,
                  allowedExchangeRateChangeUpper: allowedExchangeRateChangeUpper,
                  allowedExchangeRateChangeLower: allowedExchangeRateChangeLower,
                  lastUpdateTimestamp: uint64(block.timestamp),
                  isPaused: false,
                  minimumUpdateDelayInSeconds: minimumUpdateDelayInSeconds,
                  platformFee: platformFee,
                  performanceFee: performanceFee
              });
          }
          // ========================================= ADMIN FUNCTIONS =========================================
          /**
           * @notice Pause this contract, which prevents future calls to `updateExchangeRate`, and any safe rate
           *         calls will revert.
           * @dev Callable by MULTISIG_ROLE.
           */
          function pause() external requiresAuth {
              accountantState.isPaused = true;
              emit Paused();
          }
          /**
           * @notice Unpause this contract, which allows future calls to `updateExchangeRate`, and any safe rate
           *         calls will stop reverting.
           * @dev Callable by MULTISIG_ROLE.
           */
          function unpause() external requiresAuth {
              accountantState.isPaused = false;
              emit Unpaused();
          }
          /**
           * @notice Update the minimum time delay between `updateExchangeRate` calls.
           * @dev There are no input requirements, as it is possible the admin would want
           *      the exchange rate updated as frequently as needed.
           * @dev Callable by OWNER_ROLE.
           */
          function updateDelay(uint24 minimumUpdateDelayInSeconds) external requiresAuth {
              if (minimumUpdateDelayInSeconds > 14 days) revert AccountantWithRateProviders__UpdateDelayTooLarge();
              uint24 oldDelay = accountantState.minimumUpdateDelayInSeconds;
              accountantState.minimumUpdateDelayInSeconds = minimumUpdateDelayInSeconds;
              emit DelayInSecondsUpdated(oldDelay, minimumUpdateDelayInSeconds);
          }
          /**
           * @notice Update the allowed upper bound change of exchange rate between `updateExchangeRateCalls`.
           * @dev Callable by OWNER_ROLE.
           */
          function updateUpper(uint16 allowedExchangeRateChangeUpper) external requiresAuth {
              if (allowedExchangeRateChangeUpper < 1e4) revert AccountantWithRateProviders__UpperBoundTooSmall();
              uint16 oldBound = accountantState.allowedExchangeRateChangeUpper;
              accountantState.allowedExchangeRateChangeUpper = allowedExchangeRateChangeUpper;
              emit UpperBoundUpdated(oldBound, allowedExchangeRateChangeUpper);
          }
          /**
           * @notice Update the allowed lower bound change of exchange rate between `updateExchangeRateCalls`.
           * @dev Callable by OWNER_ROLE.
           */
          function updateLower(uint16 allowedExchangeRateChangeLower) external requiresAuth {
              if (allowedExchangeRateChangeLower > 1e4) revert AccountantWithRateProviders__LowerBoundTooLarge();
              uint16 oldBound = accountantState.allowedExchangeRateChangeLower;
              accountantState.allowedExchangeRateChangeLower = allowedExchangeRateChangeLower;
              emit LowerBoundUpdated(oldBound, allowedExchangeRateChangeLower);
          }
          /**
           * @notice Update the platform fee to a new value.
           * @dev Callable by OWNER_ROLE.
           */
          function updatePlatformFee(uint16 platformFee) external requiresAuth {
              if (platformFee > 0.2e4) revert AccountantWithRateProviders__PlatformFeeTooLarge();
              uint16 oldFee = accountantState.platformFee;
              accountantState.platformFee = platformFee;
              emit PlatformFeeUpdated(oldFee, platformFee);
          }
          /**
           * @notice Update the performance fee to a new value.
           * @dev Callable by OWNER_ROLE.
           */
          function updatePerformanceFee(uint16 performanceFee) external requiresAuth {
              if (performanceFee > 0.5e4) revert AccountantWithRateProviders__PerformanceFeeTooLarge();
              uint16 oldFee = accountantState.performanceFee;
              accountantState.performanceFee = performanceFee;
              emit PerformanceFeeUpdated(oldFee, performanceFee);
          }
          /**
           * @notice Update the payout address fees are sent to.
           * @dev Callable by OWNER_ROLE.
           */
          function updatePayoutAddress(address payoutAddress) external requiresAuth {
              address oldPayout = accountantState.payoutAddress;
              accountantState.payoutAddress = payoutAddress;
              emit PayoutAddressUpdated(oldPayout, payoutAddress);
          }
          /**
           * @notice Update the rate provider data for a specific `asset`.
           * @dev Rate providers must return rates in terms of `base` or
           * an asset pegged to base and they must use the same decimals
           * as `asset`.
           * @dev Callable by OWNER_ROLE.
           */
          function setRateProviderData(ERC20 asset, bool isPeggedToBase, address rateProvider) external requiresAuth {
              rateProviderData[asset] =
                  RateProviderData({isPeggedToBase: isPeggedToBase, rateProvider: IRateProvider(rateProvider)});
              emit RateProviderUpdated(address(asset), isPeggedToBase, rateProvider);
          }
          /**
           * @notice Reset the highwater mark to the current exchange rate.
           * @dev Callable by OWNER_ROLE.
           */
          function resetHighwaterMark() external virtual requiresAuth {
              AccountantState storage state = accountantState;
              if (state.exchangeRate > state.highwaterMark) {
                  revert AccountantWithRateProviders__ExchangeRateAboveHighwaterMark();
              }
              uint64 currentTime = uint64(block.timestamp);
              uint256 currentTotalShares = vault.totalSupply();
              _calculateFeesOwed(state, state.exchangeRate, state.exchangeRate, currentTotalShares, currentTime);
              state.totalSharesLastUpdate = uint128(currentTotalShares);
              state.highwaterMark = accountantState.exchangeRate;
              state.lastUpdateTimestamp = currentTime;
              emit HighwaterMarkReset();
          }
          // ========================================= UPDATE EXCHANGE RATE/FEES FUNCTIONS =========================================
          /**
           * @notice Updates this contract exchangeRate.
           * @dev If new exchange rate is outside of accepted bounds, or if not enough time has passed, this
           *      will pause the contract, and this function will NOT calculate fees owed.
           * @dev Callable by UPDATE_EXCHANGE_RATE_ROLE.
           */
          function updateExchangeRate(uint96 newExchangeRate) external virtual requiresAuth {
              (
                  bool shouldPause,
                  AccountantState storage state,
                  uint64 currentTime,
                  uint256 currentExchangeRate,
                  uint256 currentTotalShares
              ) = _beforeUpdateExchangeRate(newExchangeRate);
              if (shouldPause) {
                  // Instead of reverting, pause the contract. This way the exchange rate updater is able to update the exchange rate
                  // to a better value, and pause it.
                  state.isPaused = true;
              } else {
                  _calculateFeesOwed(state, newExchangeRate, currentExchangeRate, currentTotalShares, currentTime);
              }
              newExchangeRate = _setExchangeRate(newExchangeRate, state);
              state.totalSharesLastUpdate = uint128(currentTotalShares);
              state.lastUpdateTimestamp = currentTime;
              emit ExchangeRateUpdated(uint96(currentExchangeRate), newExchangeRate, currentTime);
          }
          /**
           * @notice Claim pending fees.
           * @dev This function must be called by the BoringVault.
           * @dev This function will lose precision if the exchange rate
           *      decimals is greater than the feeAsset's decimals.
           */
          function claimFees(ERC20 feeAsset) external {
              if (msg.sender != address(vault)) revert AccountantWithRateProviders__OnlyCallableByBoringVault();
              AccountantState storage state = accountantState;
              if (state.isPaused) revert AccountantWithRateProviders__Paused();
              if (state.feesOwedInBase == 0) revert AccountantWithRateProviders__ZeroFeesOwed();
              // Determine amount of fees owed in feeAsset.
              uint256 feesOwedInFeeAsset;
              RateProviderData memory data = rateProviderData[feeAsset];
              if (address(feeAsset) == address(base)) {
                  feesOwedInFeeAsset = state.feesOwedInBase;
              } else {
                  uint8 feeAssetDecimals = ERC20(feeAsset).decimals();
                  uint256 feesOwedInBaseUsingFeeAssetDecimals =
                      _changeDecimals(state.feesOwedInBase, decimals, feeAssetDecimals);
                  if (data.isPeggedToBase) {
                      feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals;
                  } else {
                      uint256 rate = data.rateProvider.getRate();
                      feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals.mulDivDown(10 ** feeAssetDecimals, rate);
                  }
              }
              // Zero out fees owed.
              state.feesOwedInBase = 0;
              // Transfer fee asset to payout address.
              feeAsset.safeTransferFrom(msg.sender, state.payoutAddress, feesOwedInFeeAsset);
              emit FeesClaimed(address(feeAsset), feesOwedInFeeAsset);
          }
          // ========================================= VIEW FUNCTIONS =========================================
          /**
           * @notice Get this BoringVault's current rate in the base.
           */
          function getRate() public view returns (uint256 rate) {
              rate = accountantState.exchangeRate;
          }
          /**
           * @notice Get this BoringVault's current rate in the base.
           * @dev Revert if paused.
           */
          function getRateSafe() external view returns (uint256 rate) {
              if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
              rate = getRate();
          }
          /**
           * @notice Get this BoringVault's current rate in the provided quote.
           * @dev `quote` must have its RateProviderData set, else this will revert.
           * @dev This function will lose precision if the exchange rate
           *      decimals is greater than the quote's decimals.
           */
          function getRateInQuote(ERC20 quote) public view returns (uint256 rateInQuote) {
              if (address(quote) == address(base)) {
                  rateInQuote = accountantState.exchangeRate;
              } else {
                  RateProviderData memory data = rateProviderData[quote];
                  uint8 quoteDecimals = ERC20(quote).decimals();
                  uint256 exchangeRateInQuoteDecimals = _changeDecimals(accountantState.exchangeRate, decimals, quoteDecimals);
                  if (data.isPeggedToBase) {
                      rateInQuote = exchangeRateInQuoteDecimals;
                  } else {
                      uint256 quoteRate = data.rateProvider.getRate();
                      uint256 oneQuote = 10 ** quoteDecimals;
                      rateInQuote = oneQuote.mulDivDown(exchangeRateInQuoteDecimals, quoteRate);
                  }
              }
          }
          /**
           * @notice Get this BoringVault's current rate in the provided quote.
           * @dev `quote` must have its RateProviderData set, else this will revert.
           * @dev Revert if paused.
           */
          function getRateInQuoteSafe(ERC20 quote) external view returns (uint256 rateInQuote) {
              if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
              rateInQuote = getRateInQuote(quote);
          }
          /**
           * @notice Preview the result of an update to the exchange rate.
           * @return updateWillPause Whether the update will pause the contract.
           * @return newFeesOwedInBase The new fees owed in base.
           * @return totalFeesOwedInBase The total fees owed in base.
           */
          function previewUpdateExchangeRate(uint96 newExchangeRate)
              external
              view
              virtual
              returns (bool updateWillPause, uint256 newFeesOwedInBase, uint256 totalFeesOwedInBase)
          {
              (
                  bool shouldPause,
                  AccountantState storage state,
                  uint64 currentTime,
                  uint256 currentExchangeRate,
                  uint256 currentTotalShares
              ) = _beforeUpdateExchangeRate(newExchangeRate);
              updateWillPause = shouldPause;
              totalFeesOwedInBase = state.feesOwedInBase;
              if (!shouldPause) {
                  (uint256 platformFeesOwedInBase, uint256 shareSupplyToUse) = _calculatePlatformFee(
                      state.totalSharesLastUpdate,
                      state.lastUpdateTimestamp,
                      state.platformFee,
                      newExchangeRate,
                      currentExchangeRate,
                      currentTotalShares,
                      currentTime
                  );
                  uint256 performanceFeesOwedInBase;
                  if (newExchangeRate > state.highwaterMark) {
                      (performanceFeesOwedInBase,) = _calculatePerformanceFee(
                          newExchangeRate, shareSupplyToUse, state.highwaterMark, state.performanceFee
                      );
                  }
                  newFeesOwedInBase = platformFeesOwedInBase + performanceFeesOwedInBase;
                  totalFeesOwedInBase += newFeesOwedInBase;
              }
          }
          // ========================================= INTERNAL HELPER FUNCTIONS =========================================
          /**
           * @notice Used to change the decimals of precision used for an amount.
           */
          function _changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
              if (fromDecimals == toDecimals) {
                  return amount;
              } else if (fromDecimals < toDecimals) {
                  return amount * 10 ** (toDecimals - fromDecimals);
              } else {
                  return amount / 10 ** (fromDecimals - toDecimals);
              }
          }
          /**
           * @notice Check if the new exchange rate is outside of the allowed bounds or if not enough time has passed.
           */
          function _beforeUpdateExchangeRate(uint96 newExchangeRate)
              internal
              view
              returns (
                  bool shouldPause,
                  AccountantState storage state,
                  uint64 currentTime,
                  uint256 currentExchangeRate,
                  uint256 currentTotalShares
              )
          {
              state = accountantState;
              if (state.isPaused) revert AccountantWithRateProviders__Paused();
              currentTime = uint64(block.timestamp);
              currentExchangeRate = state.exchangeRate;
              currentTotalShares = vault.totalSupply();
              shouldPause = currentTime < state.lastUpdateTimestamp + state.minimumUpdateDelayInSeconds
                  || newExchangeRate > currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeUpper, 1e4)
                  || newExchangeRate < currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeLower, 1e4);
          }
          /**
           * @notice Set the exchange rate.
           */
          function _setExchangeRate(uint96 newExchangeRate, AccountantState storage state)
              internal
              virtual
              returns (uint96)
          {
              state.exchangeRate = newExchangeRate;
              return newExchangeRate;
          }
          /**
           * @notice Calculate platform fees.
           */
          function _calculatePlatformFee(
              uint128 totalSharesLastUpdate,
              uint64 lastUpdateTimestamp,
              uint16 platformFee,
              uint96 newExchangeRate,
              uint256 currentExchangeRate,
              uint256 currentTotalShares,
              uint64 currentTime
          ) internal view returns (uint256 platformFeesOwedInBase, uint256 shareSupplyToUse) {
              shareSupplyToUse = currentTotalShares;
              // Use the minimum between current total supply and total supply for last update.
              if (totalSharesLastUpdate < shareSupplyToUse) {
                  shareSupplyToUse = totalSharesLastUpdate;
              }
              // Determine platform fees owned.
              if (platformFee > 0) {
                  uint256 timeDelta = currentTime - lastUpdateTimestamp;
                  uint256 minimumAssets = newExchangeRate > currentExchangeRate
                      ? shareSupplyToUse.mulDivDown(currentExchangeRate, ONE_SHARE)
                      : shareSupplyToUse.mulDivDown(newExchangeRate, ONE_SHARE);
                  uint256 platformFeesAnnual = minimumAssets.mulDivDown(platformFee, 1e4);
                  platformFeesOwedInBase = platformFeesAnnual.mulDivDown(timeDelta, 365 days);
              }
          }
          /**
           * @notice Calculate performance fees.
           */
          function _calculatePerformanceFee(
              uint96 newExchangeRate,
              uint256 shareSupplyToUse,
              uint96 datum,
              uint16 performanceFee
          ) internal view returns (uint256 performanceFeesOwedInBase, uint256 yieldEarned) {
              uint256 changeInExchangeRate = newExchangeRate - datum;
              yieldEarned = changeInExchangeRate.mulDivDown(shareSupplyToUse, ONE_SHARE);
              if (performanceFee > 0) {
                  performanceFeesOwedInBase = yieldEarned.mulDivDown(performanceFee, 1e4);
              }
          }
          /**
           * @notice Calculate fees owed in base.
           * @dev This function will update the highwater mark if the new exchange rate is higher.
           */
          function _calculateFeesOwed(
              AccountantState storage state,
              uint96 newExchangeRate,
              uint256 currentExchangeRate,
              uint256 currentTotalShares,
              uint64 currentTime
          ) internal virtual {
              // Only update fees if we are not paused.
              // Update fee accounting.
              (uint256 newFeesOwedInBase, uint256 shareSupplyToUse) = _calculatePlatformFee(
                  state.totalSharesLastUpdate,
                  state.lastUpdateTimestamp,
                  state.platformFee,
                  newExchangeRate,
                  currentExchangeRate,
                  currentTotalShares,
                  currentTime
              );
              // Account for performance fees.
              if (newExchangeRate > state.highwaterMark) {
                  (uint256 performanceFeesOwedInBase,) =
                      _calculatePerformanceFee(newExchangeRate, shareSupplyToUse, state.highwaterMark, state.performanceFee);
                  // Add performance fees to fees owed.
                  newFeesOwedInBase += performanceFeesOwedInBase;
                  // Always update the highwater mark if the new exchange rate is higher.
                  // This way if we are not iniitiall taking performance fees, we can start taking them
                  // without back charging them on past performance.
                  state.highwaterMark = newExchangeRate;
              }
              state.feesOwedInBase += uint128(newFeesOwedInBase);
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Arithmetic library with operations for fixed-point numbers.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
      /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
      library FixedPointMathLib {
          /*//////////////////////////////////////////////////////////////
                          SIMPLIFIED FIXED POINT OPERATIONS
          //////////////////////////////////////////////////////////////*/
          uint256 internal constant MAX_UINT256 = 2**256 - 1;
          uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
          function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
          }
          function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
          }
          function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
          }
          function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
              return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
          }
          /*//////////////////////////////////////////////////////////////
                          LOW LEVEL FIXED POINT OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function mulDivDown(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
                  if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                      revert(0, 0)
                  }
                  // Divide x * y by the denominator.
                  z := div(mul(x, y), denominator)
              }
          }
          function mulDivUp(
              uint256 x,
              uint256 y,
              uint256 denominator
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
                  if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                      revert(0, 0)
                  }
                  // If x * y modulo the denominator is strictly greater than 0,
                  // 1 is added to round up the division of x * y by the denominator.
                  z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
              }
          }
          function rpow(
              uint256 x,
              uint256 n,
              uint256 scalar
          ) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  switch x
                  case 0 {
                      switch n
                      case 0 {
                          // 0 ** 0 = 1
                          z := scalar
                      }
                      default {
                          // 0 ** n = 0
                          z := 0
                      }
                  }
                  default {
                      switch mod(n, 2)
                      case 0 {
                          // If n is even, store scalar in z for now.
                          z := scalar
                      }
                      default {
                          // If n is odd, store x in z for now.
                          z := x
                      }
                      // Shifting right by 1 is like dividing by 2.
                      let half := shr(1, scalar)
                      for {
                          // Shift n right by 1 before looping to halve it.
                          n := shr(1, n)
                      } n {
                          // Shift n right by 1 each iteration to halve it.
                          n := shr(1, n)
                      } {
                          // Revert immediately if x ** 2 would overflow.
                          // Equivalent to iszero(eq(div(xx, x), x)) here.
                          if shr(128, x) {
                              revert(0, 0)
                          }
                          // Store x squared.
                          let xx := mul(x, x)
                          // Round to the nearest number.
                          let xxRound := add(xx, half)
                          // Revert if xx + half overflowed.
                          if lt(xxRound, xx) {
                              revert(0, 0)
                          }
                          // Set x to scaled xxRound.
                          x := div(xxRound, scalar)
                          // If n is even:
                          if mod(n, 2) {
                              // Compute z * x.
                              let zx := mul(z, x)
                              // If z * x overflowed:
                              if iszero(eq(div(zx, x), z)) {
                                  // Revert if x is non-zero.
                                  if iszero(iszero(x)) {
                                      revert(0, 0)
                                  }
                              }
                              // Round to the nearest number.
                              let zxRound := add(zx, half)
                              // Revert if zx + half overflowed.
                              if lt(zxRound, zx) {
                                  revert(0, 0)
                              }
                              // Return properly scaled zxRound.
                              z := div(zxRound, scalar)
                          }
                      }
                  }
              }
          }
          /*//////////////////////////////////////////////////////////////
                              GENERAL NUMBER UTILITIES
          //////////////////////////////////////////////////////////////*/
          function sqrt(uint256 x) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  let y := x // We start y at x, which will help us make our initial estimate.
                  z := 181 // The "correct" value is 1, but this saves a multiplication later.
                  // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
                  // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
                  // We check y >= 2^(k + 8) but shift right by k bits
                  // each branch to ensure that if x >= 256, then y >= 256.
                  if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                      y := shr(128, y)
                      z := shl(64, z)
                  }
                  if iszero(lt(y, 0x1000000000000000000)) {
                      y := shr(64, y)
                      z := shl(32, z)
                  }
                  if iszero(lt(y, 0x10000000000)) {
                      y := shr(32, y)
                      z := shl(16, z)
                  }
                  if iszero(lt(y, 0x1000000)) {
                      y := shr(16, y)
                      z := shl(8, z)
                  }
                  // Goal was to get z*z*y within a small factor of x. More iterations could
                  // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
                  // We ensured y >= 256 so that the relative difference between y and y+1 is small.
                  // That's not possible if x < 256 but we can just verify those cases exhaustively.
                  // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
                  // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
                  // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
                  // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
                  // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
                  // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
                  // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
                  // There is no overflow risk here since y < 2^136 after the first branch above.
                  z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
                  // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  z := shr(1, add(z, div(x, z)))
                  // If x+1 is a perfect square, the Babylonian method cycles between
                  // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
                  // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
                  // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
                  // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
                  z := sub(z, lt(div(x, z), z))
              }
          }
          function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Mod x by y. Note this will return
                  // 0 instead of reverting if y is zero.
                  z := mod(x, y)
              }
          }
          function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Divide x by y. Note this will return
                  // 0 instead of reverting if y is zero.
                  r := div(x, y)
              }
          }
          function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
              /// @solidity memory-safe-assembly
              assembly {
                  // Add 1 to x * y if x % y > 0. Note this will
                  // return 0 instead of reverting if y is zero.
                  z := add(gt(mod(x, y), 0), div(x, y))
              }
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      // This program is free software: you can redistribute it and/or modify
      // it under the terms of the GNU General Public License as published by
      // the Free Software Foundation, either version 3 of the License, or
      // (at your option) any later version.
      // This program is distributed in the hope that it will be useful,
      // but WITHOUT ANY WARRANTY; without even the implied warranty of
      // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      // GNU General Public License for more details.
      // You should have received a copy of the GNU General Public License
      // along with this program.  If not, see <http://www.gnu.org/licenses/>.
      pragma solidity ^0.8.0;
      interface IRateProvider {
          function getRate() external view returns (uint256);
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
      /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
      /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
      abstract contract ERC20 {
          /*//////////////////////////////////////////////////////////////
                                       EVENTS
          //////////////////////////////////////////////////////////////*/
          event Transfer(address indexed from, address indexed to, uint256 amount);
          event Approval(address indexed owner, address indexed spender, uint256 amount);
          /*//////////////////////////////////////////////////////////////
                                  METADATA STORAGE
          //////////////////////////////////////////////////////////////*/
          string public name;
          string public symbol;
          uint8 public immutable decimals;
          /*//////////////////////////////////////////////////////////////
                                    ERC20 STORAGE
          //////////////////////////////////////////////////////////////*/
          uint256 public totalSupply;
          mapping(address => uint256) public balanceOf;
          mapping(address => mapping(address => uint256)) public allowance;
          /*//////////////////////////////////////////////////////////////
                                  EIP-2612 STORAGE
          //////////////////////////////////////////////////////////////*/
          uint256 internal immutable INITIAL_CHAIN_ID;
          bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
          mapping(address => uint256) public nonces;
          /*//////////////////////////////////////////////////////////////
                                     CONSTRUCTOR
          //////////////////////////////////////////////////////////////*/
          constructor(
              string memory _name,
              string memory _symbol,
              uint8 _decimals
          ) {
              name = _name;
              symbol = _symbol;
              decimals = _decimals;
              INITIAL_CHAIN_ID = block.chainid;
              INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
          }
          /*//////////////////////////////////////////////////////////////
                                     ERC20 LOGIC
          //////////////////////////////////////////////////////////////*/
          function approve(address spender, uint256 amount) public virtual returns (bool) {
              allowance[msg.sender][spender] = amount;
              emit Approval(msg.sender, spender, amount);
              return true;
          }
          function transfer(address to, uint256 amount) public virtual returns (bool) {
              balanceOf[msg.sender] -= amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(msg.sender, to, amount);
              return true;
          }
          function transferFrom(
              address from,
              address to,
              uint256 amount
          ) public virtual returns (bool) {
              uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
              if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
              balanceOf[from] -= amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(from, to, amount);
              return true;
          }
          /*//////////////////////////////////////////////////////////////
                                   EIP-2612 LOGIC
          //////////////////////////////////////////////////////////////*/
          function permit(
              address owner,
              address spender,
              uint256 value,
              uint256 deadline,
              uint8 v,
              bytes32 r,
              bytes32 s
          ) public virtual {
              require(deadline >= block.timestamp, "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,
                                      nonces[owner]++,
                                      deadline
                                  )
                              )
                          )
                      ),
                      v,
                      r,
                      s
                  );
                  require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
                  allowance[recoveredAddress][spender] = value;
              }
              emit Approval(owner, spender, value);
          }
          function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
              return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
          }
          function computeDomainSeparator() internal view virtual returns (bytes32) {
              return
                  keccak256(
                      abi.encode(
                          keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                          keccak256(bytes(name)),
                          keccak256("1"),
                          block.chainid,
                          address(this)
                      )
                  );
          }
          /*//////////////////////////////////////////////////////////////
                              INTERNAL MINT/BURN LOGIC
          //////////////////////////////////////////////////////////////*/
          function _mint(address to, uint256 amount) internal virtual {
              totalSupply += amount;
              // Cannot overflow because the sum of all user
              // balances can't exceed the max uint256 value.
              unchecked {
                  balanceOf[to] += amount;
              }
              emit Transfer(address(0), to, amount);
          }
          function _burn(address from, uint256 amount) internal virtual {
              balanceOf[from] -= amount;
              // Cannot underflow because a user's balance
              // will never be larger than the total supply.
              unchecked {
                  totalSupply -= amount;
              }
              emit Transfer(from, address(0), amount);
          }
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      import {ERC20} from "../tokens/ERC20.sol";
      /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
      /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
      /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
      library SafeTransferLib {
          /*//////////////////////////////////////////////////////////////
                                   ETH OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function safeTransferETH(address to, uint256 amount) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Transfer the ETH and store if it succeeded or not.
                  success := call(gas(), to, amount, 0, 0, 0, 0)
              }
              require(success, "ETH_TRANSFER_FAILED");
          }
          /*//////////////////////////////////////////////////////////////
                                  ERC20 OPERATIONS
          //////////////////////////////////////////////////////////////*/
          function safeTransferFrom(
              ERC20 token,
              address from,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
                  mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
                  )
              }
              require(success, "TRANSFER_FROM_FAILED");
          }
          function safeTransfer(
              ERC20 token,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                  )
              }
              require(success, "TRANSFER_FAILED");
          }
          function safeApprove(
              ERC20 token,
              address to,
              uint256 amount
          ) internal {
              bool success;
              /// @solidity memory-safe-assembly
              assembly {
                  // Get a pointer to some free memory.
                  let freeMemoryPointer := mload(0x40)
                  // Write the abi-encoded calldata into memory, beginning with the function selector.
                  mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
                  mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                  mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
                  success := and(
                      // Set success to whether the call reverted, if not we check it either
                      // returned exactly 1 (can't just be non-zero data), or had no return data.
                      or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                      // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                      // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                      // Counterintuitively, this call must be positioned second to the or() call in the
                      // surrounding and() call or else returndatasize() will be zero during the computation.
                      call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
                  )
              }
              require(success, "APPROVE_FAILED");
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      import {Address} from "@openzeppelin/contracts/utils/Address.sol";
      import {ERC721Holder} from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
      import {ERC1155Holder} from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
      import {FixedPointMathLib} from "@solmate/utils/FixedPointMathLib.sol";
      import {SafeTransferLib} from "@solmate/utils/SafeTransferLib.sol";
      import {ERC20} from "@solmate/tokens/ERC20.sol";
      import {BeforeTransferHook} from "src/interfaces/BeforeTransferHook.sol";
      import {Auth, Authority} from "@solmate/auth/Auth.sol";
      contract BoringVault is ERC20, Auth, ERC721Holder, ERC1155Holder {
          using Address for address;
          using SafeTransferLib for ERC20;
          using FixedPointMathLib for uint256;
          // ========================================= STATE =========================================
          /**
           * @notice Contract responsbile for implementing `beforeTransfer`.
           */
          BeforeTransferHook public hook;
          //============================== EVENTS ===============================
          event Enter(address indexed from, address indexed asset, uint256 amount, address indexed to, uint256 shares);
          event Exit(address indexed to, address indexed asset, uint256 amount, address indexed from, uint256 shares);
          //============================== CONSTRUCTOR ===============================
          constructor(address _owner, string memory _name, string memory _symbol, uint8 _decimals)
              ERC20(_name, _symbol, _decimals)
              Auth(_owner, Authority(address(0)))
          {}
          //============================== MANAGE ===============================
          /**
           * @notice Allows manager to make an arbitrary function call from this contract.
           * @dev Callable by MANAGER_ROLE.
           */
          function manage(address target, bytes calldata data, uint256 value)
              external
              requiresAuth
              returns (bytes memory result)
          {
              result = target.functionCallWithValue(data, value);
          }
          /**
           * @notice Allows manager to make arbitrary function calls from this contract.
           * @dev Callable by MANAGER_ROLE.
           */
          function manage(address[] calldata targets, bytes[] calldata data, uint256[] calldata values)
              external
              requiresAuth
              returns (bytes[] memory results)
          {
              uint256 targetsLength = targets.length;
              results = new bytes[](targetsLength);
              for (uint256 i; i < targetsLength; ++i) {
                  results[i] = targets[i].functionCallWithValue(data[i], values[i]);
              }
          }
          //============================== ENTER ===============================
          /**
           * @notice Allows minter to mint shares, in exchange for assets.
           * @dev If assetAmount is zero, no assets are transferred in.
           * @dev Callable by MINTER_ROLE.
           */
          function enter(address from, ERC20 asset, uint256 assetAmount, address to, uint256 shareAmount)
              external
              requiresAuth
          {
              // Transfer assets in
              if (assetAmount > 0) asset.safeTransferFrom(from, address(this), assetAmount);
              // Mint shares.
              _mint(to, shareAmount);
              emit Enter(from, address(asset), assetAmount, to, shareAmount);
          }
          //============================== EXIT ===============================
          /**
           * @notice Allows burner to burn shares, in exchange for assets.
           * @dev If assetAmount is zero, no assets are transferred out.
           * @dev Callable by BURNER_ROLE.
           */
          function exit(address to, ERC20 asset, uint256 assetAmount, address from, uint256 shareAmount)
              external
              requiresAuth
          {
              // Burn shares.
              _burn(from, shareAmount);
              // Transfer assets out.
              if (assetAmount > 0) asset.safeTransfer(to, assetAmount);
              emit Exit(to, address(asset), assetAmount, from, shareAmount);
          }
          //============================== BEFORE TRANSFER HOOK ===============================
          /**
           * @notice Sets the share locker.
           * @notice If set to zero address, the share locker logic is disabled.
           * @dev Callable by OWNER_ROLE.
           */
          function setBeforeTransferHook(address _hook) external requiresAuth {
              hook = BeforeTransferHook(_hook);
          }
          /**
           * @notice Call `beforeTransferHook` passing in `from` `to`, and `msg.sender`.
           */
          function _callBeforeTransfer(address from, address to) internal view {
              if (address(hook) != address(0)) hook.beforeTransfer(from, to, msg.sender);
          }
          function transfer(address to, uint256 amount) public override returns (bool) {
              _callBeforeTransfer(msg.sender, to);
              return super.transfer(to, amount);
          }
          function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
              _callBeforeTransfer(from, to);
              return super.transferFrom(from, to, amount);
          }
          //============================== RECEIVE ===============================
          receive() external payable {}
      }
      // SPDX-License-Identifier: AGPL-3.0-only
      pragma solidity >=0.8.0;
      /// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      abstract contract Auth {
          event OwnershipTransferred(address indexed user, address indexed newOwner);
          event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
          address public owner;
          Authority public authority;
          constructor(address _owner, Authority _authority) {
              owner = _owner;
              authority = _authority;
              emit OwnershipTransferred(msg.sender, _owner);
              emit AuthorityUpdated(msg.sender, _authority);
          }
          modifier requiresAuth() virtual {
              require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
              _;
          }
          function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
              Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
              // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
              // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
              return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
          }
          function setAuthority(Authority newAuthority) public virtual {
              // We check if the caller is the owner first because we want to ensure they can
              // always swap out the authority even if it's reverting or using up a lot of gas.
              require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
              authority = newAuthority;
              emit AuthorityUpdated(msg.sender, newAuthority);
          }
          function transferOwnership(address newOwner) public virtual requiresAuth {
              owner = newOwner;
              emit OwnershipTransferred(msg.sender, newOwner);
          }
      }
      /// @notice A generic interface for a contract which provides authorization data to an Auth instance.
      /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
      /// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
      interface Authority {
          function canCall(
              address user,
              address target,
              bytes4 functionSig
          ) external view returns (bool);
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      interface IPausable {
          function pause() external;
          function unpause() external;
      }
      // 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) (token/ERC721/utils/ERC721Holder.sol)
      pragma solidity ^0.8.20;
      import {IERC721Receiver} from "../IERC721Receiver.sol";
      /**
       * @dev Implementation of the {IERC721Receiver} interface.
       *
       * Accepts all token transfers.
       * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
       * {IERC721-setApprovalForAll}.
       */
      abstract contract ERC721Holder is IERC721Receiver {
          /**
           * @dev See {IERC721Receiver-onERC721Received}.
           *
           * Always returns `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
              return this.onERC721Received.selector;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)
      pragma solidity ^0.8.20;
      import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
      import {IERC1155Receiver} from "../IERC1155Receiver.sol";
      /**
       * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
       *
       * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
       * stuck.
       */
      abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
              return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
          }
          function onERC1155Received(
              address,
              address,
              uint256,
              uint256,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155Received.selector;
          }
          function onERC1155BatchReceived(
              address,
              address,
              uint256[] memory,
              uint256[] memory,
              bytes memory
          ) public virtual override returns (bytes4) {
              return this.onERC1155BatchReceived.selector;
          }
      }
      // SPDX-License-Identifier: UNLICENSED
      pragma solidity 0.8.21;
      interface BeforeTransferHook {
          function beforeTransfer(address from, address to, address operator) external view;
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)
      pragma solidity ^0.8.20;
      /**
       * @title ERC721 token receiver interface
       * @dev Interface for any contract that wants to support safeTransfers
       * from ERC721 asset contracts.
       */
      interface IERC721Receiver {
          /**
           * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
           * by `operator` from `from`, this function is called.
           *
           * It must return its Solidity selector to confirm the token transfer.
           * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
           * reverted.
           *
           * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
           */
          function onERC721Received(
              address operator,
              address from,
              uint256 tokenId,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
      pragma solidity ^0.8.20;
      import {IERC165} from "./IERC165.sol";
      /**
       * @dev Implementation of the {IERC165} interface.
       *
       * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
       * for the additional interface id that will be supported. For example:
       *
       * ```solidity
       * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
       *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
       * }
       * ```
       */
      abstract contract ERC165 is IERC165 {
          /**
           * @dev See {IERC165-supportsInterface}.
           */
          function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
              return interfaceId == type(IERC165).interfaceId;
          }
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)
      pragma solidity ^0.8.20;
      import {IERC165} from "../../utils/introspection/IERC165.sol";
      /**
       * @dev Interface that must be implemented by smart contracts in order to receive
       * ERC-1155 token transfers.
       */
      interface IERC1155Receiver is IERC165 {
          /**
           * @dev Handles the receipt of a single ERC1155 token type. This function is
           * called at the end of a `safeTransferFrom` after the balance has been updated.
           *
           * NOTE: To accept the transfer, this must return
           * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
           * (i.e. 0xf23a6e61, or its own function selector).
           *
           * @param operator The address which initiated the transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param id The ID of the token being transferred
           * @param value The amount of tokens being transferred
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
           */
          function onERC1155Received(
              address operator,
              address from,
              uint256 id,
              uint256 value,
              bytes calldata data
          ) external returns (bytes4);
          /**
           * @dev Handles the receipt of a multiple ERC1155 token types. This function
           * is called at the end of a `safeBatchTransferFrom` after the balances have
           * been updated.
           *
           * NOTE: To accept the transfer(s), this must return
           * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
           * (i.e. 0xbc197c81, or its own function selector).
           *
           * @param operator The address which initiated the batch transfer (i.e. msg.sender)
           * @param from The address which previously owned the token
           * @param ids An array containing ids of each token being transferred (order and length must match values array)
           * @param values An array containing amounts of each token being transferred (order and length must match ids array)
           * @param data Additional data with no specified format
           * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
           */
          function onERC1155BatchReceived(
              address operator,
              address from,
              uint256[] calldata ids,
              uint256[] calldata values,
              bytes calldata data
          ) external returns (bytes4);
      }
      // SPDX-License-Identifier: MIT
      // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
      pragma solidity ^0.8.20;
      /**
       * @dev Interface of the ERC165 standard, as defined in the
       * https://eips.ethereum.org/EIPS/eip-165[EIP].
       *
       * Implementers can declare support of contract interfaces, which can then be
       * queried by others ({ERC165Checker}).
       *
       * For an implementation, see {ERC165}.
       */
      interface IERC165 {
          /**
           * @dev Returns true if this contract implements the interface defined by
           * `interfaceId`. See the corresponding
           * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
           * to learn more about how these ids are created.
           *
           * This function call must use less than 30 000 gas.
           */
          function supportsInterface(bytes4 interfaceId) external view returns (bool);
      }