{"constructor_args":null,"is_partially_verified":true,"is_changed_bytecode":false,"abi":[{"inputs":[],"name":"AccountBlocked","type":"error"},{"inputs":[],"name":"AnnualInterestBipsTooHigh","type":"error"},{"inputs":[],"name":"AprChangeOnClosedMarket","type":"error"},{"inputs":[],"name":"BadLaunchCode","type":"error"},{"inputs":[],"name":"BadRescueAsset","type":"error"},{"inputs":[],"name":"BorrowAmountTooHigh","type":"error"},{"inputs":[],"name":"BorrowFromClosedMarket","type":"error"},{"inputs":[],"name":"BorrowWhileSanctioned","type":"error"},{"inputs":[],"name":"BuyBackOnDelinquentMarket","type":"error"},{"inputs":[],"name":"CapacityChangeOnClosedMarket","type":"error"},{"inputs":[],"name":"CloseMarketWithUnpaidWithdrawals","type":"error"},{"inputs":[],"name":"DepositToClosedMarket","type":"error"},{"inputs":[],"name":"FIFOQueueOutOfBounds","type":"error"},{"inputs":[],"name":"InsufficientReservesForFeeWithdrawal","type":"error"},{"inputs":[],"name":"InsufficientReservesForNewLiquidityRatio","type":"error"},{"inputs":[],"name":"InsufficientReservesForOldLiquidityRatio","type":"error"},{"inputs":[],"name":"InvalidArrayLength","type":"error"},{"inputs":[],"name":"MarketAlreadyClosed","type":"error"},{"inputs":[],"name":"MaxSupplyExceeded","type":"error"},{"inputs":[],"name":"NoReentrantCalls","type":"error"},{"inputs":[],"name":"NotApprovedBorrower","type":"error"},{"inputs":[],"name":"NotApprovedLender","type":"error"},{"inputs":[],"name":"NotFactory","type":"error"},{"inputs":[],"name":"NullBurnAmount","type":"error"},{"inputs":[],"name":"NullBuyBackAmount","type":"error"},{"inputs":[],"name":"NullFeeAmount","type":"error"},{"inputs":[],"name":"NullMintAmount","type":"error"},{"inputs":[],"name":"NullRepayAmount","type":"error"},{"inputs":[],"name":"NullTransferAmount","type":"error"},{"inputs":[],"name":"NullWithdrawalAmount","type":"error"},{"inputs":[],"name":"ProtocolFeeChangeOnClosedMarket","type":"error"},{"inputs":[],"name":"ProtocolFeeTooHigh","type":"error"},{"inputs":[],"name":"RepayToClosedMarket","type":"error"},{"inputs":[],"name":"ReserveRatioBipsTooHigh","type":"error"},{"inputs":[],"name":"SphereXOperatorRequired","type":"error"},{"inputs":[],"name":"WithdrawalBatchNotExpired","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"AccountSanctioned","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"annualInterestBipsUpdated","type":"uint256"}],"name":"AnnualInterestBipsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"assetAmount","type":"uint256"}],"name":"Borrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldEngineAddress","type":"address"},{"indexed":false,"internalType":"address","name":"newEngineAddress","type":"address"}],"name":"ChangedSpherexEngineAddress","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldSphereXAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newSphereXAdmin","type":"address"}],"name":"ChangedSpherexOperator","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":false,"internalType":"uint256","name":"assetAmount","type":"uint256"}],"name":"DebtRepaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"assetAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"scaledAmount","type":"uint256"}],"name":"Deposit","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"FeesCollected","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"fromTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"toTimestamp","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"scaleFactor","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"baseInterestRay","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"delinquencyFeeRay","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolFees","type":"uint256"}],"name":"InterestAndFeesAccrued","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"MarketClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"assets","type":"uint256"}],"name":"MaxTotalSupplyUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"protocolFeeBips","type":"uint256"}],"name":"ProtocolFeeBipsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reserveRatioBipsUpdated","type":"uint256"}],"name":"ReserveRatioBipsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"expiry","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"scaledAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"normalizedAmount","type":"uint256"}],"name":"SanctionedAccountAssetsQueuedForWithdrawal","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"escrow","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"SanctionedAccountAssetsSentToEscrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"address","name":"escrow","type":"address"},{"indexed":false,"internalType":"uint32","name":"expiry","type":"uint32"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"SanctionedAccountWithdrawalSentToEscrow","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"scaleFactor","type":"uint256"},{"indexed":false,"internalType":"bool","name":"isDelinquent","type":"bool"}],"name":"StateUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"}],"name":"WithdrawalBatchClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"}],"name":"WithdrawalBatchCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"scaledTotalAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"scaledAmountBurned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"normalizedAmountPaid","type":"uint256"}],"name":"WithdrawalBatchExpired","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"scaledAmountBurned","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"normalizedAmountPaid","type":"uint256"}],"name":"WithdrawalBatchPayment","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"normalizedAmount","type":"uint256"}],"name":"WithdrawalExecuted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"expiry","type":"uint256"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"scaledAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"normalizedAmount","type":"uint256"}],"name":"WithdrawalQueued","type":"event"},{"inputs":[],"name":"accruedProtocolFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"annualInterestBips","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"archController","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"asset","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"borrow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"borrowableAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"borrower","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newSphereXEngine","type":"address"}],"name":"changeSphereXEngine","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"closeMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collectFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"coverageLiquidity","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentState","outputs":[{"components":[{"internalType":"bool","name":"isClosed","type":"bool"},{"internalType":"uint128","name":"maxTotalSupply","type":"uint128"},{"internalType":"uint128","name":"accruedProtocolFees","type":"uint128"},{"internalType":"uint128","name":"normalizedUnclaimedWithdrawals","type":"uint128"},{"internalType":"uint104","name":"scaledTotalSupply","type":"uint104"},{"internalType":"uint104","name":"scaledPendingWithdrawals","type":"uint104"},{"internalType":"uint32","name":"pendingWithdrawalExpiry","type":"uint32"},{"internalType":"bool","name":"isDelinquent","type":"bool"},{"internalType":"uint32","name":"timeDelinquent","type":"uint32"},{"internalType":"uint16","name":"protocolFeeBips","type":"uint16"},{"internalType":"uint16","name":"annualInterestBips","type":"uint16"},{"internalType":"uint16","name":"reserveRatioBips","type":"uint16"},{"internalType":"uint112","name":"scaleFactor","type":"uint112"},{"internalType":"uint32","name":"lastInterestAccruedTimestamp","type":"uint32"}],"internalType":"struct MarketState","name":"state","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"delinquencyFeeBips","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"delinquencyGracePeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"depositUpTo","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"accountAddress","type":"address"},{"internalType":"uint32","name":"expiry","type":"uint32"}],"name":"executeWithdrawal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"accountAddresses","type":"address[]"},{"internalType":"uint32[]","name":"expiries","type":"uint32[]"}],"name":"executeWithdrawals","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"feeRecipient","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"accountAddress","type":"address"},{"internalType":"uint32","name":"expiry","type":"uint32"}],"name":"getAccountWithdrawalStatus","outputs":[{"components":[{"internalType":"uint104","name":"scaledAmount","type":"uint104"},{"internalType":"uint128","name":"normalizedAmountWithdrawn","type":"uint128"}],"internalType":"struct AccountWithdrawalStatus","name":"status","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"accountAddress","type":"address"},{"internalType":"uint32","name":"expiry","type":"uint32"}],"name":"getAvailableWithdrawalAmount","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getUnpaidBatchExpiries","outputs":[{"internalType":"uint32[]","name":"","type":"uint32[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"expiry","type":"uint32"}],"name":"getWithdrawalBatch","outputs":[{"components":[{"internalType":"uint104","name":"scaledTotalAmount","type":"uint104"},{"internalType":"uint104","name":"scaledAmountBurned","type":"uint104"},{"internalType":"uint128","name":"normalizedAmountPaid","type":"uint128"}],"internalType":"struct WithdrawalBatch","name":"batch","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hooks","outputs":[{"internalType":"HooksConfig","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isClosed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxTotalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maximumDeposit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"accountAddress","type":"address"}],"name":"nukeFromOrbit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"previousState","outputs":[{"components":[{"internalType":"bool","name":"isClosed","type":"bool"},{"internalType":"uint128","name":"maxTotalSupply","type":"uint128"},{"internalType":"uint128","name":"accruedProtocolFees","type":"uint128"},{"internalType":"uint128","name":"normalizedUnclaimedWithdrawals","type":"uint128"},{"internalType":"uint104","name":"scaledTotalSupply","type":"uint104"},{"internalType":"uint104","name":"scaledPendingWithdrawals","type":"uint104"},{"internalType":"uint32","name":"pendingWithdrawalExpiry","type":"uint32"},{"internalType":"bool","name":"isDelinquent","type":"bool"},{"internalType":"uint32","name":"timeDelinquent","type":"uint32"},{"internalType":"uint16","name":"protocolFeeBips","type":"uint16"},{"internalType":"uint16","name":"annualInterestBips","type":"uint16"},{"internalType":"uint16","name":"reserveRatioBips","type":"uint16"},{"internalType":"uint112","name":"scaleFactor","type":"uint112"},{"internalType":"uint32","name":"lastInterestAccruedTimestamp","type":"uint32"}],"internalType":"struct MarketState","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"queueFullWithdrawal","outputs":[{"internalType":"uint32","name":"expiry","type":"uint32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"queueWithdrawal","outputs":[{"internalType":"uint32","name":"expiry","type":"uint32"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"repay","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"uint256","name":"maxBatches","type":"uint256"}],"name":"repayAndProcessUnpaidWithdrawalBatches","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"rescueTokens","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"reserveRatioBips","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"scaleFactor","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"scaledBalanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"scaledTotalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sentinel","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint16","name":"_annualInterestBips","type":"uint16"},{"internalType":"uint16","name":"_reserveRatioBips","type":"uint16"}],"name":"setAnnualInterestAndReserveRatioBips","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_maxTotalSupply","type":"uint256"}],"name":"setMaxTotalSupply","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"_protocolFeeBips","type":"uint16"}],"name":"setProtocolFeeBips","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sphereXEngine","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sphereXOperator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalAssets","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalDebts","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"updateState","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"withdrawableProtocolFees","outputs":[{"internalType":"uint128","name":"","type":"uint128"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"withdrawalBatchDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}],"conflicting_implementations":null,"certified":false,"additional_sources":[{"file_path":"src/libraries/MarketState.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport './MathUtils.sol';\nimport './SafeCastLib.sol';\nimport './FeeMath.sol';\n\nusing MarketStateLib for MarketState global;\nusing MarketStateLib for Account global;\nusing FeeMath for MarketState global;\n\nstruct MarketState {\n  bool isClosed;\n  uint128 maxTotalSupply;\n  uint128 accruedProtocolFees;\n  // Underlying assets reserved for withdrawals which have been paid\n  // by the borrower but not yet executed.\n  uint128 normalizedUnclaimedWithdrawals;\n  // Scaled token supply (divided by scaleFactor)\n  uint104 scaledTotalSupply;\n  // Scaled token amount in withdrawal batches that have not been\n  // paid by borrower yet.\n  uint104 scaledPendingWithdrawals;\n  uint32 pendingWithdrawalExpiry;\n  // Whether market is currently delinquent (liquidity under requirement)\n  bool isDelinquent;\n  // Seconds borrower has been delinquent\n  uint32 timeDelinquent;\n  // Fee charged to borrowers as a fraction of the annual interest rate\n  uint16 protocolFeeBips;\n  // Annual interest rate accrued to lenders, in basis points\n  uint16 annualInterestBips;\n  // Percentage of outstanding balance that must be held in liquid reserves\n  uint16 reserveRatioBips;\n  // Ratio between internal balances and underlying token amounts\n  uint112 scaleFactor;\n  uint32 lastInterestAccruedTimestamp;\n}\n\nstruct Account {\n  uint104 scaledBalance;\n}\n\nlibrary MarketStateLib {\n  using MathUtils for uint256;\n  using SafeCastLib for uint256;\n\n  /**\n   * @dev Returns the normalized total supply of the market.\n   */\n  function totalSupply(MarketState memory state) internal pure returns (uint256) {\n    return state.normalizeAmount(state.scaledTotalSupply);\n  }\n\n  /**\n   * @dev Returns the maximum amount of tokens that can be deposited without\n   *      reaching the maximum total supply.\n   */\n  function maximumDeposit(MarketState memory state) internal pure returns (uint256) {\n    return uint256(state.maxTotalSupply).satSub(state.totalSupply());\n  }\n\n  /**\n   * @dev Normalize an amount of scaled tokens using the current scale factor.\n   */\n  function normalizeAmount(\n    MarketState memory state,\n    uint256 amount\n  ) internal pure returns (uint256) {\n    return amount.rayMul(state.scaleFactor);\n  }\n\n  /**\n   * @dev Scale an amount of normalized tokens using the current scale factor.\n   */\n  function scaleAmount(MarketState memory state, uint256 amount) internal pure returns (uint256) {\n    return amount.rayDiv(state.scaleFactor);\n  }\n\n  /**\n   * @dev Collateralization requirement is:\n   *      - 100% of all pending (unpaid) withdrawals\n   *      - 100% of all unclaimed (paid) withdrawals\n   *      - reserve ratio times the outstanding debt (supply - pending withdrawals)\n   *      - accrued protocol fees\n   */\n  function liquidityRequired(\n    MarketState memory state\n  ) internal pure returns (uint256 _liquidityRequired) {\n    uint256 scaledWithdrawals = state.scaledPendingWithdrawals;\n    uint256 scaledRequiredReserves = (state.scaledTotalSupply - scaledWithdrawals).bipMul(\n      state.reserveRatioBips\n    ) + scaledWithdrawals;\n    return\n      state.normalizeAmount(scaledRequiredReserves) +\n      state.accruedProtocolFees +\n      state.normalizedUnclaimedWithdrawals;\n  }\n\n  /**\n   * @dev Returns the amount of underlying assets that can be withdrawn\n   *      for protocol fees. The only debts with higher priority are\n   *      processed withdrawals that have not been executed.\n   */\n  function withdrawableProtocolFees(\n    MarketState memory state,\n    uint256 totalAssets\n  ) internal pure returns (uint128) {\n    uint256 totalAvailableAssets = totalAssets - state.normalizedUnclaimedWithdrawals;\n    return uint128(MathUtils.min(totalAvailableAssets, state.accruedProtocolFees));\n  }\n\n  /**\n   * @dev Returns the amount of underlying assets that can be borrowed.\n   *\n   *      The borrower must maintain sufficient assets in the market to\n   *      cover 100% of pending withdrawals, 100% of previously processed\n   *      withdrawals (before they are executed), and the reserve ratio\n   *      times the outstanding debt (deposits not pending withdrawal).\n   *\n   *      Any underlying assets in the market above this amount can be borrowed.\n   */\n  function borrowableAssets(\n    MarketState memory state,\n    uint256 totalAssets\n  ) internal pure returns (uint256) {\n    return totalAssets.satSub(state.liquidityRequired());\n  }\n\n  function hasPendingExpiredBatch(MarketState memory state) internal view returns (bool result) {\n    uint256 expiry = state.pendingWithdrawalExpiry;\n    assembly {\n      // Equivalent to expiry > 0 && expiry < block.timestamp\n      result := and(gt(expiry, 0), gt(timestamp(), expiry))\n    }\n  }\n\n  function totalDebts(MarketState memory state) internal pure returns (uint256) {\n    return\n      state.normalizeAmount(state.scaledTotalSupply) +\n      state.normalizedUnclaimedWithdrawals +\n      state.accruedProtocolFees;\n  }\n}\n"},{"file_path":"src/IHooksFactory.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport './access/IHooks.sol';\nimport './interfaces/WildcatStructsAndEnums.sol';\n\nstruct HooksTemplate {\n  /// @dev Asset used to pay origination fee\n  address originationFeeAsset;\n  /// @dev Amount of `originationFeeAsset` paid to deploy a new market using\n  ///      an instance of this template.\n  uint80 originationFeeAmount;\n  /// @dev Basis points paid on interest for markets deployed using hooks\n  ///      based on this template\n  uint16 protocolFeeBips;\n  /// @dev Whether the template exists\n  bool exists;\n  /// @dev Whether the template is enabled\n  bool enabled;\n  /// @dev Index of the template address in the array of hooks templates\n  uint24 index;\n  /// @dev Address to pay origination and interest fees\n  address feeRecipient;\n  /// @dev Name of the template\n  string name;\n}\n\ninterface IHooksFactoryEventsAndErrors {\n  error FeeMismatch();\n  error NotApprovedBorrower();\n  error HooksTemplateNotFound();\n  error HooksTemplateNotAvailable();\n  error HooksTemplateAlreadyExists();\n  error DeploymentFailed();\n  error HooksInstanceNotFound();\n  error CallerNotArchControllerOwner();\n  error InvalidFeeConfiguration();\n  error SaltDoesNotContainSender();\n  error MarketAlreadyExists();\n  error HooksInstanceAlreadyExists();\n  error NameOrSymbolTooLong();\n  error AssetBlacklisted();\n  error SetProtocolFeeBipsFailed();\n\n  event HooksInstanceDeployed(address hooksInstance, address hooksTemplate);\n  event HooksTemplateAdded(\n    address hooksTemplate,\n    string name,\n    address feeRecipient,\n    address originationFeeAsset,\n    uint80 originationFeeAmount,\n    uint16 protocolFeeBips\n  );\n  event HooksTemplateDisabled(address hooksTemplate);\n  event HooksTemplateFeesUpdated(\n    address hooksTemplate,\n    address feeRecipient,\n    address originationFeeAsset,\n    uint80 originationFeeAmount,\n    uint16 protocolFeeBips\n  );\n\n  event MarketDeployed(\n    address indexed hooksTemplate,\n    address indexed market,\n    string name,\n    string symbol,\n    address asset,\n    uint256 maxTotalSupply,\n    uint256 annualInterestBips,\n    uint256 delinquencyFeeBips,\n    uint256 withdrawalBatchDuration,\n    uint256 reserveRatioBips,\n    uint256 delinquencyGracePeriod,\n    HooksConfig hooks\n  );\n}\n\ninterface IHooksFactory is IHooksFactoryEventsAndErrors {\n  function archController() external view returns (address);\n\n  function sanctionsSentinel() external view returns (address);\n\n  function marketInitCodeStorage() external view returns (address);\n\n  function marketInitCodeHash() external view returns (uint256);\n\n  /// @dev Set-up function to register the factory as a controller with the arch-controller.\n  ///      This enables the factory to register new markets.\n  function registerWithArchController() external;\n\n  function name() external view returns (string memory);\n\n  // ========================================================================== //\n  //                               Hooks Templates                              //\n  // ========================================================================== //\n\n  /// @dev Add a hooks template that stores the initcode for the template.\n  ///\n  ///      On success:\n  ///      - Emits `HooksTemplateAdded` on success.\n  ///      - Adds the template to the list of templates.\n  ///      - Creates `HooksTemplate` struct with the given parameters mapped to the template address.\n  ///\n  ///      Reverts if:\n  ///      - The caller is not the owner of the arch-controller.\n  ///      - The template already exists.\n  ///      - The fee settings are invalid.\n  function addHooksTemplate(\n    address hooksTemplate,\n    string calldata name,\n    address feeRecipient,\n    address originationFeeAsset,\n    uint80 originationFeeAmount,\n    uint16 protocolFeeBips\n  ) external;\n\n  /// @dev Update the fees for a hooks template.\n  ///\n  ///      On success:\n  ///      - Emits `HooksTemplateFeesUpdated` on success.\n  ///      - Updates the fees for the `HooksTemplate` struct mapped to the template address.\n  ///\n  ///      Reverts if:\n  ///      - The caller is not the owner of the arch-controller.\n  ///      - The template does not exist.\n  ///      - The fee settings are invalid.\n  function updateHooksTemplateFees(\n    address hooksTemplate,\n    address feeRecipient,\n    address originationFeeAsset,\n    uint80 originationFeeAmount,\n    uint16 protocolFeeBips\n  ) external;\n\n  /// @dev Disable a hooks template.\n  ///\n  ///      On success:\n  ///      - Emits `HooksTemplateDisabled` on success.\n  ///      - Disables the `HooksTemplate` struct mapped to the template address.\n  ///\n  ///      Reverts if:\n  ///      - The caller is not the owner of the arch-controller.\n  ///      - The template does not exist.\n  function disableHooksTemplate(address hooksTemplate) external;\n\n  /// @dev Get the name and fee configuration for an approved hooks template.\n  function getHooksTemplateDetails(\n    address hooksTemplate\n  ) external view returns (HooksTemplate memory);\n\n  /// @dev Check if a hooks template is approved.\n  function isHooksTemplate(address hooksTemplate) external view returns (bool);\n\n  /// @dev Get the list of approved hooks templates.\n  function getHooksTemplates() external view returns (address[] memory);\n\n  function getHooksTemplates(\n    uint256 start,\n    uint256 end\n  ) external view returns (address[] memory arr);\n\n  function getHooksTemplatesCount() external view returns (uint256);\n\n  function getMarketsForHooksTemplate(\n    address hooksTemplate\n  ) external view returns (address[] memory);\n\n  function getMarketsForHooksTemplate(\n    address hooksTemplate,\n    uint256 start,\n    uint256 end\n  ) external view returns (address[] memory arr);\n\n  function getMarketsForHooksTemplateCount(address hooksTemplate) external view returns (uint256);\n\n  // ========================================================================== //\n  //                               Hooks Instances                              //\n  // ========================================================================== //\n\n  /// @dev Deploy a hooks instance for an approved template with constructor args.\n  ///\n  ///      On success:\n  ///      - Emits `HooksInstanceDeployed`.\n  ///      - Deploys a new hooks instance with the given templates and constructor args.\n  ///      - Maps the hooks instance to the template address.\n  ///\n  ///      Reverts if:\n  ///      - The caller is not an approved borrower.\n  ///      - The template does not exist.\n  ///      - The template is not enabled.\n  ///      - The deployment fails.\n  function deployHooksInstance(\n    address hooksTemplate,\n    bytes calldata constructorArgs\n  ) external returns (address hooksDeployment);\n\n  function getHooksInstancesForBorrower(address borrower) external view returns (address[] memory);\n\n  function getHooksInstancesCountForBorrower(address borrower) external view returns (uint256);\n\n  /// @dev Check if a hooks instance was deployed by the factory.\n  function isHooksInstance(address hooks) external view returns (bool);\n\n  /// @dev Get the template that was used to deploy a hooks instance.\n  function getHooksTemplateForInstance(address hooks) external view returns (address);\n\n  // ========================================================================== //\n  //                                   Markets                                  //\n  // ========================================================================== //\n  function getMarketsForHooksInstance(\n    address hooksInstance\n  ) external view returns (address[] memory);\n\n  function getMarketsForHooksInstance(\n    address hooksInstance,\n    uint256 start,\n    uint256 len\n  ) external view returns (address[] memory arr);\n\n  function getMarketsForHooksInstanceCount(address hooksInstance) external view returns (uint256);\n\n  /// @dev Get the temporarily stored market parameters for a market that is\n  ///      currently being deployed.\n  function getMarketParameters() external view returns (MarketParameters memory parameters);\n\n  /// @dev Deploy a market with an existing hooks deployment (in `parameters.hooks`)\n  ///\n  ///      On success:\n  ///      - Pays the origination fee (if applicable).\n  ///      - Calls `onDeployMarket` on the hooks contract.\n  ///      - Deploys a new market with the given parameters.\n  ///      - Emits `MarketDeployed`.\n  ///\n  ///      Reverts if:\n  ///      - The caller is not an approved borrower.\n  ///      - The hooks instance does not exist.\n  ///      - Payment of origination fee fails.\n  ///      - The deployment fails.\n  ///      - The call to `onDeployMarket` fails.\n  ///      - `originationFeeAsset` does not match the hook template's\n  ///      - `originationFeeAmount` does not match the hook template's\n  function deployMarket(\n    DeployMarketInputs calldata parameters,\n    bytes calldata hooksData,\n    bytes32 salt,\n    address originationFeeAsset,\n    uint256 originationFeeAmount\n  ) external returns (address market);\n\n  /// @dev Deploy a hooks instance for an approved template,then deploy a new market with that\n  ///      instance as its hooks contract.\n  ///      Will call `onCreateMarket` on `parameters.hooks`.\n  function deployMarketAndHooks(\n    address hooksTemplate,\n    bytes calldata hooksConstructorArgs,\n    DeployMarketInputs calldata parameters,\n    bytes calldata hooksData,\n    bytes32 salt,\n    address originationFeeAsset,\n    uint256 originationFeeAmount\n  ) external returns (address market, address hooks);\n\n  function computeMarketAddress(bytes32 salt) external view returns (address);\n\n  function pushProtocolFeeBipsUpdates(\n    address hooksTemplate,\n    uint marketStartIndex,\n    uint marketEndIndex\n  ) external;\n\n  function pushProtocolFeeBipsUpdates(address hooksTemplate) external;\n}\n"},{"file_path":"src/interfaces/IERC20.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\ninterface IERC20 {\n  event Transfer(address indexed from, address indexed to, uint256 value);\n  event Approval(address indexed owner, address indexed spender, uint256 value);\n\n  function totalSupply() external view returns (uint256);\n\n  function balanceOf(address account) external view returns (uint256);\n\n  function transfer(address recipient, uint256 amount) external returns (bool);\n\n  function allowance(address owner, address spender) external view returns (uint256);\n\n  function approve(address spender, uint256 amount) external returns (bool);\n\n  function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n\n  function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n\n  function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n  function name() external view returns (string memory);\n\n  function symbol() external view returns (string memory);\n\n  function decimals() external view returns (uint8);\n}\n"},{"file_path":"src/spherex/ISphereXEngine.sol","source_code":"// SPDX-License-Identifier: UNLICENSED\n// (c) SphereX 2023 Terms&Conditions\npragma solidity ^0.8.20;\n\n/// @dev this struct is used to reduce the stack usage of the modifiers.\nstruct ModifierLocals {\n  bytes32[] storageSlots;\n  bytes32[] valuesBefore;\n  uint256 gas;\n  address engine;\n}\n\n/// @title Interface for SphereXEngine - definitions of core functionality\n/// @author SphereX Technologies ltd\n/// @notice This interface is imported by SphereXProtected, so that SphereXProtected can call functions from SphereXEngine\n/// @dev Full docs of these functions can be found in SphereXEngine\ninterface ISphereXEngine {\n  function sphereXValidatePre(\n    int256 num,\n    address sender,\n    bytes calldata data\n  ) external returns (bytes32[] memory);\n\n  function sphereXValidatePost(\n    int256 num,\n    uint256 gas,\n    bytes32[] calldata valuesBefore,\n    bytes32[] calldata valuesAfter\n  ) external;\n\n  function sphereXValidateInternalPre(int256 num) external returns (bytes32[] memory);\n\n  function sphereXValidateInternalPost(\n    int256 num,\n    uint256 gas,\n    bytes32[] calldata valuesBefore,\n    bytes32[] calldata valuesAfter\n  ) external;\n\n  function addAllowedSenderOnChain(address sender) external;\n\n  /// This function is taken as is from OZ IERC165, we don't inherit from OZ\n  /// to avoid collisions with the customer OZ version.\n  /// @dev Returns true if this contract implements the interface defined by\n  /// `interfaceId`. See the corresponding\n  /// https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n  /// to learn more about how these ids are created.\n  /// This function call must use less than 30 000 gas.\n  function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},{"file_path":"src/libraries/MarketErrors.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nuint256 constant MaxSupplyExceeded_ErrorSelector = 0x8a164f63;\n\n/// @dev Equivalent to `revert MaxSupplyExceeded()`\nfunction revert_MaxSupplyExceeded() pure {\n  assembly {\n    mstore(0, 0x8a164f63)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant CapacityChangeOnClosedMarket_ErrorSelector = 0x81b21078;\n\n/// @dev Equivalent to `revert CapacityChangeOnClosedMarket()`\nfunction revert_CapacityChangeOnClosedMarket() pure {\n  assembly {\n    mstore(0, 0x81b21078)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant AprChangeOnClosedMarket_ErrorSelector = 0xb9de88a2;\n\n/// @dev Equivalent to `revert AprChangeOnClosedMarket()`\nfunction revert_AprChangeOnClosedMarket() pure {\n  assembly {\n    mstore(0, 0xb9de88a2)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant MarketAlreadyClosed_ErrorSelector = 0x449e5f50;\n\n/// @dev Equivalent to `revert MarketAlreadyClosed()`\nfunction revert_MarketAlreadyClosed() pure {\n  assembly {\n    mstore(0, 0x449e5f50)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NotApprovedBorrower_ErrorSelector = 0x02171e6a;\n\n/// @dev Equivalent to `revert NotApprovedBorrower()`\nfunction revert_NotApprovedBorrower() pure {\n  assembly {\n    mstore(0, 0x02171e6a)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NotApprovedLender_ErrorSelector = 0xe50a45ce;\n\n/// @dev Equivalent to `revert NotApprovedLender()`\nfunction revert_NotApprovedLender() pure {\n  assembly {\n    mstore(0, 0xe50a45ce)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant BadLaunchCode_ErrorSelector = 0xa97ab167;\n\n/// @dev Equivalent to `revert BadLaunchCode()`\nfunction revert_BadLaunchCode() pure {\n  assembly {\n    mstore(0, 0xa97ab167)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant ReserveRatioBipsTooHigh_ErrorSelector = 0x8ec83073;\n\n/// @dev Equivalent to `revert ReserveRatioBipsTooHigh()`\nfunction revert_ReserveRatioBipsTooHigh() pure {\n  assembly {\n    mstore(0, 0x8ec83073)\n    revert(0x1c, 0x04)\n  }\n}\n\n/* \ncode size: 25634\ninitcode size: 28024\n\nerrors: -48 runtime, -48 initcode\n*/\nuint256 constant AnnualInterestBipsTooHigh_ErrorSelector = 0xcf1f916f;\n\n/// @dev Equivalent to `revert ReserveRatioBipsTooHigh()`\nfunction revert_AnnualInterestBipsTooHigh() pure {\n  assembly {\n    mstore(0, 0xcf1f916f)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant AccountBlocked_ErrorSelector = 0x6bc671fd;\n\n/// @dev Equivalent to `revert AccountBlocked()`\nfunction revert_AccountBlocked() pure {\n  assembly {\n    mstore(0, 0x6bc671fd)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant BorrowAmountTooHigh_ErrorSelector = 0x119fe6e3;\n\n/// @dev Equivalent to `revert BorrowAmountTooHigh()`\nfunction revert_BorrowAmountTooHigh() pure {\n  assembly {\n    mstore(0, 0x119fe6e3)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant BadRescueAsset_ErrorSelector = 0x11530cde;\n\n/// @dev Equivalent to `revert BadRescueAsset()`\nfunction revert_BadRescueAsset() pure {\n  assembly {\n    mstore(0, 0x11530cde)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant InsufficientReservesForFeeWithdrawal_ErrorSelector = 0xf784cfa4;\n\n/// @dev Equivalent to `revert InsufficientReservesForFeeWithdrawal()`\nfunction revert_InsufficientReservesForFeeWithdrawal() pure {\n  assembly {\n    mstore(0, 0xf784cfa4)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant WithdrawalBatchNotExpired_ErrorSelector = 0x2561b880;\n\n/// @dev Equivalent to `revert WithdrawalBatchNotExpired()`\nfunction revert_WithdrawalBatchNotExpired() pure {\n  assembly {\n    mstore(0, 0x2561b880)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullMintAmount_ErrorSelector = 0xe4aa5055;\n\n/// @dev Equivalent to `revert NullMintAmount()`\nfunction revert_NullMintAmount() pure {\n  assembly {\n    mstore(0, 0xe4aa5055)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullBurnAmount_ErrorSelector = 0xd61c50f8;\n\n/// @dev Equivalent to `revert NullBurnAmount()`\nfunction revert_NullBurnAmount() pure {\n  assembly {\n    mstore(0, 0xd61c50f8)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullFeeAmount_ErrorSelector = 0x45c835cb;\n\n/// @dev Equivalent to `revert NullFeeAmount()`\nfunction revert_NullFeeAmount() pure {\n  assembly {\n    mstore(0, 0x45c835cb)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullTransferAmount_ErrorSelector = 0xddee9b30;\n\n/// @dev Equivalent to `revert NullTransferAmount()`\nfunction revert_NullTransferAmount() pure {\n  assembly {\n    mstore(0, 0xddee9b30)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullWithdrawalAmount_ErrorSelector = 0x186334fe;\n\n/// @dev Equivalent to `revert NullWithdrawalAmount()`\nfunction revert_NullWithdrawalAmount() pure {\n  assembly {\n    mstore(0, 0x186334fe)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullRepayAmount_ErrorSelector = 0x7e082088;\n\n/// @dev Equivalent to `revert NullRepayAmount()`\nfunction revert_NullRepayAmount() pure {\n  assembly {\n    mstore(0, 0x7e082088)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NullBuyBackAmount_ErrorSelector = 0x50394120;\n\n/// @dev Equivalent to `revert NullBuyBackAmount()`\nfunction revert_NullBuyBackAmount() pure {\n  assembly {\n    mstore(0, 0x50394120)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant DepositToClosedMarket_ErrorSelector = 0x22d7c043;\n\n/// @dev Equivalent to `revert DepositToClosedMarket()`\nfunction revert_DepositToClosedMarket() pure {\n  assembly {\n    mstore(0, 0x22d7c043)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant RepayToClosedMarket_ErrorSelector = 0x61d1bc8f;\n\n/// @dev Equivalent to `revert RepayToClosedMarket()`\nfunction revert_RepayToClosedMarket() pure {\n  assembly {\n    mstore(0, 0x61d1bc8f)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant BuyBackOnDelinquentMarket_Selector = 0x1707a7b7;\n\n/// @dev Equivalent to `revert BuyBackOnDelinquentMarket()`\nfunction revert_BuyBackOnDelinquentMarket() pure {\n  assembly {\n    mstore(0, 0x1707a7b7)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant BorrowWhileSanctioned_ErrorSelector = 0x4a1c13a9;\n\n/// @dev Equivalent to `revert BorrowWhileSanctioned()`\nfunction revert_BorrowWhileSanctioned() pure {\n  assembly {\n    mstore(0, 0x4a1c13a9)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant BorrowFromClosedMarket_ErrorSelector = 0xd0242b28;\n\n/// @dev Equivalent to `revert BorrowFromClosedMarket()`\nfunction revert_BorrowFromClosedMarket() pure {\n  assembly {\n    mstore(0, 0xd0242b28)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant CloseMarketWithUnpaidWithdrawals_ErrorSelector = 0x4d790997;\n\n/// @dev Equivalent to `revert CloseMarketWithUnpaidWithdrawals()`\nfunction revert_CloseMarketWithUnpaidWithdrawals() pure {\n  assembly {\n    mstore(0, 0x4d790997)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant InsufficientReservesForNewLiquidityRatio_ErrorSelector = 0x253ecbb9;\n\n/// @dev Equivalent to `revert InsufficientReservesForNewLiquidityRatio()`\nfunction revert_InsufficientReservesForNewLiquidityRatio() pure {\n  assembly {\n    mstore(0, 0x253ecbb9)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant InsufficientReservesForOldLiquidityRatio_ErrorSelector = 0x0a68e5bf;\n\n/// @dev Equivalent to `revert InsufficientReservesForOldLiquidityRatio()`\nfunction revert_InsufficientReservesForOldLiquidityRatio() pure {\n  assembly {\n    mstore(0, 0x0a68e5bf)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant InvalidArrayLength_ErrorSelector = 0x9d89020a;\n\n/// @dev Equivalent to `revert InvalidArrayLength()`\nfunction revert_InvalidArrayLength() pure {\n  assembly {\n    mstore(0, 0x9d89020a)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant ProtocolFeeTooHigh_ErrorSelector = 0x499fddb1;\n\n/// @dev Equivalent to `revert ProtocolFeeTooHigh()`\nfunction revert_ProtocolFeeTooHigh() pure {\n  assembly {\n    mstore(0, 0x499fddb1)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant ProtocolFeeChangeOnClosedMarket_ErrorSelector = 0x37f1a75f;\n\n/// @dev Equivalent to `revert ProtocolFeeChangeOnClosedMarket()`\nfunction revert_ProtocolFeeChangeOnClosedMarket() pure {\n  assembly {\n    mstore(0, 0x37f1a75f)\n    revert(0x1c, 0x04)\n  }\n}\n\nuint256 constant NotFactory_ErrorSelector = 0x32cc7236;\n\nfunction revert_NotFactory() pure {\n  assembly {\n    mstore(0, 0x32cc7236)\n    revert(0x1c, 0x04)\n  }\n}\n"},{"file_path":"src/libraries/Errors.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nuint256 constant Panic_CompilerPanic = 0x00;\nuint256 constant Panic_AssertFalse = 0x01;\nuint256 constant Panic_Arithmetic = 0x11;\nuint256 constant Panic_DivideByZero = 0x12;\nuint256 constant Panic_InvalidEnumValue = 0x21;\nuint256 constant Panic_InvalidStorageByteArray = 0x22;\nuint256 constant Panic_EmptyArrayPop = 0x31;\nuint256 constant Panic_ArrayOutOfBounds = 0x32;\nuint256 constant Panic_MemoryTooLarge = 0x41;\nuint256 constant Panic_UninitializedFunctionPointer = 0x51;\n\nuint256 constant Panic_ErrorSelector = 0x4e487b71;\nuint256 constant Panic_ErrorCodePointer = 0x20;\nuint256 constant Panic_ErrorLength = 0x24;\nuint256 constant Error_SelectorPointer = 0x1c;\n\n/**\n * @dev Reverts with the given error selector.\n * @param errorSelector The left-aligned error selector.\n */\nfunction revertWithSelector(bytes4 errorSelector) pure {\n  assembly {\n    mstore(0, errorSelector)\n    revert(0, 4)\n  }\n}\n\n/**\n * @dev Reverts with the given error selector.\n * @param errorSelector The left-padded error selector.\n */\nfunction revertWithSelector(uint256 errorSelector) pure {\n  assembly {\n    mstore(0, errorSelector)\n    revert(Error_SelectorPointer, 4)\n  }\n}\n\n/**\n * @dev Reverts with the given error selector and argument.\n * @param errorSelector The left-aligned error selector.\n * @param argument The argument to the error.\n */\nfunction revertWithSelectorAndArgument(bytes4 errorSelector, uint256 argument) pure {\n  assembly {\n    mstore(0, errorSelector)\n    mstore(4, argument)\n    revert(0, 0x24)\n  }\n}\n\n/**\n * @dev Reverts with the given error selector and argument.\n * @param errorSelector The left-padded error selector.\n * @param argument The argument to the error.\n */\nfunction revertWithSelectorAndArgument(uint256 errorSelector, uint256 argument) pure {\n  assembly {\n    mstore(0, errorSelector)\n    mstore(0x20, argument)\n    revert(Error_SelectorPointer, 0x24)\n  }\n}\n"},{"file_path":"src/interfaces/IWildcatSanctionsSentinel.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\ninterface IWildcatSanctionsSentinel {\n  event NewSanctionsEscrow(\n    address indexed borrower,\n    address indexed account,\n    address indexed asset\n  );\n\n  event SanctionOverride(address indexed borrower, address indexed account);\n\n  event SanctionOverrideRemoved(address indexed borrower, address indexed account);\n\n  struct TmpEscrowParams {\n    address borrower;\n    address account;\n    address asset;\n  }\n\n  function WildcatSanctionsEscrowInitcodeHash() external pure returns (bytes32);\n\n  // Returns immutable sanctions list contract\n  function chainalysisSanctionsList() external view returns (address);\n\n  // Returns immutable arch-controller\n  function archController() external view returns (address);\n\n  // Returns temporary escrow params\n  function tmpEscrowParams()\n    external\n    view\n    returns (address borrower, address account, address asset);\n\n  // Returns result of `chainalysisSanctionsList().isSanctioned(account)`\n  function isFlaggedByChainalysis(address account) external view returns (bool);\n\n  // Returns result of `chainalysisSanctionsList().isSanctioned(account)`\n  // if borrower has not overridden the status of `account`\n  function isSanctioned(address borrower, address account) external view returns (bool);\n\n  // Returns boolean indicating whether `borrower` has overridden the\n  // sanction status of `account`\n  function sanctionOverrides(address borrower, address account) external view returns (bool);\n\n  function overrideSanction(address account) external;\n\n  function removeSanctionOverride(address account) external;\n\n  // Returns create2 address of sanctions escrow contract for\n  // combination of `borrower,account,asset`\n  function getEscrowAddress(\n    address borrower,\n    address account,\n    address asset\n  ) external view returns (address escrowContract);\n\n  /**\n   * @dev Returns a create2 deployment of WildcatSanctionsEscrow unique to each\n   *      combination of `account,borrower,asset`. If the contract is already\n   *      deployed, returns the existing address.\n   *\n   *      Emits `NewSanctionsEscrow(borrower, account, asset)` if a new contract\n   *      is deployed.\n   *\n   *      The sanctions escrow contract is used to hold assets until either the\n   *      sanctioned status is lifted or the assets are released by the borrower.\n   */\n  function createEscrow(\n    address borrower,\n    address account,\n    address asset\n  ) external returns (address escrowContract);\n}\n"},{"file_path":"src/interfaces/IWildcatSanctionsEscrow.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\ninterface IWildcatSanctionsEscrow {\n  event EscrowReleased(address indexed account, address indexed asset, uint256 amount);\n\n  error CanNotReleaseEscrow();\n\n  function sentinel() external view returns (address);\n\n  function borrower() external view returns (address);\n\n  function account() external view returns (address);\n\n  function balance() external view returns (uint256);\n\n  function canReleaseEscrow() external view returns (bool);\n\n  function escrowedAsset() external view returns (address token, uint256 amount);\n\n  function releaseEscrow() external;\n}\n"},{"file_path":"src/libraries/MarketEvents.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nuint256 constant InterestAndFeesAccrued_abi_head_size = 0xc0;\nuint256 constant InterestAndFeesAccrued_toTimestamp_offset = 0x20;\nuint256 constant InterestAndFeesAccrued_scaleFactor_offset = 0x40;\nuint256 constant InterestAndFeesAccrued_baseInterestRay_offset = 0x60;\nuint256 constant InterestAndFeesAccrued_delinquencyFeeRay_offset = 0x80;\nuint256 constant InterestAndFeesAccrued_protocolFees_offset = 0xa0;\n\nfunction emit_Transfer(address from, address to, uint256 value) {\n  assembly {\n    mstore(0, value)\n    log3(0, 0x20, 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef, from, to)\n  }\n}\n\nfunction emit_Approval(address owner, address spender, uint256 value) {\n  assembly {\n    mstore(0, value)\n    log3(\n      0,\n      0x20,\n      0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925,\n      owner,\n      spender\n    )\n  }\n}\n\nfunction emit_MaxTotalSupplyUpdated(uint256 assets) {\n  assembly {\n    mstore(0, assets)\n    log1(0, 0x20, 0xf2672935fc79f5237559e2e2999dbe743bf65430894ac2b37666890e7c69e1af)\n  }\n}\n\nfunction emit_ProtocolFeeBipsUpdated(uint256 protocolFeeBips) {\n  assembly {\n    mstore(0, protocolFeeBips)\n    log1(0, 0x20, 0x4b34705283cdb9398d0e50b216b8fb424c6d4def5db9bfadc661ee3adc6076ee)\n  }\n}\n\nfunction emit_AnnualInterestBipsUpdated(uint256 annualInterestBipsUpdated) {\n  assembly {\n    mstore(0, annualInterestBipsUpdated)\n    log1(0, 0x20, 0xff7b6c8be373823323d3c5d99f5d027dd409dce5db54eae511bbdd5546b75037)\n  }\n}\n\nfunction emit_ReserveRatioBipsUpdated(uint256 reserveRatioBipsUpdated) {\n  assembly {\n    mstore(0, reserveRatioBipsUpdated)\n    log1(0, 0x20, 0x72877a153052500f5edbb2f9da96a0f45d671d4b4555fdf8628a709dc4eab43a)\n  }\n}\n\nfunction emit_SanctionedAccountAssetsSentToEscrow(address account, address escrow, uint256 amount) {\n  assembly {\n    mstore(0, escrow)\n    mstore(0x20, amount)\n    log2(0, 0x40, 0x571e706c2f09ae0632313e5f3ae89fffdedfc370a2ea59a07fb0d8091147645b, account)\n  }\n}\n\nfunction emit_SanctionedAccountAssetsQueuedForWithdrawal(\n  address account,\n  uint32 expiry,\n  uint256 scaledAmount,\n  uint256 normalizedAmount\n) {\n  assembly {\n    let freePointer := mload(0x40)\n    mstore(0, expiry)\n    mstore(0x20, scaledAmount)\n    mstore(0x40, normalizedAmount)\n    log2(0, 0x60, 0xe12b220b92469ae28fb0d79de531f94161431be9f073b96b8aad3effb88be6fa, account)\n    mstore(0x40, freePointer)\n  }\n}\n\nfunction emit_Deposit(address account, uint256 assetAmount, uint256 scaledAmount) {\n  assembly {\n    mstore(0, assetAmount)\n    mstore(0x20, scaledAmount)\n    log2(0, 0x40, 0x90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a15, account)\n  }\n}\n\nfunction emit_Borrow(uint256 assetAmount) {\n  assembly {\n    mstore(0, assetAmount)\n    log1(0, 0x20, 0xb848ae6b1253b6cb77e81464128ce8bd94d3d524fea54e801e0da869784dca33)\n  }\n}\n\nfunction emit_DebtRepaid(address from, uint256 assetAmount) {\n  assembly {\n    mstore(0, assetAmount)\n    log2(0, 0x20, 0xe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa6, from)\n  }\n}\n\nfunction emit_MarketClosed(uint256 _timestamp) {\n  assembly {\n    mstore(0, _timestamp)\n    log1(0, 0x20, 0x9dc30b8eda31a6a144e092e5de600955523a6a925cc15cc1d1b9b4872cfa6155)\n  }\n}\n\nfunction emit_FeesCollected(uint256 assets) {\n  assembly {\n    mstore(0, assets)\n    log1(0, 0x20, 0x860c0aa5520013080c2f65981705fcdea474d9f7c3daf954656ed5e65d692d1f)\n  }\n}\n\nfunction emit_StateUpdated(uint256 scaleFactor, bool isDelinquent) {\n  assembly {\n    mstore(0, scaleFactor)\n    mstore(0x20, isDelinquent)\n    log1(0, 0x40, 0x9385f9ff65bcd2fb81cece54b27d4ec7376795fc4dcff686e370e347b0ed86c0)\n  }\n}\n\nfunction emit_InterestAndFeesAccrued(\n  uint256 fromTimestamp,\n  uint256 toTimestamp,\n  uint256 scaleFactor,\n  uint256 baseInterestRay,\n  uint256 delinquencyFeeRay,\n  uint256 protocolFees\n) {\n  assembly {\n    let dst := mload(0x40)\n    /// Copy fromTimestamp\n    mstore(dst, fromTimestamp)\n    /// Copy toTimestamp\n    mstore(add(dst, InterestAndFeesAccrued_toTimestamp_offset), toTimestamp)\n    /// Copy scaleFactor\n    mstore(add(dst, InterestAndFeesAccrued_scaleFactor_offset), scaleFactor)\n    /// Copy baseInterestRay\n    mstore(add(dst, InterestAndFeesAccrued_baseInterestRay_offset), baseInterestRay)\n    /// Copy delinquencyFeeRay\n    mstore(add(dst, InterestAndFeesAccrued_delinquencyFeeRay_offset), delinquencyFeeRay)\n    /// Copy protocolFees\n    mstore(add(dst, InterestAndFeesAccrued_protocolFees_offset), protocolFees)\n    log1(\n      dst,\n      InterestAndFeesAccrued_abi_head_size,\n      0x18247a393d0531b65fbd94f5e78bc5639801a4efda62ae7b43533c4442116c3a\n    )\n  }\n}\n\nfunction emit_WithdrawalBatchExpired(\n  uint256 expiry,\n  uint256 scaledTotalAmount,\n  uint256 scaledAmountBurned,\n  uint256 normalizedAmountPaid\n) {\n  assembly {\n    let freePointer := mload(0x40)\n    mstore(0, scaledTotalAmount)\n    mstore(0x20, scaledAmountBurned)\n    mstore(0x40, normalizedAmountPaid)\n    log2(0, 0x60, 0x9262dc39b47cad3a0512e4c08dda248cb345e7163058f300bc63f56bda288b6e, expiry)\n    mstore(0x40, freePointer)\n  }\n}\n\nfunction emit_WithdrawalBatchCreated(uint256 expiry) {\n  assembly {\n    log2(0, 0x00, 0x5c9a946d3041134198ebefcd814de7748def6576efd3d1b48f48193e183e89ef, expiry)\n  }\n}\n\nfunction emit_WithdrawalBatchClosed(uint256 expiry) {\n  assembly {\n    log2(0, 0x00, 0xcbdf25bf6e096dd9030d89bb2ba2e3e7adb82d25a233c3ca3d92e9f098b74e55, expiry)\n  }\n}\n\nfunction emit_WithdrawalBatchPayment(\n  uint256 expiry,\n  uint256 scaledAmountBurned,\n  uint256 normalizedAmountPaid\n) {\n  assembly {\n    mstore(0, scaledAmountBurned)\n    mstore(0x20, normalizedAmountPaid)\n    log2(0, 0x40, 0x5272034725119f19d7236de4129fdb5093f0dcb80282ca5edbd587df91d2bd89, expiry)\n  }\n}\n\nfunction emit_WithdrawalQueued(\n  uint256 expiry,\n  address account,\n  uint256 scaledAmount,\n  uint256 normalizedAmount\n) {\n  assembly {\n    mstore(0, scaledAmount)\n    mstore(0x20, normalizedAmount)\n    log3(\n      0,\n      0x40,\n      0xecc966b282a372469fa4d3e497c2ac17983c3eaed03f3f17c9acf4b15591663e,\n      expiry,\n      account\n    )\n  }\n}\n\nfunction emit_WithdrawalExecuted(uint256 expiry, address account, uint256 normalizedAmount) {\n  assembly {\n    mstore(0, normalizedAmount)\n    log3(\n      0,\n      0x20,\n      0xd6cddb3d69146e96ebc2c87b1b3dd0b20ee2d3b0eadf134e011afb434a3e56e6,\n      expiry,\n      account\n    )\n  }\n}\n\nfunction emit_SanctionedAccountWithdrawalSentToEscrow(\n  address account,\n  address escrow,\n  uint32 expiry,\n  uint256 amount\n) {\n  assembly {\n    let freePointer := mload(0x40)\n    mstore(0, escrow)\n    mstore(0x20, expiry)\n    mstore(0x40, amount)\n    log2(0, 0x60, 0x0d0843a0fcb8b83f625aafb6e42f234ac48c6728b207d52d97cfa8fbd34d498f, account)\n    mstore(0x40, freePointer)\n  }\n}\n"},{"file_path":"src/libraries/FeeMath.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport './MathUtils.sol';\nimport './SafeCastLib.sol';\nimport './MarketState.sol';\n\nusing SafeCastLib for uint256;\nusing MathUtils for uint256;\n\nlibrary FeeMath {\n  /**\n   * @dev Function to calculate the interest accumulated using a linear interest rate formula\n   *\n   * @param rateBip The interest rate, in bips\n   * @param timeDelta The time elapsed since the last interest accrual\n   * @return result The interest rate linearly accumulated during the timeDelta, in ray\n   */\n  function calculateLinearInterestFromBips(\n    uint256 rateBip,\n    uint256 timeDelta\n  ) internal pure returns (uint256 result) {\n    uint256 rate = rateBip.bipToRay();\n    uint256 accumulatedInterestRay = rate * timeDelta;\n    unchecked {\n      return accumulatedInterestRay / SECONDS_IN_365_DAYS;\n    }\n  }\n\n  function calculateBaseInterest(\n    MarketState memory state,\n    uint256 timestamp\n  ) internal pure returns (uint256 baseInterestRay) {\n    baseInterestRay = MathUtils.calculateLinearInterestFromBips(\n      state.annualInterestBips,\n      timestamp - state.lastInterestAccruedTimestamp\n    );\n  }\n\n  function applyProtocolFee(\n    MarketState memory state,\n    uint256 baseInterestRay\n  ) internal pure returns (uint256 protocolFee) {\n    // Protocol fee is charged in addition to the interest paid to lenders.\n    uint256 protocolFeeRay = uint(state.protocolFeeBips).bipMul(baseInterestRay);\n    protocolFee = uint256(state.scaledTotalSupply).rayMul(\n      uint256(state.scaleFactor).rayMul(protocolFeeRay)\n    );\n    state.accruedProtocolFees = (state.accruedProtocolFees + protocolFee).toUint128();\n  }\n\n  function updateDelinquency(\n    MarketState memory state,\n    uint256 timestamp,\n    uint256 delinquencyFeeBips,\n    uint256 delinquencyGracePeriod\n  ) internal pure returns (uint256 delinquencyFeeRay) {\n    // Calculate the number of seconds the borrower spent in penalized\n    // delinquency since the last update.\n    uint256 timeWithPenalty = updateTimeDelinquentAndGetPenaltyTime(\n      state,\n      delinquencyGracePeriod,\n      timestamp - state.lastInterestAccruedTimestamp\n    );\n\n    if (timeWithPenalty > 0) {\n      // Calculate penalty fees on the interest accrued.\n      delinquencyFeeRay = calculateLinearInterestFromBips(delinquencyFeeBips, timeWithPenalty);\n    }\n  }\n\n  /**\n   * @notice  Calculate the number of seconds that the market has been in\n   *          penalized delinquency since the last update, and update\n   *          `timeDelinquent` in state.\n   *\n   * @dev When `isDelinquent`, equivalent to:\n   *        max(0, timeDelta - max(0, delinquencyGracePeriod - previousTimeDelinquent))\n   *      When `!isDelinquent`, equivalent to:\n   *        min(timeDelta, max(0, previousTimeDelinquent - delinquencyGracePeriod))\n   *\n   * @param state Encoded state parameters\n   * @param delinquencyGracePeriod Seconds in delinquency before penalties apply\n   * @param timeDelta Seconds since the last update\n   * @param `timeWithPenalty` Number of seconds since the last update where\n   *        the market was in delinquency outside of the grace period.\n   */\n  function updateTimeDelinquentAndGetPenaltyTime(\n    MarketState memory state,\n    uint256 delinquencyGracePeriod,\n    uint256 timeDelta\n  ) internal pure returns (uint256 /* timeWithPenalty */) {\n    // Seconds in delinquency at last update\n    uint256 previousTimeDelinquent = state.timeDelinquent;\n\n    if (state.isDelinquent) {\n      // Since the borrower is still delinquent, increase the total\n      // time in delinquency by the time elapsed.\n      state.timeDelinquent = (previousTimeDelinquent + timeDelta).toUint32();\n\n      // Calculate the number of seconds the borrower had remaining\n      // in the grace period.\n      uint256 secondsRemainingWithoutPenalty = delinquencyGracePeriod.satSub(\n        previousTimeDelinquent\n      );\n\n      // Penalties apply for the number of seconds the market spent in\n      // delinquency outside of the grace period since the last update.\n      return timeDelta.satSub(secondsRemainingWithoutPenalty);\n    }\n\n    // Reduce the total time in delinquency by the time elapsed, stopping\n    // when it reaches zero.\n    state.timeDelinquent = previousTimeDelinquent.satSub(timeDelta).toUint32();\n\n    // Calculate the number of seconds the old timeDelinquent had remaining\n    // outside the grace period, or zero if it was already in the grace period.\n    uint256 secondsRemainingWithPenalty = previousTimeDelinquent.satSub(delinquencyGracePeriod);\n\n    // Only apply penalties for the remaining time outside of the grace period.\n    return MathUtils.min(secondsRemainingWithPenalty, timeDelta);\n  }\n\n  /**\n   * @dev Calculates interest and delinquency/protocol fees accrued since last state update\n   *      and applies it to cached state, returning the rates for base interest and delinquency\n   *      fees and the normalized amount of protocol fees accrued.\n   *\n   *      Takes `timestamp` as input to allow separate calculation of interest\n   *      before and after withdrawal batch expiry.\n   *\n   * @param state Market scale parameters\n   * @param delinquencyFeeBips Delinquency fee rate (in bips)\n   * @param delinquencyGracePeriod Grace period (in seconds) before delinquency fees apply\n   * @param timestamp Time to calculate interest and fees accrued until\n   * @return baseInterestRay Interest accrued to lenders (ray)\n   * @return delinquencyFeeRay Penalty fee incurred by borrower for delinquency (ray).\n   * @return protocolFee Protocol fee charged on interest (normalized token amount).\n   */\n  function updateScaleFactorAndFees(\n    MarketState memory state,\n    uint256 delinquencyFeeBips,\n    uint256 delinquencyGracePeriod,\n    uint256 timestamp\n  )\n    internal\n    pure\n    returns (uint256 baseInterestRay, uint256 delinquencyFeeRay, uint256 protocolFee)\n  {\n    baseInterestRay = state.calculateBaseInterest(timestamp);\n\n    if (state.protocolFeeBips > 0) {\n      protocolFee = state.applyProtocolFee(baseInterestRay);\n    }\n\n    if (delinquencyFeeBips > 0) {\n      delinquencyFeeRay = state.updateDelinquency(\n        timestamp,\n        delinquencyFeeBips,\n        delinquencyGracePeriod\n      );\n    }\n\n    // Calculate new scaleFactor\n    uint256 prevScaleFactor = state.scaleFactor;\n    uint256 scaleFactorDelta = prevScaleFactor.rayMul(baseInterestRay + delinquencyFeeRay);\n\n    state.scaleFactor = (prevScaleFactor + scaleFactorDelta).toUint112();\n    state.lastInterestAccruedTimestamp = uint32(timestamp);\n  }\n}\n"},{"file_path":"src/libraries/BoolUtils.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nlibrary BoolUtils {\n  function and(bool a, bool b) internal pure returns (bool c) {\n    assembly {\n      c := and(a, b)\n    }\n  }\n\n  function or(bool a, bool b) internal pure returns (bool c) {\n    assembly {\n      c := or(a, b)\n    }\n  }\n\n  function xor(bool a, bool b) internal pure returns (bool c) {\n    assembly {\n      c := xor(a, b)\n    }\n  }\n}\n"},{"file_path":"src/market/WildcatMarketConfig.sol","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport './WildcatMarketBase.sol';\nimport '../libraries/FeeMath.sol';\nimport '../libraries/SafeCastLib.sol';\n\ncontract WildcatMarketConfig is WildcatMarketBase {\n  using SafeCastLib for uint256;\n  using FunctionTypeCasts for *;\n\n  // ===================================================================== //\n  //                      External Config Getters                          //\n  // ===================================================================== //\n\n  /**\n   * @dev Returns whether or not a market has been closed.\n   */\n  function isClosed() external view returns (bool) {\n    // Use stored state because the state update can not affect whether\n    // the market is closed.\n    return _state.isClosed;\n  }\n\n  /**\n   * @dev Returns the maximum amount of underlying asset that can\n   *      currently be deposited to the market.\n   */\n  function maximumDeposit() external view returns (uint256) {\n    MarketState memory state = _calculateCurrentStatePointers.asReturnsMarketState()();\n    return state.maximumDeposit();\n  }\n\n  /**\n   * @dev Returns the maximum supply the market can reach via\n   *      deposits (does not apply to interest accrual).\n   */\n  function maxTotalSupply() external view returns (uint256) {\n    return _state.maxTotalSupply;\n  }\n\n  /**\n   * @dev Returns the annual interest rate earned by lenders\n   *      in bips.\n   */\n  function annualInterestBips() external view returns (uint256) {\n    return _state.annualInterestBips;\n  }\n\n  function reserveRatioBips() external view returns (uint256) {\n    return _state.reserveRatioBips;\n  }\n\n  // ========================================================================== //\n  //                                  Sanctions                                 //\n  // ========================================================================== //\n\n  /// @dev Block a sanctioned account from interacting with the market\n  ///      and transfer its balance to an escrow contract.\n  // ******************************************************************\n  //          *  |\\**/|  *          *                                *\n  //          *  \\ == /  *          *                                *\n  //          *   | b|   *          *                                *\n  //          *   | y|   *          *                                *\n  //          *   \\ e/   *          *                                *\n  //          *    \\/    *          *                                *\n  //          *          *          *                                *\n  //          *          *          *                                *\n  //          *          *  |\\**/|  *                                *\n  //          *          *  \\ == /  *         _.-^^---....,,--       *\n  //          *          *   | b|   *    _--                  --_    *\n  //          *          *   | y|   *   <                        >)  *\n  //          *          *   \\ e/   *   |         O-FAC!          |  *\n  //          *          *    \\/    *    \\._                   _./   *\n  //          *          *          *       ```--. . , ; .--'''      *\n  //          *          *          *   💸        | |   |            *\n  //          *          *          *          .-=||  | |=-.    💸   *\n  //  💰🤑💰  *    😅    *    😐    *    💸    `-=#$%&%$#=-'         *\n  //   \\|/    *   /|\\    *   /|\\    *  🌪         | ;  :|    🌪      *\n  //   /\\     * 💰/\\ 💰  * 💰/\\ 💰  *    _____.,-#%&$@%#&#~,._____   *\n  // ******************************************************************\n  function nukeFromOrbit(address accountAddress) external nonReentrant sphereXGuardExternal {\n    if (!_isSanctioned(accountAddress)) revert_BadLaunchCode();\n    MarketState memory state = _getUpdatedState();\n    hooks.onNukeFromOrbit(accountAddress, state);\n    _blockAccount(state, accountAddress);\n    _writeState(state);\n  }\n\n  // ========================================================================== //\n  //                           External Config Setters                          //\n  // ========================================================================== //\n\n  /**\n   * @dev Sets the maximum total supply - this only limits deposits and\n   *      does not affect interest accrual.\n   *\n   *      The hooks contract may block the change but can not modify the\n   *      value being set.\n   */\n  function setMaxTotalSupply(\n    uint256 _maxTotalSupply\n  ) external onlyBorrower nonReentrant sphereXGuardExternal {\n    MarketState memory state = _getUpdatedState();\n    if (state.isClosed) revert_CapacityChangeOnClosedMarket();\n\n    hooks.onSetMaxTotalSupply(_maxTotalSupply, state);\n    state.maxTotalSupply = _maxTotalSupply.toUint128();\n    _writeState(state);\n    emit_MaxTotalSupplyUpdated(_maxTotalSupply);\n  }\n\n  /**\n   * @dev Sets the annual interest rate earned by lenders in bips.\n   *\n   *      If the new reserve ratio is lower than the old ratio,\n   *      asserts that the market is not currently delinquent.\n   *\n   *      If the new reserve ratio is higher than the old ratio,\n   *      asserts that the market will not become delinquent\n   *      because of the change.\n   */\n  function setAnnualInterestAndReserveRatioBips(\n    uint16 _annualInterestBips,\n    uint16 _reserveRatioBips\n  ) external onlyBorrower nonReentrant sphereXGuardExternal {\n    MarketState memory state = _getUpdatedState();\n    if (state.isClosed) revert_AprChangeOnClosedMarket();\n\n    uint256 initialReserveRatioBips = state.reserveRatioBips;\n\n    (_annualInterestBips, _reserveRatioBips) = hooks.onSetAnnualInterestAndReserveRatioBips(\n      _annualInterestBips,\n      _reserveRatioBips,\n      state\n    );\n\n    if (_annualInterestBips > BIP) {\n      revert_AnnualInterestBipsTooHigh();\n    }\n\n    if (_reserveRatioBips > BIP) {\n      revert_ReserveRatioBipsTooHigh();\n    }\n\n    if (_reserveRatioBips <= initialReserveRatioBips) {\n      if (state.liquidityRequired() > totalAssets()) {\n        revert_InsufficientReservesForOldLiquidityRatio();\n      }\n    }\n    state.reserveRatioBips = _reserveRatioBips;\n    state.annualInterestBips = _annualInterestBips;\n    if (_reserveRatioBips > initialReserveRatioBips) {\n      if (state.liquidityRequired() > totalAssets()) {\n        revert_InsufficientReservesForNewLiquidityRatio();\n      }\n    }\n\n    _writeState(state);\n    emit_AnnualInterestBipsUpdated(_annualInterestBips);\n    emit_ReserveRatioBipsUpdated(_reserveRatioBips);\n  }\n\n  function setProtocolFeeBips(uint16 _protocolFeeBips) external nonReentrant sphereXGuardExternal {\n    if (msg.sender != factory) revert_NotFactory();\n    if (_protocolFeeBips > 1_000) revert_ProtocolFeeTooHigh();\n    MarketState memory state = _getUpdatedState();\n    if (state.isClosed) revert_ProtocolFeeChangeOnClosedMarket();\n    if (_protocolFeeBips != state.protocolFeeBips) {\n      hooks.onSetProtocolFeeBips(_protocolFeeBips, state);\n      state.protocolFeeBips = _protocolFeeBips;\n      emit ProtocolFeeBipsUpdated(_protocolFeeBips);\n    }\n    _writeState(state);\n  }\n}\n"},{"file_path":"src/WildcatSanctionsEscrow.sol","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport './interfaces/IERC20.sol';\nimport './interfaces/IWildcatSanctionsEscrow.sol';\nimport './interfaces/IWildcatSanctionsSentinel.sol';\nimport './libraries/LibERC20.sol';\n\ncontract WildcatSanctionsEscrow is IWildcatSanctionsEscrow {\n  using LibERC20 for address;\n\n  address public immutable override sentinel;\n  address public immutable override borrower;\n  address public immutable override account;\n  address internal immutable asset;\n\n  constructor() {\n    sentinel = msg.sender;\n    (borrower, account, asset) = IWildcatSanctionsSentinel(sentinel).tmpEscrowParams();\n  }\n\n  function balance() public view override returns (uint256) {\n    return IERC20(asset).balanceOf(address(this));\n  }\n\n  function canReleaseEscrow() public view override returns (bool) {\n    return !IWildcatSanctionsSentinel(sentinel).isSanctioned(borrower, account);\n  }\n\n  function escrowedAsset() public view override returns (address, uint256) {\n    return (asset, balance());\n  }\n\n  function releaseEscrow() public override {\n    if (!canReleaseEscrow()) revert CanNotReleaseEscrow();\n\n    uint256 amount = balance();\n    address _account = account;\n    address _asset = asset;\n\n    asset.safeTransfer(_account, amount);\n\n    emit EscrowReleased(_account, _asset, amount);\n  }\n}\n"},{"file_path":"src/market/WildcatMarketBase.sol","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport '../ReentrancyGuard.sol';\nimport '../spherex/SphereXProtectedRegisteredBase.sol';\nimport '../interfaces/IMarketEventsAndErrors.sol';\nimport '../interfaces/IERC20.sol';\nimport '../IHooksFactory.sol';\nimport '../libraries/FeeMath.sol';\nimport '../libraries/MarketErrors.sol';\nimport '../libraries/MarketEvents.sol';\nimport '../libraries/Withdrawal.sol';\nimport '../libraries/FunctionTypeCasts.sol';\nimport '../libraries/LibERC20.sol';\nimport '../types/HooksConfig.sol';\n\ncontract WildcatMarketBase is\n  SphereXProtectedRegisteredBase,\n  ReentrancyGuard,\n  IMarketEventsAndErrors\n{\n  using SafeCastLib for uint256;\n  using MathUtils for uint256;\n  using FunctionTypeCasts for *;\n  using LibERC20 for address;\n\n  // ==================================================================== //\n  //                       Market Config (immutable)                       //\n  // ==================================================================== //\n\n  /**\n   * @dev Return the contract version string \"2\".\n   */\n  function version() external pure returns (string memory) {\n    assembly {\n      mstore(0x40, 0)\n      mstore(0x41, 0x0132)\n      mstore(0x20, 0x20)\n      return(0x20, 0x60)\n    }\n  }\n\n  HooksConfig public immutable hooks;\n\n  /// @dev Account with blacklist control, used for blocking sanctioned addresses.\n  address public immutable sentinel;\n\n  /// @dev Account with authority to borrow assets from the market.\n  address public immutable borrower;\n\n  /// @dev Factory that deployed the market. Has the ability to update the protocol fee.\n  address public immutable factory;\n\n  /// @dev Account that receives protocol fees.\n  address public immutable feeRecipient;\n\n  /// @dev Penalty fee added to interest earned by lenders, does not affect protocol fee.\n  uint public immutable delinquencyFeeBips;\n\n  /// @dev Time after which delinquency incurs penalty fee.\n  uint public immutable delinquencyGracePeriod;\n\n  /// @dev Time before withdrawal batches are processed.\n  uint public immutable withdrawalBatchDuration;\n\n  /// @dev Token decimals (same as underlying asset).\n  uint8 public immutable decimals;\n\n  /// @dev Address of the underlying asset.\n  address public immutable asset;\n\n  bytes32 internal immutable PACKED_NAME_WORD_0;\n  bytes32 internal immutable PACKED_NAME_WORD_1;\n  bytes32 internal immutable PACKED_SYMBOL_WORD_0;\n  bytes32 internal immutable PACKED_SYMBOL_WORD_1;\n\n  function symbol() external view returns (string memory) {\n    bytes32 symbolWord0 = PACKED_SYMBOL_WORD_0;\n    bytes32 symbolWord1 = PACKED_SYMBOL_WORD_1;\n\n    assembly {\n      // The layout here is:\n      // 0x00: Offset to the string\n      // 0x20: Length of the string\n      // 0x40: First word of the string\n      // 0x60: Second word of the string\n      // The first word of the string that is kept in immutable storage also contains the\n      // length byte, meaning the total size limit of the string is 63 bytes.\n      mstore(0, 0x20)\n      mstore(0x20, 0)\n      mstore(0x3f, symbolWord0)\n      mstore(0x5f, symbolWord1)\n      return(0, 0x80)\n    }\n  }\n\n  function name() external view returns (string memory) {\n    bytes32 nameWord0 = PACKED_NAME_WORD_0;\n    bytes32 nameWord1 = PACKED_NAME_WORD_1;\n\n    assembly {\n      // The layout here is:\n      // 0x00: Offset to the string\n      // 0x20: Length of the string\n      // 0x40: First word of the string\n      // 0x60: Second word of the string\n      // The first word of the string that is kept in immutable storage also contains the\n      // length byte, meaning the total size limit of the string is 63 bytes.\n      mstore(0, 0x20)\n      mstore(0x20, 0)\n      mstore(0x3f, nameWord0)\n      mstore(0x5f, nameWord1)\n      return(0, 0x80)\n    }\n  }\n\n  /// @dev Returns immutable arch-controller address.\n  function archController() external view returns (address) {\n    return _archController;\n  }\n\n  // ===================================================================== //\n  //                             Market State                               //\n  // ===================================================================== //\n\n  MarketState internal _state;\n\n  mapping(address => Account) internal _accounts;\n\n  WithdrawalData internal _withdrawalData;\n\n  // ===================================================================== //\n  //                             Constructor                               //\n  // ===================================================================== //\n\n  function _getMarketParameters() internal view returns (uint256 marketParametersPointer) {\n    assembly {\n      marketParametersPointer := mload(0x40)\n      mstore(0x40, add(marketParametersPointer, 0x260))\n      // Write the selector for IHooksFactory.getMarketParameters\n      mstore(0x00, 0x04032dbb)\n      // Call `getMarketParameters` and copy the returned struct to the allocated memory\n      // buffer, reverting if the call fails or does not return the correct amount of bytes.\n      // This overrides all the ABI decoding safety checks, as the call is always made to\n      // the factory contract which will only ever return the prepared market parameters.\n      if iszero(\n        and(\n          eq(returndatasize(), 0x260),\n          staticcall(gas(), caller(), 0x1c, 0x04, marketParametersPointer, 0x260)\n        )\n      ) {\n        revert(0, 0)\n      }\n    }\n  }\n\n  constructor() {\n    factory = msg.sender;\n    // Cast the function signature of `_getMarketParameters` to get a valid reference to\n    // a `MarketParameters` object without creating a duplicate allocation or unnecessarily\n    // zeroing out the memory buffer.\n    MarketParameters memory parameters = _getMarketParameters.asReturnsMarketParameters()();\n\n    // Set asset metadata\n    asset = parameters.asset;\n    decimals = parameters.decimals;\n\n    PACKED_NAME_WORD_0 = parameters.packedNameWord0;\n    PACKED_NAME_WORD_1 = parameters.packedNameWord1;\n    PACKED_SYMBOL_WORD_0 = parameters.packedSymbolWord0;\n    PACKED_SYMBOL_WORD_1 = parameters.packedSymbolWord1;\n\n    {\n      // Initialize the market state - all values in slots 1 and 2 of the struct are\n      // initialized to zero, so they are skipped.\n\n      uint maxTotalSupply = parameters.maxTotalSupply;\n      uint reserveRatioBips = parameters.reserveRatioBips;\n      uint annualInterestBips = parameters.annualInterestBips;\n      uint protocolFeeBips = parameters.protocolFeeBips;\n\n      assembly {\n        // MarketState Slot 0 Storage Layout:\n        // [15:31] | state.maxTotalSupply\n        // [31:32] | state.isClosed = false\n\n        let slot0 := shl(8, maxTotalSupply)\n        sstore(_state.slot, slot0)\n\n        // MarketState Slot 3 Storage Layout:\n        // [4:8] | lastInterestAccruedTimestamp\n        // [8:22] | scaleFactor = 1e27\n        // [22:24] | reserveRatioBips\n        // [24:26] | annualInterestBips\n        // [26:28] | protocolFeeBips\n        // [28:32] | timeDelinquent = 0\n\n        let slot3 := or(\n          or(or(shl(0xc0, timestamp()), shl(0x50, RAY)), shl(0x40, reserveRatioBips)),\n          or(shl(0x30, annualInterestBips), shl(0x20, protocolFeeBips))\n        )\n\n        sstore(add(_state.slot, 3), slot3)\n      }\n    }\n\n    hooks = parameters.hooks;\n    sentinel = parameters.sentinel;\n    borrower = parameters.borrower;\n    feeRecipient = parameters.feeRecipient;\n    delinquencyFeeBips = parameters.delinquencyFeeBips;\n    delinquencyGracePeriod = parameters.delinquencyGracePeriod;\n    withdrawalBatchDuration = parameters.withdrawalBatchDuration;\n    _archController = parameters.archController;\n    __SphereXProtectedRegisteredBase_init(parameters.sphereXEngine);\n  }\n\n  // ===================================================================== //\n  //                              Modifiers                                //\n  // ===================================================================== //\n\n  modifier onlyBorrower() {\n    address _borrower = borrower;\n    assembly {\n      // Equivalent to\n      // if (msg.sender != borrower) revert NotApprovedBorrower();\n      if xor(caller(), _borrower) {\n        mstore(0, 0x02171e6a)\n        revert(0x1c, 0x04)\n      }\n    }\n    _;\n  }\n\n  // ===================================================================== //\n  //                       Internal State Getters                          //\n  // ===================================================================== //\n\n  /**\n   * @dev Retrieve an account from storage.\n   *\n   *      Reverts if account is sanctioned.\n   */\n  function _getAccount(address accountAddress) internal view returns (Account memory account) {\n    account = _accounts[accountAddress];\n    if (_isSanctioned(accountAddress)) revert_AccountBlocked();\n  }\n\n  /**\n   * @dev Checks if `account` is flagged as a sanctioned entity by Chainalysis.\n   *      If an account is flagged mistakenly, the borrower can override their\n   *      status on the sentinel and allow them to interact with the market.\n   */\n  function _isSanctioned(address account) internal view returns (bool result) {\n    address _borrower = borrower;\n    address _sentinel = address(sentinel);\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(0, 0x06e74444)\n      mstore(0x20, _borrower)\n      mstore(0x40, account)\n      // Call `sentinel.isSanctioned(borrower, account)` and revert if the call fails\n      // or does not return 32 bytes.\n      if iszero(\n        and(eq(returndatasize(), 0x20), staticcall(gas(), _sentinel, 0x1c, 0x44, 0, 0x20))\n      ) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n      result := mload(0)\n      mstore(0x40, freeMemoryPointer)\n    }\n  }\n\n  // ===================================================================== //\n  //                       External State Getters                          //\n  // ===================================================================== //\n\n  /**\n   * @dev Returns the amount of underlying assets the borrower is obligated\n   *      to maintain in the market to avoid delinquency.\n   */\n  function coverageLiquidity() external view nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().liquidityRequired();\n  }\n\n  /**\n   * @dev Returns the scale factor (in ray) used to convert scaled balances\n   *      to normalized balances.\n   */\n  function scaleFactor() external view nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().scaleFactor;\n  }\n\n  /**\n   * @dev Total balance in underlying asset.\n   */\n  function totalAssets() public view returns (uint256) {\n    return asset.balanceOf(address(this));\n  }\n\n  /**\n   * @dev Returns the amount of underlying assets the borrower is allowed\n   *      to borrow.\n   *\n   *      This is the balance of underlying assets minus:\n   *      - pending (unpaid) withdrawals\n   *      - paid withdrawals\n   *      - reserve ratio times the portion of the supply not pending withdrawal\n   *      - protocol fees\n   */\n  function borrowableAssets() external view nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().borrowableAssets(totalAssets());\n  }\n\n  /**\n   * @dev Returns the amount of protocol fees (in underlying asset amount)\n   *      that have accrued and are pending withdrawal.\n   */\n  function accruedProtocolFees() external view nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().accruedProtocolFees;\n  }\n\n  function totalDebts() external view nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().totalDebts();\n  }\n\n  /**\n   * @dev Returns the state of the market as of the last update.\n   */\n  function previousState() external view returns (MarketState memory) {\n    MarketState memory state = _state;\n\n    assembly {\n      return(state, 0x1c0)\n    }\n  }\n\n  /**\n   * @dev Return the state the market would have at the current block after applying\n   *      interest and fees accrued since the last update and processing the pending\n   *      withdrawal batch if it is expired.\n   */\n  function currentState() external view nonReentrantView returns (MarketState memory state) {\n    state = _calculateCurrentStatePointers.asReturnsMarketState()();\n    assembly {\n      return(state, 0x1c0)\n    }\n  }\n\n  /**\n   * @dev Call `_calculateCurrentState()` and return only the `state` parameter.\n   *\n   *      Casting the function type prevents a duplicate declaration of the MarketState\n   *      return parameter, which would cause unnecessary zeroing and allocation of memory.\n   *      With `viaIR` enabled, the cast is a noop.\n   */\n  function _calculateCurrentStatePointers() internal view returns (uint256 state) {\n    (state, , ) = _calculateCurrentState.asReturnsPointers()();\n  }\n\n  /**\n   * @dev Returns the scaled total supply the vaut would have at the current block\n   *      after applying interest and fees accrued since the last update and burning\n   *      market tokens for the pending withdrawal batch if it is expired.\n   */\n  function scaledTotalSupply() external view nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().scaledTotalSupply;\n  }\n\n  /**\n   * @dev Returns the scaled balance of `account`\n   */\n  function scaledBalanceOf(address account) external view nonReentrantView returns (uint256) {\n    return _accounts[account].scaledBalance;\n  }\n\n  /**\n   * @dev Returns the amount of protocol fees that are currently\n   *      withdrawable by the fee recipient.\n   */\n  function withdrawableProtocolFees() external view returns (uint128) {\n    return\n      _calculateCurrentStatePointers.asReturnsMarketState()().withdrawableProtocolFees(\n        totalAssets()\n      );\n  }\n\n  // /*//////////////////////////////////////////////////////////////\n  //                     Internal State Handlers\n  // //////////////////////////////////////////////////////////////*/\n\n  function _blockAccount(MarketState memory state, address accountAddress) internal virtual {}\n\n  /**\n   * @dev Returns cached MarketState after accruing interest and delinquency / protocol fees\n   *      and processing expired withdrawal batch, if any.\n   *\n   *      Used by functions that make additional changes to `state`.\n   *\n   *      NOTE: Returned `state` does not match `_state` if interest is accrued\n   *            Calling function must update `_state` or revert.\n   *\n   * @return state Market state after interest is accrued.\n   */\n  function _getUpdatedState() internal returns (MarketState memory state) {\n    state = _state;\n    // Handle expired withdrawal batch\n    if (state.hasPendingExpiredBatch()) {\n      uint256 expiry = state.pendingWithdrawalExpiry;\n      // Only accrue interest if time has passed since last update.\n      // This will only be false if withdrawalBatchDuration is 0.\n      uint32 lastInterestAccruedTimestamp = state.lastInterestAccruedTimestamp;\n      if (expiry != lastInterestAccruedTimestamp) {\n        (uint256 baseInterestRay, uint256 delinquencyFeeRay, uint256 protocolFee) = state\n          .updateScaleFactorAndFees(delinquencyFeeBips, delinquencyGracePeriod, expiry);\n        emit_InterestAndFeesAccrued(\n          lastInterestAccruedTimestamp,\n          expiry,\n          state.scaleFactor,\n          baseInterestRay,\n          delinquencyFeeRay,\n          protocolFee\n        );\n      }\n      _processExpiredWithdrawalBatch(state);\n    }\n    uint32 lastInterestAccruedTimestamp = state.lastInterestAccruedTimestamp;\n    // Apply interest and fees accrued since last update (expiry or previous tx)\n    if (block.timestamp != lastInterestAccruedTimestamp) {\n      (uint256 baseInterestRay, uint256 delinquencyFeeRay, uint256 protocolFee) = state\n        .updateScaleFactorAndFees(delinquencyFeeBips, delinquencyGracePeriod, block.timestamp);\n      emit_InterestAndFeesAccrued(\n        lastInterestAccruedTimestamp,\n        block.timestamp,\n        state.scaleFactor,\n        baseInterestRay,\n        delinquencyFeeRay,\n        protocolFee\n      );\n    }\n\n    // If there is a pending withdrawal batch which is not fully paid off, set aside\n    // up to the available liquidity for that batch.\n    if (state.pendingWithdrawalExpiry != 0) {\n      uint32 expiry = state.pendingWithdrawalExpiry;\n      WithdrawalBatch memory batch = _withdrawalData.batches[expiry];\n      if (batch.scaledAmountBurned < batch.scaledTotalAmount) {\n        // Burn as much of the withdrawal batch as possible with available liquidity.\n        uint256 availableLiquidity = batch.availableLiquidityForPendingBatch(state, totalAssets());\n        if (availableLiquidity > 0) {\n          _applyWithdrawalBatchPayment(batch, state, expiry, availableLiquidity);\n          _withdrawalData.batches[expiry] = batch;\n        }\n      }\n    }\n  }\n\n  /**\n   * @dev Calculate the current state, applying fees and interest accrued since\n   *      the last state update as well as the effects of withdrawal batch expiry\n   *      on the market state.\n   *      Identical to _getUpdatedState() except it does not modify storage or\n   *      or emit events.\n   *      Returns expired batch data, if any, so queries against batches have\n   *      access to the most recent data.\n   */\n  function _calculateCurrentState()\n    internal\n    view\n    returns (\n      MarketState memory state,\n      uint32 pendingBatchExpiry,\n      WithdrawalBatch memory pendingBatch\n    )\n  {\n    state = _state;\n    // Handle expired withdrawal batch\n    if (state.hasPendingExpiredBatch()) {\n      pendingBatchExpiry = state.pendingWithdrawalExpiry;\n      // Only accrue interest if time has passed since last update.\n      // This will only be false if withdrawalBatchDuration is 0.\n      if (pendingBatchExpiry != state.lastInterestAccruedTimestamp) {\n        state.updateScaleFactorAndFees(\n          delinquencyFeeBips,\n          delinquencyGracePeriod,\n          pendingBatchExpiry\n        );\n      }\n\n      pendingBatch = _withdrawalData.batches[pendingBatchExpiry];\n      uint256 availableLiquidity = pendingBatch.availableLiquidityForPendingBatch(\n        state,\n        totalAssets()\n      );\n      if (availableLiquidity > 0) {\n        _applyWithdrawalBatchPaymentView(pendingBatch, state, availableLiquidity);\n      }\n      state.pendingWithdrawalExpiry = 0;\n    }\n\n    if (state.lastInterestAccruedTimestamp != block.timestamp) {\n      state.updateScaleFactorAndFees(delinquencyFeeBips, delinquencyGracePeriod, block.timestamp);\n    }\n\n    // If there is a pending withdrawal batch which is not fully paid off, set aside\n    // up to the available liquidity for that batch.\n    if (state.pendingWithdrawalExpiry != 0) {\n      pendingBatchExpiry = state.pendingWithdrawalExpiry;\n      pendingBatch = _withdrawalData.batches[pendingBatchExpiry];\n      if (pendingBatch.scaledAmountBurned < pendingBatch.scaledTotalAmount) {\n        // Burn as much of the withdrawal batch as possible with available liquidity.\n        uint256 availableLiquidity = pendingBatch.availableLiquidityForPendingBatch(\n          state,\n          totalAssets()\n        );\n        if (availableLiquidity > 0) {\n          _applyWithdrawalBatchPaymentView(pendingBatch, state, availableLiquidity);\n        }\n      }\n    }\n  }\n\n  /**\n   * @dev Writes the cached MarketState to storage and emits an event.\n   *      Used at the end of all functions which modify `state`.\n   */\n  function _writeState(MarketState memory state) internal {\n    bool isDelinquent = state.liquidityRequired() > totalAssets();\n    state.isDelinquent = isDelinquent;\n\n    {\n      bool isClosed = state.isClosed;\n      uint maxTotalSupply = state.maxTotalSupply;\n      assembly {\n        // Slot 0 Storage Layout:\n        // [15:31] | state.maxTotalSupply\n        // [31:32] | state.isClosed\n        let slot0 := or(isClosed, shl(0x08, maxTotalSupply))\n        sstore(_state.slot, slot0)\n      }\n    }\n    {\n      uint accruedProtocolFees = state.accruedProtocolFees;\n      uint normalizedUnclaimedWithdrawals = state.normalizedUnclaimedWithdrawals;\n      assembly {\n        // Slot 1 Storage Layout:\n        // [0:16] | state.normalizedUnclaimedWithdrawals\n        // [16:32] | state.accruedProtocolFees\n        let slot1 := or(accruedProtocolFees, shl(0x80, normalizedUnclaimedWithdrawals))\n        sstore(add(_state.slot, 1), slot1)\n      }\n    }\n    {\n      uint scaledTotalSupply = state.scaledTotalSupply;\n      uint scaledPendingWithdrawals = state.scaledPendingWithdrawals;\n      uint pendingWithdrawalExpiry = state.pendingWithdrawalExpiry;\n      assembly {\n        // Slot 2 Storage Layout:\n        // [1:2] | state.isDelinquent\n        // [2:6] | state.pendingWithdrawalExpiry\n        // [6:19] | state.scaledPendingWithdrawals\n        // [19:32] | state.scaledTotalSupply\n        let slot2 := or(\n          or(\n            or(shl(0xf0, isDelinquent), shl(0xd0, pendingWithdrawalExpiry)),\n            shl(0x68, scaledPendingWithdrawals)\n          ),\n          scaledTotalSupply\n        )\n        sstore(add(_state.slot, 2), slot2)\n      }\n    }\n    {\n      uint timeDelinquent = state.timeDelinquent;\n      uint protocolFeeBips = state.protocolFeeBips;\n      uint annualInterestBips = state.annualInterestBips;\n      uint reserveRatioBips = state.reserveRatioBips;\n      uint scaleFactor = state.scaleFactor;\n      uint lastInterestAccruedTimestamp = state.lastInterestAccruedTimestamp;\n      assembly {\n        // Slot 3 Storage Layout:\n        // [4:8] | state.lastInterestAccruedTimestamp\n        // [8:22] | state.scaleFactor\n        // [22:24] | state.reserveRatioBips\n        // [24:26] | state.annualInterestBips\n        // [26:28] | protocolFeeBips\n        // [28:32] | state.timeDelinquent\n        let slot3 := or(\n          or(\n            or(\n              or(shl(0xc0, lastInterestAccruedTimestamp), shl(0x50, scaleFactor)),\n              shl(0x40, reserveRatioBips)\n            ),\n            or(shl(0x30, annualInterestBips), shl(0x20, protocolFeeBips))\n          ),\n          timeDelinquent\n        )\n        sstore(add(_state.slot, 3), slot3)\n      }\n    }\n    emit_StateUpdated(state.scaleFactor, isDelinquent);\n  }\n\n  /**\n   * @dev Handles an expired withdrawal batch:\n   *      - Retrieves the amount of underlying assets that can be used to pay for the batch.\n   *      - If the amount is sufficient to pay the full amount owed to the batch, the batch\n   *        is closed and the total withdrawal amount is reserved.\n   *      - If the amount is insufficient to pay the full amount owed to the batch, the batch\n   *        is recorded as an unpaid batch and the available assets are reserved.\n   *      - The assets reserved for the batch are scaled by the current scale factor and that\n   *        amount of scaled tokens is burned, ensuring borrowers do not continue paying interest\n   *        on withdrawn assets.\n   */\n  function _processExpiredWithdrawalBatch(MarketState memory state) internal {\n    uint32 expiry = state.pendingWithdrawalExpiry;\n    WithdrawalBatch memory batch = _withdrawalData.batches[expiry];\n\n    if (batch.scaledAmountBurned < batch.scaledTotalAmount) {\n      // Burn as much of the withdrawal batch as possible with available liquidity.\n      uint256 availableLiquidity = batch.availableLiquidityForPendingBatch(state, totalAssets());\n      if (availableLiquidity > 0) {\n        _applyWithdrawalBatchPayment(batch, state, expiry, availableLiquidity);\n      }\n    }\n\n    emit_WithdrawalBatchExpired(\n      expiry,\n      batch.scaledTotalAmount,\n      batch.scaledAmountBurned,\n      batch.normalizedAmountPaid\n    );\n\n    if (batch.scaledAmountBurned < batch.scaledTotalAmount) {\n      _withdrawalData.unpaidBatches.push(expiry);\n    } else {\n      emit_WithdrawalBatchClosed(expiry);\n    }\n\n    state.pendingWithdrawalExpiry = 0;\n\n    _withdrawalData.batches[expiry] = batch;\n  }\n\n  /**\n   * @dev Process withdrawal payment, burning market tokens and reserving\n   *      underlying assets so they are only available for withdrawals.\n   */\n  function _applyWithdrawalBatchPayment(\n    WithdrawalBatch memory batch,\n    MarketState memory state,\n    uint32 expiry,\n    uint256 availableLiquidity\n  ) internal returns (uint104 scaledAmountBurned, uint128 normalizedAmountPaid) {\n    uint104 scaledAmountOwed = batch.scaledTotalAmount - batch.scaledAmountBurned;\n\n    // Do nothing if batch is already paid\n    if (scaledAmountOwed == 0) return (0, 0);\n\n    uint256 scaledAvailableLiquidity = state.scaleAmount(availableLiquidity);\n    scaledAmountBurned = MathUtils.min(scaledAvailableLiquidity, scaledAmountOwed).toUint104();\n    // Use mulDiv instead of normalizeAmount to round `normalizedAmountPaid` down, ensuring\n    // it is always possible to finish withdrawal batches on closed markets.\n    normalizedAmountPaid = MathUtils.mulDiv(scaledAmountBurned, state.scaleFactor, RAY).toUint128();\n\n    batch.scaledAmountBurned += scaledAmountBurned;\n    batch.normalizedAmountPaid += normalizedAmountPaid;\n    state.scaledPendingWithdrawals -= scaledAmountBurned;\n\n    // Update normalizedUnclaimedWithdrawals so the tokens are only accessible for withdrawals.\n    state.normalizedUnclaimedWithdrawals += normalizedAmountPaid;\n\n    // Burn market tokens to stop interest accrual upon withdrawal payment.\n    state.scaledTotalSupply -= scaledAmountBurned;\n\n    // Emit transfer for external trackers to indicate burn.\n    emit_Transfer(address(this), _runtimeConstant(address(0)), normalizedAmountPaid);\n    emit_WithdrawalBatchPayment(expiry, scaledAmountBurned, normalizedAmountPaid);\n  }\n\n  function _applyWithdrawalBatchPaymentView(\n    WithdrawalBatch memory batch,\n    MarketState memory state,\n    uint256 availableLiquidity\n  ) internal pure {\n    uint104 scaledAmountOwed = batch.scaledTotalAmount - batch.scaledAmountBurned;\n    // Do nothing if batch is already paid\n    if (scaledAmountOwed == 0) return;\n\n    uint256 scaledAvailableLiquidity = state.scaleAmount(availableLiquidity);\n    uint104 scaledAmountBurned = MathUtils\n      .min(scaledAvailableLiquidity, scaledAmountOwed)\n      .toUint104();\n    // Use mulDiv instead of normalizeAmount to round `normalizedAmountPaid` down, ensuring\n    // it is always possible to finish withdrawal batches on closed markets.\n    uint128 normalizedAmountPaid = MathUtils\n      .mulDiv(scaledAmountBurned, state.scaleFactor, RAY)\n      .toUint128();\n\n    batch.scaledAmountBurned += scaledAmountBurned;\n    batch.normalizedAmountPaid += normalizedAmountPaid;\n    state.scaledPendingWithdrawals -= scaledAmountBurned;\n\n    // Update normalizedUnclaimedWithdrawals so the tokens are only accessible for withdrawals.\n    state.normalizedUnclaimedWithdrawals += normalizedAmountPaid;\n\n    // Burn market tokens to stop interest accrual upon withdrawal payment.\n    state.scaledTotalSupply -= scaledAmountBurned;\n  }\n\n  /**\n   * @dev Function to obfuscate the fact that a value is constant from solc's optimizer.\n   *      This prevents function specialization for calls with a constant input parameter,\n   *      which usually has very little benefit in terms of gas savings but can\n   *      drastically increase contract size.\n   *\n   *      The value returned will always match the input value outside of the constructor,\n   *      fallback and receive functions.\n   */\n  function _runtimeConstant(\n    uint256 actualConstant\n  ) internal pure returns (uint256 runtimeConstant) {\n    assembly {\n      mstore(0, actualConstant)\n      runtimeConstant := mload(iszero(calldatasize()))\n    }\n  }\n\n  function _runtimeConstant(\n    address actualConstant\n  ) internal pure returns (address runtimeConstant) {\n    assembly {\n      mstore(0, actualConstant)\n      runtimeConstant := mload(iszero(calldatasize()))\n    }\n  }\n\n  function _isFlaggedByChainalysis(address account) internal view returns (bool isFlagged) {\n    address sentinelAddress = address(sentinel);\n    assembly {\n      mstore(0, 0x95c09839)\n      mstore(0x20, account)\n      if iszero(\n        and(eq(returndatasize(), 0x20), staticcall(gas(), sentinelAddress, 0x1c, 0x24, 0, 0x20))\n      ) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n      isFlagged := mload(0)\n    }\n  }\n\n  function _createEscrowForUnderlyingAsset(\n    address accountAddress\n  ) internal returns (address escrow) {\n    address tokenAddress = address(asset);\n    address borrowerAddress = borrower;\n    address sentinelAddress = address(sentinel);\n\n    assembly {\n      let freeMemoryPointer := mload(0x40)\n      mstore(0, 0xa1054f6b)\n      mstore(0x20, borrowerAddress)\n      mstore(0x40, accountAddress)\n      mstore(0x60, tokenAddress)\n      if iszero(\n        and(eq(returndatasize(), 0x20), call(gas(), sentinelAddress, 0, 0x1c, 0x64, 0, 0x20))\n      ) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n      escrow := mload(0)\n      mstore(0x40, freeMemoryPointer)\n      mstore(0x60, 0)\n    }\n  }\n}\n"},{"file_path":"src/libraries/StringQuery.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport { LibBit } from 'solady/utils/LibBit.sol';\n\nusing LibBit for uint256;\n\nuint256 constant OnlyFullWordMask = 0xffffffe0;\n\nfunction bytes32ToString(bytes32 value) pure returns (string memory str) {\n  uint256 size;\n  unchecked {\n    uint256 sizeInBits = 255 - uint256(value).ffs();\n    size = (sizeInBits + 7) / 8;\n  }\n  assembly {\n    str := mload(0x40)\n    mstore(0x40, add(str, 0x40))\n    mstore(str, size)\n    mstore(add(str, 0x20), value)\n  }\n}\n\nfunction queryStringOrBytes32AsString(\n  address target,\n  uint256 leftPaddedFunctionSelector,\n  uint256 leftPaddedGenericErrorSelector\n) view returns (string memory str) {\n  bool isBytes32;\n  assembly {\n    mstore(0, leftPaddedFunctionSelector)\n    let status := staticcall(gas(), target, 0x1c, 0x04, 0, 0)\n    isBytes32 := eq(returndatasize(), 0x20)\n    // If call fails or function returns invalid data, revert.\n    // Strings are always right padded to full words - if the returndata\n    // is not 32 bytes (string encoded as bytes32) or >95 bytes (minimum abi\n    // encoded string) it is an invalid string.\n    if or(iszero(status), iszero(or(isBytes32, gt(returndatasize(), 0x5f)))) {\n      // Check if call failed\n      if iszero(status) {\n        // Check if any revert data was given\n        if returndatasize() {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n        // If not, throw a generic error\n        mstore(0, leftPaddedGenericErrorSelector)\n        revert(0x1c, 0x04)\n      }\n      // If the returndata is the wrong size, `revert InvalidReturnDataString()`\n      mstore(0, 0x4cb9c000)\n      revert(0x1c, 0x04)\n    }\n  }\n  if (isBytes32) {\n    bytes32 value;\n    assembly {\n      returndatacopy(0x00, 0x00, 0x20)\n      value := mload(0)\n    }\n    str = bytes32ToString(value);\n  } else {\n    // If returndata is a string, copy the length and value\n    assembly {\n      str := mload(0x40)\n      // Get allocation size for the string including the length and data.\n      // Rounding down returndatasize to nearest word because the returndata\n      // has an extra offset word.\n      let allocSize := and(sub(returndatasize(), 1), OnlyFullWordMask)\n      mstore(0x40, add(str, allocSize))\n      // Copy returndata after the offset\n      returndatacopy(str, 0x20, sub(returndatasize(), 0x20))\n      let length := mload(str)\n      // Check if the length matches the returndatasize.\n      // The encoded string should have the string length rounded up to the nearest word\n      // as well as two words for length and offset.\n      let expectedReturndataSize := add(allocSize, 0x20)\n      if xor(returndatasize(), expectedReturndataSize) {\n        mstore(0, 0x4cb9c000)\n        revert(0x1c, 0x04)\n      }\n    }\n  }\n}\n"},{"file_path":"src/spherex/SphereXProtectedEvents.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nfunction emit_ChangedSpherexOperator(address oldSphereXAdmin, address newSphereXAdmin) {\n  assembly {\n    mstore(0, oldSphereXAdmin)\n    mstore(0x20, newSphereXAdmin)\n    log1(0, 0x40, 0x2ac55ae7ba47db34b5334622acafeb34a65daf143b47019273185d64c73a35a5)\n  }\n}\n\nfunction emit_ChangedSpherexEngineAddress(address oldEngineAddress, address newEngineAddress) {\n  assembly {\n    mstore(0, oldEngineAddress)\n    mstore(0x20, newEngineAddress)\n    log1(0, 0x40, 0xf33499cccaa0611882086224cc48cd82ef54b66a4d2edf4ed67108dd516896d5)\n  }\n}\n\nfunction emit_SpherexAdminTransferStarted(address currentAdmin, address pendingAdmin) {\n  assembly {\n    mstore(0, currentAdmin)\n    mstore(0x20, pendingAdmin)\n    log1(0, 0x40, 0x5778f1547abbbb86090a43c32aec38334b31df4beeb6f8f3fa063f593b53a526)\n  }\n}\n\nfunction emit_SpherexAdminTransferCompleted(address oldAdmin, address newAdmin) {\n  assembly {\n    mstore(0, oldAdmin)\n    mstore(0x20, newAdmin)\n    log1(0, 0x40, 0x67ebaebcd2ca5a91a404e898110f221747e8d15567f2388a34794aab151cf3e6)\n  }\n}\n\nfunction emit_NewAllowedSenderOnchain(address sender) {\n  assembly {\n    mstore(0, sender)\n    log1(0, 0x20, 0x6de0a1fd3a59e5479e6480ba65ef28d4f3ab8143c2c631bbfd9969ab39074797)\n  }\n}\n"},{"file_path":"src/libraries/SafeCastLib.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport './Errors.sol';\n\nlibrary SafeCastLib {\n  function _assertNonOverflow(bool didNotOverflow) private pure {\n    assembly {\n      if iszero(didNotOverflow) {\n        mstore(0, Panic_ErrorSelector)\n        mstore(Panic_ErrorCodePointer, Panic_Arithmetic)\n        revert(Error_SelectorPointer, Panic_ErrorLength)\n      }\n    }\n  }\n\n  function toUint8(uint256 x) internal pure returns (uint8 y) {\n    _assertNonOverflow(x == (y = uint8(x)));\n  }\n\n  function toUint16(uint256 x) internal pure returns (uint16 y) {\n    _assertNonOverflow(x == (y = uint16(x)));\n  }\n\n  function toUint24(uint256 x) internal pure returns (uint24 y) {\n    _assertNonOverflow(x == (y = uint24(x)));\n  }\n\n  function toUint32(uint256 x) internal pure returns (uint32 y) {\n    _assertNonOverflow(x == (y = uint32(x)));\n  }\n\n  function toUint40(uint256 x) internal pure returns (uint40 y) {\n    _assertNonOverflow(x == (y = uint40(x)));\n  }\n\n  function toUint48(uint256 x) internal pure returns (uint48 y) {\n    _assertNonOverflow(x == (y = uint48(x)));\n  }\n\n  function toUint56(uint256 x) internal pure returns (uint56 y) {\n    _assertNonOverflow(x == (y = uint56(x)));\n  }\n\n  function toUint64(uint256 x) internal pure returns (uint64 y) {\n    _assertNonOverflow(x == (y = uint64(x)));\n  }\n\n  function toUint72(uint256 x) internal pure returns (uint72 y) {\n    _assertNonOverflow(x == (y = uint72(x)));\n  }\n\n  function toUint80(uint256 x) internal pure returns (uint80 y) {\n    _assertNonOverflow(x == (y = uint80(x)));\n  }\n\n  function toUint88(uint256 x) internal pure returns (uint88 y) {\n    _assertNonOverflow(x == (y = uint88(x)));\n  }\n\n  function toUint96(uint256 x) internal pure returns (uint96 y) {\n    _assertNonOverflow(x == (y = uint96(x)));\n  }\n\n  function toUint104(uint256 x) internal pure returns (uint104 y) {\n    _assertNonOverflow(x == (y = uint104(x)));\n  }\n\n  function toUint112(uint256 x) internal pure returns (uint112 y) {\n    _assertNonOverflow(x == (y = uint112(x)));\n  }\n\n  function toUint120(uint256 x) internal pure returns (uint120 y) {\n    _assertNonOverflow(x == (y = uint120(x)));\n  }\n\n  function toUint128(uint256 x) internal pure returns (uint128 y) {\n    _assertNonOverflow(x == (y = uint128(x)));\n  }\n\n  function toUint136(uint256 x) internal pure returns (uint136 y) {\n    _assertNonOverflow(x == (y = uint136(x)));\n  }\n\n  function toUint144(uint256 x) internal pure returns (uint144 y) {\n    _assertNonOverflow(x == (y = uint144(x)));\n  }\n\n  function toUint152(uint256 x) internal pure returns (uint152 y) {\n    _assertNonOverflow(x == (y = uint152(x)));\n  }\n\n  function toUint160(uint256 x) internal pure returns (uint160 y) {\n    _assertNonOverflow(x == (y = uint160(x)));\n  }\n\n  function toUint168(uint256 x) internal pure returns (uint168 y) {\n    _assertNonOverflow(x == (y = uint168(x)));\n  }\n\n  function toUint176(uint256 x) internal pure returns (uint176 y) {\n    _assertNonOverflow(x == (y = uint176(x)));\n  }\n\n  function toUint184(uint256 x) internal pure returns (uint184 y) {\n    _assertNonOverflow(x == (y = uint184(x)));\n  }\n\n  function toUint192(uint256 x) internal pure returns (uint192 y) {\n    _assertNonOverflow(x == (y = uint192(x)));\n  }\n\n  function toUint200(uint256 x) internal pure returns (uint200 y) {\n    _assertNonOverflow(x == (y = uint200(x)));\n  }\n\n  function toUint208(uint256 x) internal pure returns (uint208 y) {\n    _assertNonOverflow(x == (y = uint208(x)));\n  }\n\n  function toUint216(uint256 x) internal pure returns (uint216 y) {\n    _assertNonOverflow(x == (y = uint216(x)));\n  }\n\n  function toUint224(uint256 x) internal pure returns (uint224 y) {\n    _assertNonOverflow(x == (y = uint224(x)));\n  }\n\n  function toUint232(uint256 x) internal pure returns (uint232 y) {\n    _assertNonOverflow(x == (y = uint232(x)));\n  }\n\n  function toUint240(uint256 x) internal pure returns (uint240 y) {\n    _assertNonOverflow(x == (y = uint240(x)));\n  }\n\n  function toUint248(uint256 x) internal pure returns (uint248 y) {\n    _assertNonOverflow(x == (y = uint248(x)));\n  }\n}\n"},{"file_path":"src/market/WildcatMarketWithdrawals.sol","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport './WildcatMarketBase.sol';\nimport '../libraries/LibERC20.sol';\nimport '../libraries/BoolUtils.sol';\n\ncontract WildcatMarketWithdrawals is WildcatMarketBase {\n  using LibERC20 for address;\n  using MathUtils for uint256;\n  using MathUtils for bool;\n  using SafeCastLib for uint256;\n  using BoolUtils for bool;\n\n  // ========================================================================== //\n  //                             Withdrawal Queries                             //\n  // ========================================================================== //\n\n  /**\n   * @dev Returns the expiry timestamp of every unpaid withdrawal batch.\n   */\n  function getUnpaidBatchExpiries() external view nonReentrantView returns (uint32[] memory) {\n    return _withdrawalData.unpaidBatches.values();\n  }\n\n  function getWithdrawalBatch(\n    uint32 expiry\n  ) external view nonReentrantView returns (WithdrawalBatch memory batch) {\n    (, uint32 pendingBatchExpiry, WithdrawalBatch memory pendingBatch) = _calculateCurrentState();\n    if ((expiry == pendingBatchExpiry).and(expiry > 0)) {\n      return pendingBatch;\n    }\n\n    WithdrawalBatch storage _batch = _withdrawalData.batches[expiry];\n    batch.scaledTotalAmount = _batch.scaledTotalAmount;\n    batch.scaledAmountBurned = _batch.scaledAmountBurned;\n    batch.normalizedAmountPaid = _batch.normalizedAmountPaid;\n  }\n\n  function getAccountWithdrawalStatus(\n    address accountAddress,\n    uint32 expiry\n  ) external view nonReentrantView returns (AccountWithdrawalStatus memory status) {\n    AccountWithdrawalStatus storage _status = _withdrawalData.accountStatuses[expiry][\n      accountAddress\n    ];\n    status.scaledAmount = _status.scaledAmount;\n    status.normalizedAmountWithdrawn = _status.normalizedAmountWithdrawn;\n  }\n\n  function getAvailableWithdrawalAmount(\n    address accountAddress,\n    uint32 expiry\n  ) external view nonReentrantView returns (uint256) {\n    if (expiry >= block.timestamp) {\n      revert_WithdrawalBatchNotExpired();\n    }\n    (, uint32 pendingBatchExpiry, WithdrawalBatch memory pendingBatch) = _calculateCurrentState();\n    WithdrawalBatch memory batch;\n    if (expiry == pendingBatchExpiry) {\n      batch = pendingBatch;\n    } else {\n      batch = _withdrawalData.batches[expiry];\n    }\n    AccountWithdrawalStatus memory status = _withdrawalData.accountStatuses[expiry][accountAddress];\n    // Rounding errors will lead to some dust accumulating in the batch, but the cost of\n    // executing a withdrawal will be lower for users.\n    uint256 previousTotalWithdrawn = status.normalizedAmountWithdrawn;\n    uint256 newTotalWithdrawn = uint256(batch.normalizedAmountPaid).mulDiv(\n      status.scaledAmount,\n      batch.scaledTotalAmount\n    );\n    return newTotalWithdrawn - previousTotalWithdrawn;\n  }\n\n  // ========================================================================== //\n  //                             Withdrawal Actions                             //\n  // ========================================================================== //\n\n  function _queueWithdrawal(\n    MarketState memory state,\n    Account memory account,\n    address accountAddress,\n    uint104 scaledAmount,\n    uint normalizedAmount,\n    uint baseCalldataSize\n  ) internal returns (uint32 expiry) {\n    // Cache batch expiry on the stack for gas savings\n    expiry = state.pendingWithdrawalExpiry;\n\n    // If there is no pending withdrawal batch, create a new one.\n    if (state.pendingWithdrawalExpiry == 0) {\n      // If the market is closed, use zero for withdrawal batch duration.\n      uint duration = state.isClosed.ternary(0, withdrawalBatchDuration);\n      expiry = uint32(block.timestamp + duration);\n      emit_WithdrawalBatchCreated(expiry);\n      state.pendingWithdrawalExpiry = expiry;\n    }\n\n    // Execute queueWithdrawal hook if enabled\n    hooks.onQueueWithdrawal(accountAddress, expiry, scaledAmount, state, baseCalldataSize);\n\n    // Reduce account's balance and emit transfer event\n    account.scaledBalance -= scaledAmount;\n    _accounts[accountAddress] = account;\n\n    emit_Transfer(accountAddress, address(this), normalizedAmount);\n\n    WithdrawalBatch memory batch = _withdrawalData.batches[expiry];\n\n    // Add scaled withdrawal amount to account withdrawal status, withdrawal batch and market state.\n    _withdrawalData.accountStatuses[expiry][accountAddress].scaledAmount += scaledAmount;\n    batch.scaledTotalAmount += scaledAmount;\n    state.scaledPendingWithdrawals += scaledAmount;\n\n    emit_WithdrawalQueued(expiry, accountAddress, scaledAmount, normalizedAmount);\n\n    // Burn as much of the withdrawal batch as possible with available liquidity.\n    uint256 availableLiquidity = batch.availableLiquidityForPendingBatch(state, totalAssets());\n    if (availableLiquidity > 0) {\n      _applyWithdrawalBatchPayment(batch, state, expiry, availableLiquidity);\n    }\n\n    // Update stored batch data\n    _withdrawalData.batches[expiry] = batch;\n\n    // Update stored state\n    _writeState(state);\n  }\n\n  /**\n   * @dev Create a withdrawal request for a lender.\n   */\n  function queueWithdrawal(\n    uint256 amount\n  ) external nonReentrant sphereXGuardExternal returns (uint32 expiry) {\n    MarketState memory state = _getUpdatedState();\n\n    uint104 scaledAmount = state.scaleAmount(amount).toUint104();\n    if (scaledAmount == 0) revert_NullBurnAmount();\n\n    // Cache account data\n    Account memory account = _getAccount(msg.sender);\n\n    return\n      _queueWithdrawal(state, account, msg.sender, scaledAmount, amount, _runtimeConstant(0x24));\n  }\n\n  /**\n   * @dev Queue a withdrawal for all of the caller's balance.\n   */\n  function queueFullWithdrawal()\n    external\n    nonReentrant\n    sphereXGuardExternal\n    returns (uint32 expiry)\n  {\n    MarketState memory state = _getUpdatedState();\n\n    // Cache account data\n    Account memory account = _getAccount(msg.sender);\n\n    uint104 scaledAmount = account.scaledBalance;\n    if (scaledAmount == 0) revert_NullBurnAmount();\n\n    uint256 normalizedAmount = state.normalizeAmount(scaledAmount);\n\n    return\n      _queueWithdrawal(\n        state,\n        account,\n        msg.sender,\n        scaledAmount,\n        normalizedAmount,\n        _runtimeConstant(0x04)\n      );\n  }\n\n  /**\n   * @dev Execute a pending withdrawal request for a batch that has expired.\n   *\n   *      Withdraws the proportional amount of the paid batch owed to\n   *      `accountAddress` which has not already been withdrawn.\n   *\n   *      If `accountAddress` is sanctioned, transfers the owed amount to\n   *      an escrow contract specific to the account and blocks the account.\n   *\n   *      Reverts if:\n   *      - `expiry >= block.timestamp`\n   *      -  `expiry` does not correspond to an existing withdrawal batch\n   *      - `accountAddress` has already withdrawn the full amount owed\n   */\n  function executeWithdrawal(\n    address accountAddress,\n    uint32 expiry\n  ) public nonReentrant sphereXGuardExternal returns (uint256) {\n    MarketState memory state = _getUpdatedState();\n    // Use an obfuscated constant for the base calldata size to prevent solc\n    // function specialization.\n    uint256 normalizedAmountWithdrawn = _executeWithdrawal(\n      state,\n      accountAddress,\n      expiry,\n      _runtimeConstant(0x44)\n    );\n    // Update stored state\n    _writeState(state);\n    return normalizedAmountWithdrawn;\n  }\n\n  function executeWithdrawals(\n    address[] calldata accountAddresses,\n    uint32[] calldata expiries\n  ) external nonReentrant sphereXGuardExternal returns (uint256[] memory amounts) {\n    if (accountAddresses.length != expiries.length) revert_InvalidArrayLength();\n\n    amounts = new uint256[](accountAddresses.length);\n\n    MarketState memory state = _getUpdatedState();\n\n    for (uint256 i = 0; i < accountAddresses.length; i++) {\n      // Use calldatasize() for baseCalldataSize to indicate no data should be passed as `extraData`\n      amounts[i] = _executeWithdrawal(state, accountAddresses[i], expiries[i], msg.data.length);\n    }\n    // Update stored state\n    _writeState(state);\n    return amounts;\n  }\n\n  function _executeWithdrawal(\n    MarketState memory state,\n    address accountAddress,\n    uint32 expiry,\n    uint baseCalldataSize\n  ) internal returns (uint256) {\n    WithdrawalBatch memory batch = _withdrawalData.batches[expiry];\n    if (expiry == state.pendingWithdrawalExpiry) revert_WithdrawalBatchNotExpired();\n\n    AccountWithdrawalStatus storage status = _withdrawalData.accountStatuses[expiry][\n      accountAddress\n    ];\n\n    uint128 newTotalWithdrawn = uint128(\n      MathUtils.mulDiv(batch.normalizedAmountPaid, status.scaledAmount, batch.scaledTotalAmount)\n    );\n\n    uint128 normalizedAmountWithdrawn = newTotalWithdrawn - status.normalizedAmountWithdrawn;\n\n    if (normalizedAmountWithdrawn == 0) revert_NullWithdrawalAmount();\n\n    hooks.onExecuteWithdrawal(accountAddress, normalizedAmountWithdrawn, state, baseCalldataSize);\n\n    status.normalizedAmountWithdrawn = newTotalWithdrawn;\n    state.normalizedUnclaimedWithdrawals -= normalizedAmountWithdrawn;\n\n    if (_isSanctioned(accountAddress)) {\n      // Get or create an escrow contract for the lender and transfer the owed amount to it.\n      // They will be unable to withdraw from the escrow until their sanctioned\n      // status is lifted on Chainalysis, or until the borrower overrides it.\n      address escrow = _createEscrowForUnderlyingAsset(accountAddress);\n      asset.safeTransfer(escrow, normalizedAmountWithdrawn);\n\n      // Emit `SanctionedAccountWithdrawalSentToEscrow` event using a custom emitter.\n      emit_SanctionedAccountWithdrawalSentToEscrow(\n        accountAddress,\n        escrow,\n        expiry,\n        normalizedAmountWithdrawn\n      );\n    } else {\n      asset.safeTransfer(accountAddress, normalizedAmountWithdrawn);\n    }\n\n    emit_WithdrawalExecuted(expiry, accountAddress, normalizedAmountWithdrawn);\n\n    return normalizedAmountWithdrawn;\n  }\n\n  function repayAndProcessUnpaidWithdrawalBatches(\n    uint256 repayAmount,\n    uint256 maxBatches\n  ) public nonReentrant sphereXGuardExternal {\n    // Repay before updating state to ensure the paid amount is counted towards\n    // any pending or unpaid withdrawals.\n    if (repayAmount > 0) {\n      asset.safeTransferFrom(msg.sender, address(this), repayAmount);\n      emit_DebtRepaid(msg.sender, repayAmount);\n    }\n\n    MarketState memory state = _getUpdatedState();\n    if (state.isClosed) revert_RepayToClosedMarket();\n\n    // Use an obfuscated constant for the base calldata size to prevent solc\n    // function specialization.\n    if (repayAmount > 0) hooks.onRepay(repayAmount, state, _runtimeConstant(0x44));\n\n    // Calculate assets available to process the first batch - will be updated after each batch\n    uint256 availableLiquidity = totalAssets() -\n      (state.normalizedUnclaimedWithdrawals + state.accruedProtocolFees);\n\n    // Get the maximum number of batches to process\n    uint256 numBatches = MathUtils.min(maxBatches, _withdrawalData.unpaidBatches.length());\n\n    uint256 i;\n    // Process up to `maxBatches` unpaid batches while there is available liquidity\n    while (i++ < numBatches && availableLiquidity > 0) {\n      // Process the next unpaid batch using available liquidity\n      uint256 normalizedAmountPaid = _processUnpaidWithdrawalBatch(state, availableLiquidity);\n      // Reduce liquidity available to next batch\n      availableLiquidity = availableLiquidity.satSub(normalizedAmountPaid);\n    }\n    _writeState(state);\n  }\n\n  function _processUnpaidWithdrawalBatch(\n    MarketState memory state,\n    uint256 availableLiquidity\n  ) internal returns (uint256 normalizedAmountPaid) {\n    // Get the next unpaid batch timestamp from storage (reverts if none)\n    uint32 expiry = _withdrawalData.unpaidBatches.first();\n\n    // Cache batch data in memory\n    WithdrawalBatch memory batch = _withdrawalData.batches[expiry];\n\n    // Pay up to the available liquidity to the batch\n    (, normalizedAmountPaid) = _applyWithdrawalBatchPayment(\n      batch,\n      state,\n      expiry,\n      availableLiquidity\n    );\n\n    // Update stored batch\n    _withdrawalData.batches[expiry] = batch;\n\n    // Remove batch from unpaid set if fully paid\n    if (batch.scaledTotalAmount == batch.scaledAmountBurned) {\n      _withdrawalData.unpaidBatches.shift();\n      emit_WithdrawalBatchClosed(expiry);\n    }\n  }\n}\n"},{"file_path":"src/spherex/SphereXProtectedErrors.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nfunction revert_SphereXOperatorRequired() pure {\n  assembly {\n    mstore(0, 0x4ee0b8f8)\n    revert(0x1c, 0x04)\n  }\n}\n\nfunction revert_SphereXAdminRequired() pure {\n  assembly {\n    mstore(0, 0x6222a550)\n    revert(0x1c, 0x04)\n  }\n}\n\nfunction revert_SphereXOperatorOrAdminRequired() pure {\n  assembly {\n    mstore(0, 0xb2dbeb59)\n    revert(0x1c, 0x04)\n  }\n}\n\nfunction revert_SphereXNotPendingAdmin() pure {\n  assembly {\n    mstore(0, 0x4d28a58e)\n    revert(0x1c, 0x04)\n  }\n}\n\nfunction revert_SphereXNotEngine() pure {\n  assembly {\n    mstore(0, 0x7dcb7ada)\n    revert(0x1c, 0x04)\n  }\n}\n"},{"file_path":"src/libraries/FunctionTypeCasts.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport { MarketParameters } from '../interfaces/WildcatStructsAndEnums.sol';\nimport { MarketState } from '../libraries/MarketState.sol';\nimport { WithdrawalBatch } from '../libraries/Withdrawal.sol';\n\n/**\n * @dev Type-casts to convert functions returning raw (uint) pointers\n *      to functions returning memory pointers of specific types.\n *\n *      Used to get around solc's over-allocation of memory when\n *      dynamic return parameters are re-assigned.\n *\n *      With `viaIR` enabled, calling any of these functions is a noop.\n */\nlibrary FunctionTypeCasts {\n  /**\n   * @dev Function type cast to avoid duplicate declaration/allocation\n   *      of MarketState return parameter.\n   */\n  function asReturnsMarketState(\n    function() internal view returns (uint256) fnIn\n  ) internal pure returns (function() internal view returns (MarketState memory) fnOut) {\n    assembly {\n      fnOut := fnIn\n    }\n  }\n\n  /**\n   * @dev Function type cast to avoid duplicate declaration/allocation\n   *      of MarketState and WithdrawalBatch return parameters.\n   */\n  function asReturnsPointers(\n    function() internal view returns (MarketState memory, uint32, WithdrawalBatch memory) fnIn\n  ) internal pure returns (function() internal view returns (uint256, uint32, uint256) fnOut) {\n    assembly {\n      fnOut := fnIn\n    }\n  }\n\n  /**\n   * @dev Function type cast to avoid duplicate declaration/allocation\n   *      of manually allocated MarketParameters in market constructor.\n   */\n  function asReturnsMarketParameters(\n    function() internal view returns (uint256) fnIn\n  ) internal pure returns (function() internal view returns (MarketParameters memory) fnOut) {\n    assembly {\n      fnOut := fnIn\n    }\n  }\n}\n"},{"file_path":"src/access/IHooks.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport '../types/HooksConfig.sol';\nimport '../libraries/MarketState.sol';\nimport '../interfaces/WildcatStructsAndEnums.sol';\n\nabstract contract IHooks {\n  error CallerNotFactory();\n\n  address public immutable factory;\n\n  constructor() {\n    factory = msg.sender;\n  }\n\n  /// @dev Returns the version string of the hooks contract.\n  ///      Used to determine what the contract does and how `extraData` is interpreted.\n  function version() external view virtual returns (string memory);\n\n  /// @dev Returns the HooksDeploymentConfig type which contains the sets\n  ///      of optional and required hooks that this contract implements.\n  function config() external view virtual returns (HooksDeploymentConfig);\n\n  function onCreateMarket(\n    address deployer,\n    address marketAddress,\n    DeployMarketInputs calldata parameters,\n    bytes calldata extraData\n  ) external returns (HooksConfig) {\n    if (msg.sender != factory) revert CallerNotFactory();\n    return _onCreateMarket(deployer, marketAddress, parameters, extraData);\n  }\n\n  function _onCreateMarket(\n    address deployer,\n    address marketAddress,\n    DeployMarketInputs calldata parameters,\n    bytes calldata extraData\n  ) internal virtual returns (HooksConfig);\n\n  function onDeposit(\n    address lender,\n    uint256 scaledAmount,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onQueueWithdrawal(\n    address lender,\n    uint32 expiry,\n    uint scaledAmount,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onExecuteWithdrawal(\n    address lender,\n    uint128 normalizedAmountWithdrawn,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onTransfer(\n    address caller,\n    address from,\n    address to,\n    uint scaledAmount,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onBorrow(\n    uint normalizedAmount,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onRepay(\n    uint normalizedAmount,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onCloseMarket(\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onNukeFromOrbit(\n    address lender,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onSetMaxTotalSupply(\n    uint256 maxTotalSupply,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n\n  function onSetAnnualInterestAndReserveRatioBips(\n    uint16 annualInterestBips,\n    uint16 reserveRatioBips,\n    MarketState calldata intermediateState,\n    bytes calldata extraData\n  ) external virtual returns (uint16 updatedAnnualInterestBips, uint16 updatedReserveRatioBips);\n\n  function onSetProtocolFeeBips(\n    uint16 protocolFeeBips,\n    MarketState memory intermediateState,\n    bytes calldata extraData\n  ) external virtual;\n}\n"},{"file_path":"src/market/WildcatMarketToken.sol","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport './WildcatMarketBase.sol';\n\ncontract WildcatMarketToken is WildcatMarketBase {\n  using SafeCastLib for uint256;\n  using FunctionTypeCasts for *;\n\n  // ========================================================================== //\n  //                                ERC20 Queries                               //\n  // ========================================================================== //\n\n  mapping(address => mapping(address => uint256)) public allowance;\n\n  /// @notice Returns the normalized balance of `account` with interest.\n  function balanceOf(address account) public view virtual nonReentrantView returns (uint256) {\n    return\n      _calculateCurrentStatePointers.asReturnsMarketState()().normalizeAmount(\n        _accounts[account].scaledBalance\n      );\n  }\n\n  /// @notice Returns the normalized total supply with interest.\n  function totalSupply() external view virtual nonReentrantView returns (uint256) {\n    return _calculateCurrentStatePointers.asReturnsMarketState()().totalSupply();\n  }\n\n  // ========================================================================== //\n  //                                ERC20 Actions                               //\n  // ========================================================================== //\n\n  function approve(\n    address spender,\n    uint256 amount\n  ) external virtual nonReentrant sphereXGuardExternal returns (bool) {\n    _approve(msg.sender, spender, amount);\n    return true;\n  }\n\n  function transfer(\n    address to,\n    uint256 amount\n  ) external virtual nonReentrant sphereXGuardExternal returns (bool) {\n    _transfer(msg.sender, to, amount, 0x44);\n    return true;\n  }\n\n  function transferFrom(\n    address from,\n    address to,\n    uint256 amount\n  ) external virtual nonReentrant sphereXGuardExternal returns (bool) {\n    uint256 allowed = allowance[from][msg.sender];\n\n    // Saves gas for unlimited approvals.\n    if (allowed != type(uint256).max) {\n      uint256 newAllowance = allowed - amount;\n      _approve(from, msg.sender, newAllowance);\n    }\n\n    _transfer(from, to, amount, 0x64);\n\n    return true;\n  }\n\n  function _approve(address approver, address spender, uint256 amount) internal virtual {\n    allowance[approver][spender] = amount;\n    emit_Approval(approver, spender, amount);\n  }\n\n  function _transfer(\n    address from,\n    address to,\n    uint256 amount,\n    uint baseCalldataSize\n  ) internal virtual {\n    MarketState memory state = _getUpdatedState();\n    uint104 scaledAmount = state.scaleAmount(amount).toUint104();\n\n    if (scaledAmount == 0) revert_NullTransferAmount();\n\n    hooks.onTransfer(from, to, scaledAmount, state, baseCalldataSize);\n\n    Account memory fromAccount = _getAccount(from);\n    fromAccount.scaledBalance -= scaledAmount;\n    _accounts[from] = fromAccount;\n\n    Account memory toAccount = _getAccount(to);\n    toAccount.scaledBalance += scaledAmount;\n    _accounts[to] = toAccount;\n\n    _writeState(state);\n    emit_Transfer(from, to, amount);\n  }\n}\n"},{"file_path":"src/types/HooksConfig.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport '../access/IHooks.sol';\nimport '../libraries/MarketState.sol';\n\ntype HooksConfig is uint256;\n\nHooksConfig constant EmptyHooksConfig = HooksConfig.wrap(0);\n\nusing LibHooksConfig for HooksConfig global;\nusing LibHooksConfig for HooksDeploymentConfig global;\n\n// Type that contains only the flags for a specific hooks contract, with one\n// set of flags for optional hooks and one set of flags for required hooks.\ntype HooksDeploymentConfig is uint256;\n\nfunction encodeHooksDeploymentConfig(\n  HooksConfig optionalFlags,\n  HooksConfig requiredFlags\n) pure returns (HooksDeploymentConfig flags) {\n  assembly {\n    let cleanedOptionalFlags := and(0xffff, shr(0x50, optionalFlags))\n    let cleanedRequiredFlags := and(0xffff0000, shr(0x40, requiredFlags))\n    flags := or(cleanedOptionalFlags, cleanedRequiredFlags)\n  }\n}\n\n// --------------------- Bits after hook activation flag -------------------- //\n\n// Offsets are from the right\n\nuint256 constant Bit_Enabled_Deposit = 95;\nuint256 constant Bit_Enabled_QueueWithdrawal = 94;\nuint256 constant Bit_Enabled_ExecuteWithdrawal = 93;\nuint256 constant Bit_Enabled_Transfer = 92;\nuint256 constant Bit_Enabled_Borrow = 91;\nuint256 constant Bit_Enabled_Repay = 90;\nuint256 constant Bit_Enabled_CloseMarket = 89;\nuint256 constant Bit_Enabled_NukeFromOrbit = 88;\nuint256 constant Bit_Enabled_SetMaxTotalSupply = 87;\nuint256 constant Bit_Enabled_SetAnnualInterestAndReserveRatioBips = 86;\nuint256 constant Bit_Enabled_SetProtocolFeeBips = 85;\n\nuint256 constant MarketStateSize = 0x01c0;\n\nfunction encodeHooksConfig(\n  address hooksAddress,\n  bool useOnDeposit,\n  bool useOnQueueWithdrawal,\n  bool useOnExecuteWithdrawal,\n  bool useOnTransfer,\n  bool useOnBorrow,\n  bool useOnRepay,\n  bool useOnCloseMarket,\n  bool useOnNukeFromOrbit,\n  bool useOnSetMaxTotalSupply,\n  bool useOnSetAnnualInterestAndReserveRatioBips,\n  bool useOnSetProtocolFeeBips\n) pure returns (HooksConfig hooks) {\n  assembly {\n    hooks := shl(96, hooksAddress)\n    hooks := or(hooks, shl(Bit_Enabled_Deposit, useOnDeposit))\n    hooks := or(hooks, shl(Bit_Enabled_QueueWithdrawal, useOnQueueWithdrawal))\n    hooks := or(hooks, shl(Bit_Enabled_ExecuteWithdrawal, useOnExecuteWithdrawal))\n    hooks := or(hooks, shl(Bit_Enabled_Transfer, useOnTransfer))\n    hooks := or(hooks, shl(Bit_Enabled_Borrow, useOnBorrow))\n    hooks := or(hooks, shl(Bit_Enabled_Repay, useOnRepay))\n    hooks := or(hooks, shl(Bit_Enabled_CloseMarket, useOnCloseMarket))\n    hooks := or(hooks, shl(Bit_Enabled_NukeFromOrbit, useOnNukeFromOrbit))\n    hooks := or(hooks, shl(Bit_Enabled_SetMaxTotalSupply, useOnSetMaxTotalSupply))\n    hooks := or(\n      hooks,\n      shl(\n        Bit_Enabled_SetAnnualInterestAndReserveRatioBips,\n        useOnSetAnnualInterestAndReserveRatioBips\n      )\n    )\n    hooks := or(hooks, shl(Bit_Enabled_SetProtocolFeeBips, useOnSetProtocolFeeBips))\n  }\n}\n\nlibrary LibHooksConfig {\n  function setHooksAddress(\n    HooksConfig hooks,\n    address _hooksAddress\n  ) internal pure returns (HooksConfig updatedHooks) {\n    assembly {\n      // Shift twice to clear the address\n      updatedHooks := shr(160, shl(160, hooks))\n      // Set the new address\n      updatedHooks := or(updatedHooks, shl(96, _hooksAddress))\n    }\n  }\n\n  /**\n   * @dev Create a merged HooksConfig with the shared flags of `a` and `b`\n   *      and the address of `a`.\n   */\n  function mergeSharedFlags(\n    HooksConfig a,\n    HooksConfig b\n  ) internal pure returns (HooksConfig merged) {\n    assembly {\n      let addressA := shl(0x60, shr(0x60, a))\n      let flagsA := shl(0xa0, a)\n      let flagsB := shl(0xa0, b)\n      let mergedFlags := shr(0xa0, and(flagsA, flagsB))\n      merged := or(addressA, mergedFlags)\n    }\n  }\n\n  /**\n   * @dev Create a merged HooksConfig with the shared flags of `a` and `b`\n   *      and the address of `a`.\n   */\n  function mergeAllFlags(HooksConfig a, HooksConfig b) internal pure returns (HooksConfig merged) {\n    assembly {\n      let addressA := shl(0x60, shr(0x60, a))\n      let flagsA := shl(0xa0, a)\n      let flagsB := shl(0xa0, b)\n      let mergedFlags := shr(0xa0, or(flagsA, flagsB))\n      merged := or(addressA, mergedFlags)\n    }\n  }\n\n  function mergeFlags(\n    HooksConfig config,\n    HooksDeploymentConfig flags\n  ) internal pure returns (HooksConfig merged) {\n    assembly {\n      let _hooksAddress := shl(96, shr(96, config))\n      // Position flags at the end of the word\n      let configFlags := shr(0x50, config)\n      // Optional flags are already in the right position, required flags must be\n      // shifted to align with the other flags. The leading and trailing bits for all 3\n      // words will be masked out at the end\n      let _optionalFlags := flags\n      let _requiredFlags := shr(0x10, flags)\n      let mergedFlags := and(0xffff, or(and(configFlags, _optionalFlags), _requiredFlags))\n\n      merged := or(_hooksAddress, shl(0x50, mergedFlags))\n    }\n  }\n\n  function optionalFlags(HooksDeploymentConfig flags) internal pure returns (HooksConfig config) {\n    assembly {\n      config := shl(0x50, and(flags, 0xffff))\n    }\n  }\n\n  function requiredFlags(HooksDeploymentConfig flags) internal pure returns (HooksConfig config) {\n    assembly {\n      config := shl(0x40, and(flags, 0xffff0000))\n    }\n  }\n\n  // ========================================================================== //\n  //                              Parameter Readers                             //\n  // ========================================================================== //\n\n  function readFlag(HooksConfig hooks, uint256 bitsAfter) internal pure returns (bool flagged) {\n    assembly {\n      flagged := and(shr(bitsAfter, hooks), 1)\n    }\n  }\n\n  function setFlag(\n    HooksConfig hooks,\n    uint256 bitsAfter\n  ) internal pure returns (HooksConfig updatedHooks) {\n    assembly {\n      updatedHooks := or(hooks, shl(bitsAfter, 1))\n    }\n  }\n\n  function clearFlag(\n    HooksConfig hooks,\n    uint256 bitsAfter\n  ) internal pure returns (HooksConfig updatedHooks) {\n    assembly {\n      updatedHooks := and(hooks, not(shl(bitsAfter, 1)))\n    }\n  }\n\n  /// @dev Address of the hooks contract\n  function hooksAddress(HooksConfig hooks) internal pure returns (address _hooks) {\n    assembly {\n      _hooks := shr(96, hooks)\n    }\n  }\n\n  /// @dev Whether to call hook contract for deposit\n  function useOnDeposit(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_Deposit);\n  }\n\n  /// @dev Whether to call hook contract for queueWithdrawal\n  function useOnQueueWithdrawal(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_QueueWithdrawal);\n  }\n\n  /// @dev Whether to call hook contract for executeWithdrawal\n  function useOnExecuteWithdrawal(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_ExecuteWithdrawal);\n  }\n\n  /// @dev Whether to call hook contract for transfer\n  function useOnTransfer(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_Transfer);\n  }\n\n  /// @dev Whether to call hook contract for borrow\n  function useOnBorrow(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_Borrow);\n  }\n\n  /// @dev Whether to call hook contract for repay\n  function useOnRepay(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_Repay);\n  }\n\n  /// @dev Whether to call hook contract for closeMarket\n  function useOnCloseMarket(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_CloseMarket);\n  }\n\n  /// @dev Whether to call hook contract when account sanctioned\n  function useOnNukeFromOrbit(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_NukeFromOrbit);\n  }\n\n  /// @dev Whether to call hook contract for setMaxTotalSupply\n  function useOnSetMaxTotalSupply(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_SetMaxTotalSupply);\n  }\n\n  /// @dev Whether to call hook contract for setAnnualInterestAndReserveRatioBips\n  function useOnSetAnnualInterestAndReserveRatioBips(\n    HooksConfig hooks\n  ) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_SetAnnualInterestAndReserveRatioBips);\n  }\n\n  /// @dev Whether to call hook contract for setProtocolFeeBips\n  function useOnSetProtocolFeeBips(HooksConfig hooks) internal pure returns (bool) {\n    return hooks.readFlag(Bit_Enabled_SetProtocolFeeBips);\n  }\n\n  // ========================================================================== //\n  //                              Hook for deposit                              //\n  // ========================================================================== //\n\n  uint256 internal constant DepositCalldataSize = 0x24;\n  // Size of lender + scaledAmount + state + extraData.offset + extraData.length\n  uint256 internal constant DepositHook_Base_Size = 0x0244;\n  uint256 internal constant DepositHook_ScaledAmount_Offset = 0x20;\n  uint256 internal constant DepositHook_State_Offset = 0x40;\n  uint256 internal constant DepositHook_ExtraData_Head_Offset = 0x200;\n  uint256 internal constant DepositHook_ExtraData_Length_Offset = 0x0220;\n  uint256 internal constant DepositHook_ExtraData_TailOffset = 0x0240;\n\n  function onDeposit(\n    HooksConfig self,\n    address lender,\n    uint256 scaledAmount,\n    MarketState memory state\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onDepositSelector = uint32(IHooks.onDeposit.selector);\n    if (self.useOnDeposit()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), DepositCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onDeposit`\n        mstore(cdPointer, onDepositSelector)\n        // Write `lender` to hook calldata\n        mstore(headPointer, lender)\n        // Write `scaledAmount` to hook calldata\n        mstore(add(headPointer, DepositHook_ScaledAmount_Offset), scaledAmount)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, DepositHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, DepositHook_ExtraData_Head_Offset),\n          DepositHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, DepositHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, DepositHook_ExtraData_TailOffset),\n          DepositCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(DepositHook_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                          Hook for queueWithdrawal                          //\n  // ========================================================================== //\n\n  // Size of lender + scaledAmount + state + extraData.offset + extraData.length\n  uint256 internal constant QueueWithdrawalHook_Base_Size = 0x0264;\n  uint256 internal constant QueueWithdrawalHook_Expiry_Offset = 0x20;\n  uint256 internal constant QueueWithdrawalHook_ScaledAmount_Offset = 0x40;\n  uint256 internal constant QueueWithdrawalHook_State_Offset = 0x60;\n  uint256 internal constant QueueWithdrawalHook_ExtraData_Head_Offset = 0x220;\n  uint256 internal constant QueueWithdrawalHook_ExtraData_Length_Offset = 0x0240;\n  uint256 internal constant QueueWithdrawalHook_ExtraData_TailOffset = 0x0260;\n\n  function onQueueWithdrawal(\n    HooksConfig self,\n    address lender,\n    uint32 expiry,\n    uint256 scaledAmount,\n    MarketState memory state,\n    uint256 baseCalldataSize\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onQueueWithdrawalSelector = uint32(IHooks.onQueueWithdrawal.selector);\n    if (self.useOnQueueWithdrawal()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), baseCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onQueueWithdrawal`\n        mstore(cdPointer, onQueueWithdrawalSelector)\n        // Write `lender` to hook calldata\n        mstore(headPointer, lender)\n        // Write `expiry` to hook calldata\n        mstore(add(headPointer, QueueWithdrawalHook_Expiry_Offset), expiry)\n        // Write `scaledAmount` to hook calldata\n        mstore(add(headPointer, QueueWithdrawalHook_ScaledAmount_Offset), scaledAmount)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, QueueWithdrawalHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, QueueWithdrawalHook_ExtraData_Head_Offset),\n          QueueWithdrawalHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, QueueWithdrawalHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, QueueWithdrawalHook_ExtraData_TailOffset),\n          baseCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(QueueWithdrawalHook_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                         Hook for executeWithdrawal                         //\n  // ========================================================================== //\n\n  // Size of lender + scaledAmount + state + extraData.offset + extraData.length\n  uint256 internal constant ExecuteWithdrawalHook_Base_Size = 0x0244;\n  uint256 internal constant ExecuteWithdrawalHook_ScaledAmount_Offset = 0x20;\n  uint256 internal constant ExecuteWithdrawalHook_State_Offset = 0x40;\n  uint256 internal constant ExecuteWithdrawalHook_ExtraData_Head_Offset = 0x0200;\n  uint256 internal constant ExecuteWithdrawalHook_ExtraData_Length_Offset = 0x0220;\n  uint256 internal constant ExecuteWithdrawalHook_ExtraData_TailOffset = 0x0240;\n\n  function onExecuteWithdrawal(\n    HooksConfig self,\n    address lender,\n    uint256 scaledAmount,\n    MarketState memory state,\n    uint256 baseCalldataSize\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onExecuteWithdrawalSelector = uint32(IHooks.onExecuteWithdrawal.selector);\n    if (self.useOnExecuteWithdrawal()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), baseCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onExecuteWithdrawal`\n        mstore(cdPointer, onExecuteWithdrawalSelector)\n        // Write `lender` to hook calldata\n        mstore(headPointer, lender)\n        // Write `scaledAmount` to hook calldata\n        mstore(add(headPointer, ExecuteWithdrawalHook_ScaledAmount_Offset), scaledAmount)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, ExecuteWithdrawalHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, ExecuteWithdrawalHook_ExtraData_Head_Offset),\n          ExecuteWithdrawalHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, ExecuteWithdrawalHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, ExecuteWithdrawalHook_ExtraData_TailOffset),\n          baseCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(ExecuteWithdrawalHook_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                              Hook for transfer                             //\n  // ========================================================================== //\n\n  // Size of caller + from + to + scaledAmount + state + extraData.offset + extraData.length\n  uint256 internal constant TransferHook_Base_Size = 0x0284;\n  uint256 internal constant TransferHook_From_Offset = 0x20;\n  uint256 internal constant TransferHook_To_Offset = 0x40;\n  uint256 internal constant TransferHook_ScaledAmount_Offset = 0x60;\n  uint256 internal constant TransferHook_State_Offset = 0x80;\n  uint256 internal constant TransferHook_ExtraData_Head_Offset = 0x240;\n  uint256 internal constant TransferHook_ExtraData_Length_Offset = 0x0260;\n  uint256 internal constant TransferHook_ExtraData_TailOffset = 0x0280;\n\n  function onTransfer(\n    HooksConfig self,\n    address from,\n    address to,\n    uint256 scaledAmount,\n    MarketState memory state,\n    uint256 baseCalldataSize\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onTransferSelector = uint32(IHooks.onTransfer.selector);\n    if (self.useOnTransfer()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), baseCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onTransfer`\n        mstore(cdPointer, onTransferSelector)\n        // Write `caller` to hook calldata\n        mstore(headPointer, caller())\n        // Write `from` to hook calldata\n        mstore(add(headPointer, TransferHook_From_Offset), from)\n        // Write `to` to hook calldata\n        mstore(add(headPointer, TransferHook_To_Offset), to)\n        // Write `scaledAmount` to hook calldata\n        mstore(add(headPointer, TransferHook_ScaledAmount_Offset), scaledAmount)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, TransferHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, TransferHook_ExtraData_Head_Offset),\n          TransferHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, TransferHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, TransferHook_ExtraData_TailOffset),\n          baseCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(TransferHook_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                               Hook for borrow                              //\n  // ========================================================================== //\n\n  uint256 internal constant BorrowCalldataSize = 0x24;\n  // Size of normalizedAmount + state + extraData.offset + extraData.length\n  uint256 internal constant BorrowHook_Base_Size = 0x0224;\n  uint256 internal constant BorrowHook_State_Offset = 0x20;\n  uint256 internal constant BorrowHook_ExtraData_Head_Offset = 0x01e0;\n  uint256 internal constant BorrowHook_ExtraData_Length_Offset = 0x0200;\n  uint256 internal constant BorrowHook_ExtraData_TailOffset = 0x0220;\n\n  function onBorrow(HooksConfig self, uint256 normalizedAmount, MarketState memory state) internal {\n    address target = self.hooksAddress();\n    uint32 onBorrowSelector = uint32(IHooks.onBorrow.selector);\n    if (self.useOnBorrow()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), BorrowCalldataSize)\n        let ptr := mload(0x40)\n        let headPointer := add(ptr, 0x20)\n\n        mstore(ptr, onBorrowSelector)\n        // Copy `normalizedAmount` to hook calldata\n        mstore(headPointer, normalizedAmount)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, BorrowHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, BorrowHook_ExtraData_Head_Offset),\n          BorrowHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, BorrowHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, BorrowHook_ExtraData_TailOffset),\n          BorrowCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(RepayHook_Base_Size, extraCalldataBytes)\n        if iszero(call(gas(), target, 0, add(ptr, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                               Hook for repay                               //\n  // ========================================================================== //\n\n  // Size of normalizedAmount + state + extraData.offset + extraData.length\n  uint256 internal constant RepayHook_Base_Size = 0x0224;\n  uint256 internal constant RepayHook_State_Offset = 0x20;\n  uint256 internal constant RepayHook_ExtraData_Head_Offset = 0x01e0;\n  uint256 internal constant RepayHook_ExtraData_Length_Offset = 0x0200;\n  uint256 internal constant RepayHook_ExtraData_TailOffset = 0x0220;\n\n  function onRepay(\n    HooksConfig self,\n    uint256 normalizedAmount,\n    MarketState memory state,\n    uint256 baseCalldataSize\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onRepaySelector = uint32(IHooks.onRepay.selector);\n    if (self.useOnRepay()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), baseCalldataSize)\n        let ptr := mload(0x40)\n        let headPointer := add(ptr, 0x20)\n\n        mstore(ptr, onRepaySelector)\n        // Copy `normalizedAmount` to hook calldata\n        mstore(headPointer, normalizedAmount)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, RepayHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(add(headPointer, RepayHook_ExtraData_Head_Offset), RepayHook_ExtraData_Length_Offset)\n        // Write length for `extraData`\n        mstore(add(headPointer, RepayHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, RepayHook_ExtraData_TailOffset),\n          baseCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(RepayHook_Base_Size, extraCalldataBytes)\n        if iszero(call(gas(), target, 0, add(ptr, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                            Hook for closeMarket                            //\n  // ========================================================================== //\n\n  // Size of calldata to `market.closeMarket`\n  uint256 internal constant CloseMarketCalldataSize = 0x04;\n\n  // Base size of calldata for `hooks.onCloseMarket()`\n  uint256 internal constant CloseMarketHook_Base_Size = 0x0204;\n  uint256 internal constant CloseMarketHook_ExtraData_Head_Offset = MarketStateSize;\n  uint256 internal constant CloseMarketHook_ExtraData_Length_Offset = 0x01e0;\n  uint256 internal constant CloseMarketHook_ExtraData_TailOffset = 0x0200;\n\n  function onCloseMarket(HooksConfig self, MarketState memory state) internal {\n    address target = self.hooksAddress();\n    uint32 onCloseMarketSelector = uint32(IHooks.onCloseMarket.selector);\n    if (self.useOnCloseMarket()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), CloseMarketCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onCloseMarket`\n        mstore(cdPointer, onCloseMarketSelector)\n        // Copy market state to hook calldata\n        mcopy(headPointer, state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, CloseMarketHook_ExtraData_Head_Offset),\n          CloseMarketHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, CloseMarketHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, CloseMarketHook_ExtraData_TailOffset),\n          CloseMarketCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(CloseMarketHook_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                         Hook for setMaxTotalSupply                         //\n  // ========================================================================== //\n\n  uint256 internal constant SetMaxTotalSupplyCalldataSize = 0x24;\n  // Size of maxTotalSupply + state + extraData.offset + extraData.length\n  uint256 internal constant SetMaxTotalSupplyHook_Base_Size = 0x0224;\n  uint256 internal constant SetMaxTotalSupplyHook_State_Offset = 0x20;\n  uint256 internal constant SetMaxTotalSupplyHook_ExtraData_Head_Offset = 0x01e0;\n  uint256 internal constant SetMaxTotalSupplyHook_ExtraData_Length_Offset = 0x0200;\n  uint256 internal constant SetMaxTotalSupplyHook_ExtraData_TailOffset = 0x0220;\n\n  function onSetMaxTotalSupply(\n    HooksConfig self,\n    uint256 maxTotalSupply,\n    MarketState memory state\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onSetMaxTotalSupplySelector = uint32(IHooks.onSetMaxTotalSupply.selector);\n    if (self.useOnSetMaxTotalSupply()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), SetMaxTotalSupplyCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onSetMaxTotalSupply`\n        mstore(cdPointer, onSetMaxTotalSupplySelector)\n        // Write `maxTotalSupply` to hook calldata\n        mstore(headPointer, maxTotalSupply)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, SetMaxTotalSupplyHook_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, SetMaxTotalSupplyHook_ExtraData_Head_Offset),\n          SetMaxTotalSupplyHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, SetMaxTotalSupplyHook_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, SetMaxTotalSupplyHook_ExtraData_TailOffset),\n          SetMaxTotalSupplyCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(SetMaxTotalSupplyHook_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                       Hook for setAnnualInterestBips                       //\n  // ========================================================================== //\n\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsCalldataSize = 0x44;\n  // Size of annualInterestBips + state + extraData.offset + extraData.length\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsHook_Base_Size = 0x0244;\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsHook_ReserveRatioBits_Offset = 0x20;\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsHook_State_Offset = 0x40;\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsHook_ExtraData_Head_Offset = 0x0200;\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsHook_ExtraData_Length_Offset =\n    0x0220;\n  uint256 internal constant SetAnnualInterestAndReserveRatioBipsHook_ExtraData_TailOffset = 0x0240;\n\n  function onSetAnnualInterestAndReserveRatioBips(\n    HooksConfig self,\n    uint16 annualInterestBips,\n    uint16 reserveRatioBips,\n    MarketState memory state\n  ) internal returns (uint16 newAnnualInterestBips, uint16 newReserveRatioBips) {\n    address target = self.hooksAddress();\n    uint32 onSetAnnualInterestBipsSelector = uint32(\n      IHooks.onSetAnnualInterestAndReserveRatioBips.selector\n    );\n    if (self.useOnSetAnnualInterestAndReserveRatioBips()) {\n      assembly {\n        let extraCalldataBytes := sub(\n          calldatasize(),\n          SetAnnualInterestAndReserveRatioBipsCalldataSize\n        )\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onSetAnnualInterestBips`\n        mstore(cdPointer, onSetAnnualInterestBipsSelector)\n        // Write `annualInterestBips` to hook calldata\n        mstore(headPointer, annualInterestBips)\n        // Write `reserveRatioBips` to hook calldata\n        mstore(\n          add(headPointer, SetAnnualInterestAndReserveRatioBipsHook_ReserveRatioBits_Offset),\n          reserveRatioBips\n        )\n        // Copy market state to hook calldata\n        mcopy(\n          add(headPointer, SetAnnualInterestAndReserveRatioBipsHook_State_Offset),\n          state,\n          MarketStateSize\n        )\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, SetAnnualInterestAndReserveRatioBipsHook_ExtraData_Head_Offset),\n          SetAnnualInterestAndReserveRatioBipsHook_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(\n          add(headPointer, SetAnnualInterestAndReserveRatioBipsHook_ExtraData_Length_Offset),\n          extraCalldataBytes\n        )\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, SetAnnualInterestAndReserveRatioBipsHook_ExtraData_TailOffset),\n          SetAnnualInterestAndReserveRatioBipsCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(SetAnnualInterestAndReserveRatioBipsHook_Base_Size, extraCalldataBytes)\n\n        // Returndata is expected to have the new values for `annualInterestBips` and `reserveRatioBips`\n        if or(\n          lt(returndatasize(), 0x40),\n          iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0x40))\n        ) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n\n        newAnnualInterestBips := and(mload(0), 0xffff)\n        newReserveRatioBips := and(mload(0x20), 0xffff)\n      }\n    } else {\n      (newAnnualInterestBips, newReserveRatioBips) = (annualInterestBips, reserveRatioBips);\n    }\n  }\n\n  // ========================================================================== //\n  //                     Hook for protocol fee bips updated                     //\n  // ========================================================================== //\n\n  uint256 internal constant SetProtocolFeeBipsCalldataSize = 0x24;\n  // Size of protocolFeeBips + state + extraData.offset + extraData.length\n  uint256 internal constant SetProtocolFeeBips_Base_Size = 0x0224;\n  uint256 internal constant SetProtocolFeeBips_State_Offset = 0x20;\n  uint256 internal constant SetProtocolFeeBips_ExtraData_Head_Offset = 0x01e0;\n  uint256 internal constant SetProtocolFeeBips_ExtraData_Length_Offset = 0x0200;\n  uint256 internal constant SetProtocolFeeBips_ExtraData_TailOffset = 0x0220;\n\n  function onSetProtocolFeeBips(\n    HooksConfig self,\n    uint protocolFeeBips,\n    MarketState memory state\n  ) internal {\n    address target = self.hooksAddress();\n    uint32 onSetProtocolFeeBipsSelector = uint32(IHooks.onSetProtocolFeeBips.selector);\n    if (self.useOnSetProtocolFeeBips()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), SetProtocolFeeBipsCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onSetProtocolFeeBips`\n        mstore(cdPointer, onSetProtocolFeeBipsSelector)\n        // Write `protocolFeeBips` to hook calldata\n        mstore(headPointer, protocolFeeBips)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, SetProtocolFeeBips_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, SetProtocolFeeBips_ExtraData_Head_Offset),\n          SetProtocolFeeBips_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, SetProtocolFeeBips_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, SetProtocolFeeBips_ExtraData_TailOffset),\n          SetProtocolFeeBipsCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(SetProtocolFeeBips_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                       Hook for assets sent to escrow                       //\n  // ========================================================================== //\n\n  uint256 internal constant NukeFromOrbitCalldataSize = 0x24;\n  // Size of lender + state + extraData.offset + extraData.length\n  uint256 internal constant NukeFromOrbit_Base_Size = 0x0224;\n  uint256 internal constant NukeFromOrbit_State_Offset = 0x20;\n  uint256 internal constant NukeFromOrbit_ExtraData_Head_Offset = 0x01e0;\n  uint256 internal constant NukeFromOrbit_ExtraData_Length_Offset = 0x0200;\n  uint256 internal constant NukeFromOrbit_ExtraData_TailOffset = 0x0220;\n\n  function onNukeFromOrbit(HooksConfig self, address lender, MarketState memory state) internal {\n    address target = self.hooksAddress();\n    uint32 onNukeFromOrbitSelector = uint32(IHooks.onNukeFromOrbit.selector);\n    if (self.useOnNukeFromOrbit()) {\n      assembly {\n        let extraCalldataBytes := sub(calldatasize(), NukeFromOrbitCalldataSize)\n        let cdPointer := mload(0x40)\n        let headPointer := add(cdPointer, 0x20)\n        // Write selector for `onNukeFromOrbit`\n        mstore(cdPointer, onNukeFromOrbitSelector)\n        // Write `lender` to hook calldata\n        mstore(headPointer, lender)\n        // Copy market state to hook calldata\n        mcopy(add(headPointer, NukeFromOrbit_State_Offset), state, MarketStateSize)\n        // Write bytes offset for `extraData`\n        mstore(\n          add(headPointer, NukeFromOrbit_ExtraData_Head_Offset),\n          NukeFromOrbit_ExtraData_Length_Offset\n        )\n        // Write length for `extraData`\n        mstore(add(headPointer, NukeFromOrbit_ExtraData_Length_Offset), extraCalldataBytes)\n        // Copy `extraData` from end of calldata to hook calldata\n        calldatacopy(\n          add(headPointer, NukeFromOrbit_ExtraData_TailOffset),\n          NukeFromOrbitCalldataSize,\n          extraCalldataBytes\n        )\n\n        let size := add(NukeFromOrbit_Base_Size, extraCalldataBytes)\n\n        if iszero(call(gas(), target, 0, add(cdPointer, 0x1c), size, 0, 0)) {\n          returndatacopy(0, 0, returndatasize())\n          revert(0, returndatasize())\n        }\n      }\n    }\n  }\n}\n"},{"file_path":"src/spherex/SphereXProtectedRegisteredBase.sol","source_code":"// SPDX-License-Identifier: UNLICENSED\n// (c) SphereX 2023 Terms&Conditions\npragma solidity ^0.8.20;\n\nimport { ISphereXEngine, ModifierLocals } from './ISphereXEngine.sol';\nimport './SphereXProtectedEvents.sol';\nimport './SphereXProtectedErrors.sol';\n\n/**\n * @title Modified version of SphereXProtectedBase for contracts registered\n *        on Wildcat's arch controller.\n *\n * @author Modified from https://github.com/spherex-xyz/spherex-protect-contracts/blob/main/src/SphereXProtectedBase.sol\n *\n * @dev In this version, the WildcatArchController deployment is the SphereX operator.\n *      There is no admin because the arch controller address can not be modified.\n *\n *      All admin functions/events/errors have been removed to reduce contract size.\n *\n *      SphereX engine address validation is delegated to the arch controller.\n */\nabstract contract SphereXProtectedRegisteredBase {\n  // ========================================================================== //\n  //                                  Constants                                 //\n  // ========================================================================== //\n\n  /// @dev Storage slot with the address of the SphereX engine contract.\n  bytes32 private constant SPHEREX_ENGINE_STORAGE_SLOT =\n    bytes32(uint256(keccak256('eip1967.spherex.spherex_engine')) - 1);\n\n  /**\n   * @dev Address of the WildcatArchController deployment.\n   *      The arch controller is able to set the SphereX engine address.\n   *      The inheriting contract must assign this in the constructor.\n   */\n  address internal immutable _archController;\n\n  // ========================================================================== //\n  //                                 Initializer                                //\n  // ========================================================================== //\n\n  /**\n   * @dev Initializes the SphereXEngine and emits events for the initial\n   *      engine and operator (arch controller).\n   */\n  function __SphereXProtectedRegisteredBase_init(address engine) internal virtual {\n    emit_ChangedSpherexOperator(address(0), _archController);\n    _setAddress(SPHEREX_ENGINE_STORAGE_SLOT, engine);\n    emit_ChangedSpherexEngineAddress(address(0), engine);\n  }\n\n  // ========================================================================== //\n  //                              Events and Errors                             //\n  // ========================================================================== //\n\n  error SphereXOperatorRequired();\n\n  event ChangedSpherexOperator(address oldSphereXAdmin, address newSphereXAdmin);\n  event ChangedSpherexEngineAddress(address oldEngineAddress, address newEngineAddress);\n\n  // ========================================================================== //\n  //                               Local Modifiers                              //\n  // ========================================================================== //\n\n  modifier spherexOnlyOperator() {\n    if (msg.sender != _archController) {\n      revert_SphereXOperatorRequired();\n    }\n    _;\n  }\n\n  modifier returnsIfNotActivatedPre(ModifierLocals memory locals) {\n    locals.engine = sphereXEngine();\n    if (locals.engine == address(0)) {\n      return;\n    }\n\n    _;\n  }\n\n  modifier returnsIfNotActivatedPost(ModifierLocals memory locals) {\n    if (locals.engine == address(0)) {\n      return;\n    }\n\n    _;\n  }\n\n  // ========================================================================== //\n  //                                 Management                                 //\n  // ========================================================================== //\n\n  /// @dev Returns the current operator address.\n  function sphereXOperator() public view returns (address) {\n    return _archController;\n  }\n\n  /// @dev Returns the current engine address.\n  function sphereXEngine() public view returns (address) {\n    return _getAddress(SPHEREX_ENGINE_STORAGE_SLOT);\n  }\n\n  /**\n   * @dev  Change the address of the SphereX engine.\n   *\n   *       This is also used to enable SphereX protection, which is disabled\n   *       when the engine address is 0.\n   *\n   * Note: The new engine is not validated as it would be in `SphereXProtectedBase`\n   *       because the operator is the arch controller, which validates the engine\n   *       address prior to updating it here.\n   */\n  function changeSphereXEngine(address newSphereXEngine) external spherexOnlyOperator {\n    address oldEngine = _getAddress(SPHEREX_ENGINE_STORAGE_SLOT);\n    _setAddress(SPHEREX_ENGINE_STORAGE_SLOT, newSphereXEngine);\n    emit_ChangedSpherexEngineAddress(oldEngine, newSphereXEngine);\n  }\n\n  // ========================================================================== //\n  //                                    Hooks                                   //\n  // ========================================================================== //\n\n  /**\n   * @dev Wrapper for `_getStorageSlotsAndPreparePostCalldata` that returns\n   *      a `uint256` pointer to `locals` rather than the struct itself.\n   *\n   *      Declaring a return parameter for a struct will always zero and\n   *      allocate memory for every field in the struct. If the parameter\n   *      is always reassigned, the gas and memory used on this are wasted.\n   *\n   *      Using a `uint256` pointer instead of a struct declaration avoids\n   *      this waste while being functionally identical.\n   */\n  function _sphereXValidateExternalPre() internal returns (uint256 localsPointer) {\n    return _castFunctionToPointerOutput(_getStorageSlotsAndPreparePostCalldata)(_getSelector());\n  }\n\n  /**\n   * @dev Internal function for engine communication. We use it to reduce contract size.\n   *      Should be called before the code of an external function.\n   *\n   *      Queries `storageSlots` from `sphereXValidatePre` on the engine and writes\n   *      the result to `locals.storageSlots`, then caches the current storage values\n   *      for those slots in `locals.valuesBefore`.\n   *\n   *      Also allocates memory for the calldata of the future call to `sphereXValidatePost`\n   *      and initializes every value in the calldata except for `gas` and `valuesAfter` data.\n   *\n   * @param num function identifier\n   */\n  function _getStorageSlotsAndPreparePostCalldata(\n    int256 num\n  ) internal returnsIfNotActivatedPre(locals) returns (ModifierLocals memory locals) {\n    assembly {\n      // Read engine from `locals.engine` - this is filled by `returnsIfNotActivatedPre`\n      let engineAddress := mload(add(locals, 0x60))\n\n      // Get free memory pointer - this will be used for the calldata\n      // to `sphereXValidatePre` and then reused for both `storageSlots`\n      // and the future calldata to `sphereXValidatePost`\n      let pointer := mload(0x40)\n\n      // Call `sphereXValidatePre(num, msg.sender, msg.data)`\n      mstore(pointer, 0x8925ca5a)\n      mstore(add(pointer, 0x20), num)\n      mstore(add(pointer, 0x40), caller())\n      mstore(add(pointer, 0x60), 0x60)\n      mstore(add(pointer, 0x80), calldatasize())\n      calldatacopy(add(pointer, 0xa0), 0, calldatasize())\n      let size := add(0xc4, calldatasize())\n\n      if iszero(\n        and(eq(mload(0), 0x20), call(gas(), engineAddress, 0, add(pointer, 28), size, 0, 0x40))\n      ) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n      let length := mload(0x20)\n\n      // Set up the memory after the allocation `locals` struct as:\n      // [0x00:0x20]: `storageSlots.length`\n      // [0x20:0x20+(length * 0x20)]: `storageSlots` data\n      // [0x20+(length*0x20):]: calldata for `sphereXValidatePost`\n\n      // The layout for the `sphereXValidatePost` calldata is:\n      // [0x00:0x20]: num\n      // [0x20:0x40]: gas\n      // [0x40:0x60]: valuesBefore offset (0x80)\n      // [0x60:0x80]: valuesAfter offset (0xa0 + (0x20 * length))\n      // [0x80:0xa0]: valuesBefore length (0xa0 + (0x20 * length))\n      // [0xa0:0xa0+(0x20*length)]: valuesBefore data\n      // [0xa0+(0x20*length):0xc0+(0x20*length)] valuesAfter length\n      // [0xc0+(0x20*length):0xc0+(0x40*length)]: valuesAfter data\n      //\n      // size of calldata: 0xc0 + (0x40 * length)\n      //\n      // size of allocation: 0xe0 + (0x60 * length)\n\n      // Calculate size of array data (excluding length): 32 * length\n      let arrayDataSize := shl(5, length)\n\n      // Finalize memory allocation with space for `storageSlots` and\n      // the calldata for `sphereXValidatePost`.\n      mstore(0x40, add(pointer, add(0xe0, mul(arrayDataSize, 3))))\n\n      // Copy `storageSlots` from returndata to the start of the allocated\n      // memory buffer and write the pointer to `locals.storageSlots`\n      returndatacopy(pointer, 0x20, add(arrayDataSize, 0x20))\n      mstore(locals, pointer)\n\n      // Get pointer to future calldata.\n      // Add `32 + arrayDataSize` to skip the allocation for `locals.storageSlots`\n      // @todo *could* put `valuesBefore` before `storageSlots` and reuse\n      // the `storageSlots` buffer for `valuesAfter`\n      let calldataPointer := add(pointer, add(arrayDataSize, 0x20))\n\n      // Write `-num` to calldata\n      mstore(calldataPointer, sub(0, num))\n\n      // Write `valuesBefore` offset to calldata\n      mstore(add(calldataPointer, 0x40), 0x80)\n\n      // Write `locals.valuesBefore` pointer\n      mstore(add(locals, 0x20), add(calldataPointer, 0x80))\n\n      // Write `valuesAfter` offset to calldata\n      mstore(add(calldataPointer, 0x60), add(0xa0, arrayDataSize))\n\n      // Write `gasleft()` to `locals.gas`\n      mstore(add(locals, 0x40), gas())\n    }\n    _readStorageTo(locals.storageSlots, locals.valuesBefore);\n  }\n\n  /**\n   * @dev Wrapper for `_callSphereXValidatePost` that takes a pointer\n   *      instead of a struct.\n   */\n  function _sphereXValidateExternalPost(uint256 locals) internal {\n    _castFunctionToPointerInput(_callSphereXValidatePost)(locals);\n  }\n\n  function _callSphereXValidatePost(\n    ModifierLocals memory locals\n  ) internal returnsIfNotActivatedPost(locals) {\n    uint256 length;\n    bytes32[] memory storageSlots;\n    bytes32[] memory valuesAfter;\n    assembly {\n      storageSlots := mload(locals)\n      length := mload(storageSlots)\n      valuesAfter := add(storageSlots, add(0xc0, shl(6, length)))\n    }\n    _readStorageTo(storageSlots, valuesAfter);\n    assembly {\n      let sphereXEngineAddress := mload(add(locals, 0x60))\n      let arrayDataSize := shl(5, length)\n      let calldataSize := add(0xc4, shl(1, arrayDataSize))\n\n      let calldataPointer := add(storageSlots, add(arrayDataSize, 0x20))\n      let gasDiff := sub(mload(add(locals, 0x40)), gas())\n      mstore(add(calldataPointer, 0x20), gasDiff)\n      let slotBefore := sub(calldataPointer, 32)\n      let slotBeforeCache := mload(slotBefore)\n      mstore(slotBefore, 0xf0bd9468)\n      if iszero(call(gas(), sphereXEngineAddress, 0, add(slotBefore, 28), calldataSize, 0, 0)) {\n        returndatacopy(0, 0, returndatasize())\n        revert(0, returndatasize())\n      }\n      mstore(slotBefore, slotBeforeCache)\n    }\n  }\n\n  /// @dev Returns the function selector from the current calldata.\n  function _getSelector() internal pure returns (int256 selector) {\n    assembly {\n      selector := shr(224, calldataload(0))\n    }\n  }\n\n  /// @dev Modifier to be incorporated in all external protected non-view functions\n  modifier sphereXGuardExternal() {\n    uint256 localsPointer = _sphereXValidateExternalPre();\n    _;\n    _sphereXValidateExternalPost(localsPointer);\n  }\n\n  // ========================================================================== //\n  //                          Internal Storage Helpers                          //\n  // ========================================================================== //\n\n  /// @dev Stores an address in an arbitrary slot\n  function _setAddress(bytes32 slot, address newAddress) internal {\n    assembly {\n      sstore(slot, newAddress)\n    }\n  }\n\n  /// @dev Returns an address from an arbitrary slot.\n  function _getAddress(bytes32 slot) internal view returns (address addr) {\n    assembly {\n      addr := sload(slot)\n    }\n  }\n\n  /**\n   * @dev Internal function that reads values from given storage slots\n   *      and writes them to a particular memory location.\n   *\n   * @param storageSlots array of storage slots to read\n   * @param values array of values to write values to\n   */\n  function _readStorageTo(bytes32[] memory storageSlots, bytes32[] memory values) internal view {\n    assembly {\n      let length := mload(storageSlots)\n      let arrayDataSize := shl(5, length)\n      mstore(values, length)\n      let nextSlotPointer := add(storageSlots, 0x20)\n      let nextElementPointer := add(values, 0x20)\n      let endPointer := add(nextElementPointer, shl(5, length))\n      for {\n\n      } lt(nextElementPointer, endPointer) {\n\n      } {\n        mstore(nextElementPointer, sload(mload(nextSlotPointer)))\n        nextElementPointer := add(nextElementPointer, 0x20)\n        nextSlotPointer := add(nextSlotPointer, 0x20)\n      }\n    }\n  }\n\n  // ========================================================================== //\n  //                             Function Type Casts                            //\n  // ========================================================================== //\n\n  function _castFunctionToPointerInput(\n    function(ModifierLocals memory) internal fnIn\n  ) internal pure returns (function(uint256) internal fnOut) {\n    assembly {\n      fnOut := fnIn\n    }\n  }\n\n  function _castFunctionToPointerOutput(\n    function(int256) internal returns (ModifierLocals memory) fnIn\n  ) internal pure returns (function(int256) internal returns (uint256) fnOut) {\n    assembly {\n      fnOut := fnIn\n    }\n  }\n}\n"},{"file_path":"src/libraries/MathUtils.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport './Errors.sol';\n\nuint256 constant BIP = 1e4;\nuint256 constant HALF_BIP = 0.5e4;\n\nuint256 constant RAY = 1e27;\nuint256 constant HALF_RAY = 0.5e27;\n\nuint256 constant BIP_RAY_RATIO = 1e23;\n\nuint256 constant SECONDS_IN_365_DAYS = 365 days;\n\nlibrary MathUtils {\n  /// @dev The multiply-divide operation failed, either due to a\n  /// multiplication overflow, or a division by a zero.\n  error MulDivFailed();\n\n  using MathUtils for uint256;\n\n  /**\n   * @dev Function to calculate the interest accumulated using a linear interest rate formula\n   *\n   * @param rateBip The interest rate, in bips\n   * @param timeDelta The time elapsed since the last interest accrual\n   * @return result The interest rate linearly accumulated during the timeDelta, in ray\n   */\n  function calculateLinearInterestFromBips(\n    uint256 rateBip,\n    uint256 timeDelta\n  ) internal pure returns (uint256 result) {\n    uint256 rate = rateBip.bipToRay();\n    uint256 accumulatedInterestRay = rate * timeDelta;\n    unchecked {\n      return accumulatedInterestRay / SECONDS_IN_365_DAYS;\n    }\n  }\n\n  /**\n   * @dev Return the smaller of `a` and `b`\n   */\n  function min(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    c = ternary(a < b, a, b);\n  }\n\n  /**\n   * @dev Return the larger of `a` and `b`.\n   */\n  function max(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    c = ternary(a < b, b, a);\n  }\n\n  /**\n   * @dev Saturation subtraction. Subtract `b` from `a` and return the result\n   *      if it is positive or zero if it underflows.\n   */\n  function satSub(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // (a > b) * (a - b)\n      // If a-b underflows, the product will be zero\n      c := mul(gt(a, b), sub(a, b))\n    }\n  }\n\n  /**\n   * @dev Saturation addition. Add `a` to `b` and return the result\n   *      if it is less than `maxValue` or `maxValue` if it overflows.\n   */\n  function satAdd(uint256 a, uint256 b, uint256 maxValue) internal pure returns (uint256 c) {\n    unchecked {\n      c = a + b;\n      return ternary(c < maxValue, c, maxValue);\n    }\n  }\n\n  /**\n   * @dev Return `valueIfTrue` if `condition` is true and `valueIfFalse` if it is false.\n   *      Equivalent to `condition ? valueIfTrue : valueIfFalse`\n   */\n  function ternary(\n    bool condition,\n    uint256 valueIfTrue,\n    uint256 valueIfFalse\n  ) internal pure returns (uint256 c) {\n    assembly {\n      c := add(valueIfFalse, mul(condition, sub(valueIfTrue, valueIfFalse)))\n    }\n  }\n\n  /**\n   * @dev Multiplies two bip, rounding half up to the nearest bip\n   *      see https://twitter.com/transmissions11/status/1451131036377571328\n   */\n  function bipMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // equivalent to `require(b == 0 || a <= (type(uint256).max - HALF_BIP) / b)`\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_BIP), b))))) {\n        // Store the Panic error signature.\n        mstore(0, Panic_ErrorSelector)\n        // Store the arithmetic (0x11) panic code.\n        mstore(Panic_ErrorCodePointer, Panic_Arithmetic)\n        // revert(abi.encodeWithSignature(\"Panic(uint256)\", 0x11))\n        revert(Error_SelectorPointer, Panic_ErrorLength)\n      }\n\n      c := div(add(mul(a, b), HALF_BIP), BIP)\n    }\n  }\n\n  /**\n   * @dev Divides two bip, rounding half up to the nearest bip\n   *      see https://twitter.com/transmissions11/status/1451131036377571328\n   */\n  function bipDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // equivalent to `require(b != 0 && a <= (type(uint256).max - b/2) / BIP)`\n      if or(iszero(b), gt(a, div(sub(not(0), div(b, 2)), BIP))) {\n        mstore(0, Panic_ErrorSelector)\n        mstore(Panic_ErrorCodePointer, Panic_Arithmetic)\n        revert(Error_SelectorPointer, Panic_ErrorLength)\n      }\n\n      c := div(add(mul(a, BIP), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @dev Converts bip up to ray\n   */\n  function bipToRay(uint256 a) internal pure returns (uint256 b) {\n    // to avoid overflow, b/BIP_RAY_RATIO == a\n    assembly {\n      b := mul(a, BIP_RAY_RATIO)\n      // equivalent to `require((b = a * BIP_RAY_RATIO) / BIP_RAY_RATIO == a )\n      if iszero(eq(div(b, BIP_RAY_RATIO), a)) {\n        mstore(0, Panic_ErrorSelector)\n        mstore(Panic_ErrorCodePointer, Panic_Arithmetic)\n        revert(Error_SelectorPointer, Panic_ErrorLength)\n      }\n    }\n  }\n\n  /**\n   * @dev Multiplies two ray, rounding half up to the nearest ray\n   *      see https://twitter.com/transmissions11/status/1451131036377571328\n   */\n  function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // equivalent to `require(b == 0 || a <= (type(uint256).max - HALF_RAY) / b)`\n      if iszero(or(iszero(b), iszero(gt(a, div(sub(not(0), HALF_RAY), b))))) {\n        mstore(0, Panic_ErrorSelector)\n        mstore(Panic_ErrorCodePointer, Panic_Arithmetic)\n        revert(Error_SelectorPointer, Panic_ErrorLength)\n      }\n\n      c := div(add(mul(a, b), HALF_RAY), RAY)\n    }\n  }\n\n  /**\n   * @dev Divide two ray, rounding half up to the nearest ray\n   *      see https://twitter.com/transmissions11/status/1451131036377571328\n   */\n  function rayDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {\n    assembly {\n      // equivalent to `require(b != 0 && a <= (type(uint256).max - halfB) / RAY)`\n      if or(iszero(b), gt(a, div(sub(not(0), div(b, 2)), RAY))) {\n        mstore(0, Panic_ErrorSelector)\n        mstore(Panic_ErrorCodePointer, Panic_Arithmetic)\n        revert(Error_SelectorPointer, Panic_ErrorLength)\n      }\n\n      c := div(add(mul(a, RAY), div(b, 2)), b)\n    }\n  }\n\n  /**\n   * @dev Returns `floor(x * y / d)`.\n   *      Reverts if `x * y` overflows, or `d` is zero.\n   * @custom:author solady/src/utils/FixedPointMathLib.sol\n   */\n  function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n    assembly {\n      // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))\n      if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {\n        // Store the function selector of `MulDivFailed()`.\n        mstore(0x00, 0xad251c27)\n        // Revert with (offset, size).\n        revert(0x1c, 0x04)\n      }\n      z := div(mul(x, y), d)\n    }\n  }\n\n  /**\n   * @dev Returns `ceil(x * y / d)`.\n   *      Reverts if `x * y` overflows, or `d` is zero.\n   * @custom:author solady/src/utils/FixedPointMathLib.sol\n   */\n  function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {\n    assembly {\n      // Equivalent to require(d != 0 && (y == 0 || x <= type(uint256).max / y))\n      if iszero(mul(d, iszero(mul(y, gt(x, div(not(0), y)))))) {\n        // Store the function selector of `MulDivFailed()`.\n        mstore(0x00, 0xad251c27)\n        // Revert with (offset, size).\n        revert(0x1c, 0x04)\n      }\n      z := add(iszero(iszero(mod(mul(x, y), d))), div(mul(x, y), d))\n    }\n  }\n}\n"},{"file_path":"src/WildcatSanctionsSentinel.sol","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport { IChainalysisSanctionsList } from './interfaces/IChainalysisSanctionsList.sol';\nimport { IWildcatSanctionsSentinel } from './interfaces/IWildcatSanctionsSentinel.sol';\nimport { WildcatSanctionsEscrow } from './WildcatSanctionsEscrow.sol';\n\ncontract WildcatSanctionsSentinel is IWildcatSanctionsSentinel {\n  // ========================================================================== //\n  //                                  Constants                                 //\n  // ========================================================================== //\n\n  bytes32 public constant override WildcatSanctionsEscrowInitcodeHash =\n    keccak256(type(WildcatSanctionsEscrow).creationCode);\n\n  address public immutable override chainalysisSanctionsList;\n\n  address public immutable override archController;\n\n  // ========================================================================== //\n  //                                   Storage                                  //\n  // ========================================================================== //\n\n  TmpEscrowParams public override tmpEscrowParams;\n\n  mapping(address borrower => mapping(address account => bool sanctionOverride))\n    public\n    override sanctionOverrides;\n\n  // ========================================================================== //\n  //                                 Constructor                                //\n  // ========================================================================== //\n\n  constructor(address _archController, address _chainalysisSanctionsList) {\n    archController = _archController;\n    chainalysisSanctionsList = _chainalysisSanctionsList;\n    _resetTmpEscrowParams();\n  }\n\n  // ========================================================================== //\n  //                              Internal Helpers                              //\n  // ========================================================================== //\n\n  function _resetTmpEscrowParams() internal {\n    tmpEscrowParams = TmpEscrowParams(address(1), address(1), address(1));\n  }\n\n  /**\n   * @dev Derive create2 salt for an escrow given the borrower, account and asset.\n   *      name prefix and symbol prefix.\n   */\n  function _deriveSalt(\n    address borrower,\n    address account,\n    address asset\n  ) internal pure returns (bytes32 salt) {\n    assembly {\n      // Cache free memory pointer\n      let freeMemoryPointer := mload(0x40)\n      // `keccak256(abi.encode(borrower, account, asset))`\n      mstore(0x00, borrower)\n      mstore(0x20, account)\n      mstore(0x40, asset)\n      salt := keccak256(0, 0x60)\n      // Restore free memory pointer\n      mstore(0x40, freeMemoryPointer)\n    }\n  }\n\n  // ========================================================================== //\n  //                              Sanction Queries                              //\n  // ========================================================================== //\n\n  /**\n   * @dev Returns boolean indicating whether `account` is sanctioned on Chainalysis.\n   */\n  function isFlaggedByChainalysis(address account) public view override returns (bool) {\n    return IChainalysisSanctionsList(chainalysisSanctionsList).isSanctioned(account);\n  }\n\n  /**\n   * @dev Returns boolean indicating whether `account` is sanctioned on Chainalysis\n   *      and that status has not been overridden by `borrower`.\n   */\n  function isSanctioned(address borrower, address account) public view override returns (bool) {\n    return !sanctionOverrides[borrower][account] && isFlaggedByChainalysis(account);\n  }\n\n  // ========================================================================== //\n  //                             Sanction Overrides                             //\n  // ========================================================================== //\n\n  /**\n   * @dev Overrides the sanction status of `account` for `borrower`.\n   */\n  function overrideSanction(address account) public override {\n    sanctionOverrides[msg.sender][account] = true;\n    emit SanctionOverride(msg.sender, account);\n  }\n\n  /**\n   * @dev Removes the sanction override of `account` for `borrower`.\n   */\n  function removeSanctionOverride(address account) public override {\n    sanctionOverrides[msg.sender][account] = false;\n    emit SanctionOverrideRemoved(msg.sender, account);\n  }\n\n  // ========================================================================== //\n  //                              Escrow Deployment                             //\n  // ========================================================================== //\n\n  /**\n   * @dev Creates a new WildcatSanctionsEscrow contract for `borrower`,\n   *      `account`, and `asset` or returns the existing escrow contract\n   *      if one already exists.\n   *\n   *      The escrow contract is added to the set of sanction override\n   *      addresses for `borrower` so that it can not be blocked.\n   */\n  function createEscrow(\n    address borrower,\n    address account,\n    address asset\n  ) public override returns (address escrowContract) {\n    escrowContract = getEscrowAddress(borrower, account, asset);\n\n    // Skip creation if the address code size is non-zero\n    if (escrowContract.code.length != 0) return escrowContract;\n\n    tmpEscrowParams = TmpEscrowParams(borrower, account, asset);\n\n    new WildcatSanctionsEscrow{ salt: _deriveSalt(borrower, account, asset) }();\n\n    emit NewSanctionsEscrow(borrower, account, asset);\n\n    sanctionOverrides[borrower][escrowContract] = true;\n\n    emit SanctionOverride(borrower, escrowContract);\n\n    _resetTmpEscrowParams();\n  }\n\n  /**\n   * @dev Calculate the create2 escrow address for the combination\n   *      of `borrower`, `account`, and `asset`.\n   */\n  function getEscrowAddress(\n    address borrower,\n    address account,\n    address asset\n  ) public view override returns (address escrowAddress) {\n    bytes32 salt = _deriveSalt(borrower, account, asset);\n    bytes32 initCodeHash = WildcatSanctionsEscrowInitcodeHash;\n    assembly {\n      // Cache the free memory pointer so it can be restored at the end\n      let freeMemoryPointer := mload(0x40)\n\n      // Write 0xff + address(this) to bytes 11:32\n      mstore(0x00, or(0xff0000000000000000000000000000000000000000, address()))\n\n      // Write salt to bytes 32:64\n      mstore(0x20, salt)\n\n      // Write initcode hash to bytes 64:96\n      mstore(0x40, initCodeHash)\n\n      // Calculate create2 hash\n      escrowAddress := and(keccak256(0x0b, 0x55), 0xffffffffffffffffffffffffffffffffffffffff)\n\n      // Restore the free memory pointer\n      mstore(0x40, freeMemoryPointer)\n    }\n  }\n}\n"},{"file_path":"src/libraries/FIFOQueue.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nstruct FIFOQueue {\n  uint128 startIndex;\n  uint128 nextIndex;\n  mapping(uint256 => uint32) data;\n}\n\n// @todo - make array tightly packed for gas efficiency with multiple reads/writes\n//         also make a memory version of the array with (nextIndex, startIndex, storageSlot)\n//         so that multiple storage reads aren't required for tx's using multiple functions\n\nusing FIFOQueueLib for FIFOQueue global;\n\nlibrary FIFOQueueLib {\n  error FIFOQueueOutOfBounds();\n\n  function empty(FIFOQueue storage arr) internal view returns (bool) {\n    return arr.nextIndex == arr.startIndex;\n  }\n\n  function first(FIFOQueue storage arr) internal view returns (uint32) {\n    if (arr.startIndex == arr.nextIndex) {\n      revert FIFOQueueOutOfBounds();\n    }\n    return arr.data[arr.startIndex];\n  }\n\n  function at(FIFOQueue storage arr, uint256 index) internal view returns (uint32) {\n    index += arr.startIndex;\n    if (index >= arr.nextIndex) {\n      revert FIFOQueueOutOfBounds();\n    }\n    return arr.data[index];\n  }\n\n  function length(FIFOQueue storage arr) internal view returns (uint128) {\n    return arr.nextIndex - arr.startIndex;\n  }\n\n  function values(FIFOQueue storage arr) internal view returns (uint32[] memory _values) {\n    uint256 startIndex = arr.startIndex;\n    uint256 nextIndex = arr.nextIndex;\n    uint256 len = nextIndex - startIndex;\n    _values = new uint32[](len);\n\n    for (uint256 i = 0; i < len; i++) {\n      _values[i] = arr.data[startIndex + i];\n    }\n\n    return _values;\n  }\n\n  function push(FIFOQueue storage arr, uint32 value) internal {\n    uint128 nextIndex = arr.nextIndex;\n    arr.data[nextIndex] = value;\n    arr.nextIndex = nextIndex + 1;\n  }\n\n  function shift(FIFOQueue storage arr) internal {\n    uint128 startIndex = arr.startIndex;\n    if (startIndex == arr.nextIndex) {\n      revert FIFOQueueOutOfBounds();\n    }\n    delete arr.data[startIndex];\n    arr.startIndex = startIndex + 1;\n  }\n\n  function shiftN(FIFOQueue storage arr, uint128 n) internal {\n    uint128 startIndex = arr.startIndex;\n    if (startIndex + n > arr.nextIndex) {\n      revert FIFOQueueOutOfBounds();\n    }\n    for (uint256 i = 0; i < n; i++) {\n      delete arr.data[startIndex + i];\n    }\n    arr.startIndex = startIndex + n;\n  }\n}\n"},{"file_path":"lib/solady/src/utils/LibBit.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\n/// @notice Library for bit twiddling and boolean operations.\n/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)\n/// @author Inspired by (https://graphics.stanford.edu/~seander/bithacks.html)\nlibrary LibBit {\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                  BIT TWIDDLING OPERATIONS                  */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    /// @dev Find last set.\n    /// Returns the index of the most significant bit of `x`,\n    /// counting from the least significant bit position.\n    /// If `x` is zero, returns 256.\n    function fls(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            r := or(r, shl(2, lt(0xf, shr(r, x))))\n            r := or(r, byte(shr(r, x), hex\"00000101020202020303030303030303\"))\n        }\n    }\n\n    /// @dev Count leading zeros.\n    /// Returns the number of zeros preceding the most significant one bit.\n    /// If `x` is zero, returns 256.\n    function clz(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))\n            r := or(r, shl(4, lt(0xffff, shr(r, x))))\n            r := or(r, shl(3, lt(0xff, shr(r, x))))\n            r := or(r, shl(2, lt(0xf, shr(r, x))))\n            // forgefmt: disable-next-item\n            r := add(iszero(x), xor(255,\n                or(r, byte(shr(r, x), hex\"00000101020202020303030303030303\"))))\n        }\n    }\n\n    /// @dev Find first set.\n    /// Returns the index of the least significant bit of `x`,\n    /// counting from the least significant bit position.\n    /// If `x` is zero, returns 256.\n    /// Equivalent to `ctz` (count trailing zeros), which gives\n    /// the number of zeros following the least significant one bit.\n    function ffs(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Isolate the least significant bit.\n            let b := and(x, add(not(x), 1))\n\n            r := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, b)))\n            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, b))))\n            r := or(r, shl(5, lt(0xffffffff, shr(r, b))))\n\n            // For the remaining 32 bits, use a De Bruijn lookup.\n            // forgefmt: disable-next-item\n            r := or(r, byte(and(div(0xd76453e0, shr(r, b)), 0x1f),\n                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))\n        }\n    }\n\n    /// @dev Returns the number of set bits in `x`.\n    function popCount(uint256 x) internal pure returns (uint256 c) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let max := not(0)\n            let isMax := eq(x, max)\n            x := sub(x, and(shr(1, x), div(max, 3)))\n            x := add(and(x, div(max, 5)), and(shr(2, x), div(max, 5)))\n            x := and(add(x, shr(4, x)), div(max, 17))\n            c := or(shl(8, isMax), shr(248, mul(x, div(max, 255))))\n        }\n    }\n\n    /// @dev Returns whether `x` is a power of 2.\n    function isPo2(uint256 x) internal pure returns (bool result) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Equivalent to `x && !(x & (x - 1))`.\n            result := iszero(add(and(x, sub(x, 1)), iszero(x)))\n        }\n    }\n\n    /// @dev Returns `x` reversed at the bit level.\n    function reverseBits(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Computing masks on-the-fly reduces bytecode size by about 500 bytes.\n            let m := not(0)\n            r := x\n            for { let s := 128 } 1 {} {\n                m := xor(m, shl(s, m))\n                r := or(and(shr(s, r), m), and(shl(s, r), not(m)))\n                s := shr(1, s)\n                if iszero(s) { break }\n            }\n        }\n    }\n\n    /// @dev Returns `x` reversed at the byte level.\n    function reverseBytes(uint256 x) internal pure returns (uint256 r) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            // Computing masks on-the-fly reduces bytecode size by about 200 bytes.\n            let m := not(0)\n            r := x\n            for { let s := 128 } 1 {} {\n                m := xor(m, shl(s, m))\n                r := or(and(shr(s, r), m), and(shl(s, r), not(m)))\n                s := shr(1, s)\n                if eq(s, 4) { break }\n            }\n        }\n    }\n\n    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n    /*                     BOOLEAN OPERATIONS                     */\n    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n    // A Solidity bool on the stack or memory is represented as a 256-bit word.\n    // Non-zero values are true, zero is false.\n    // A clean bool is either 0 (false) or 1 (true) under the hood.\n    // Usually, if not always, the bool result of a regular Solidity expression,\n    // or the argument of a public/external function will be a clean bool.\n    // You can usually use the raw variants for more performance.\n    // If uncertain, test (best with exact compiler settings).\n    // Or use the non-raw variants (compiler can sometimes optimize out the double `iszero`s).\n\n    /// @dev Returns `x & y`. Inputs must be clean.\n    function rawAnd(bool x, bool y) internal pure returns (bool z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := and(x, y)\n        }\n    }\n\n    /// @dev Returns `x & y`.\n    function and(bool x, bool y) internal pure returns (bool z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := and(iszero(iszero(x)), iszero(iszero(y)))\n        }\n    }\n\n    /// @dev Returns `x | y`. Inputs must be clean.\n    function rawOr(bool x, bool y) internal pure returns (bool z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := or(x, y)\n        }\n    }\n\n    /// @dev Returns `x | y`.\n    function or(bool x, bool y) internal pure returns (bool z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := or(iszero(iszero(x)), iszero(iszero(y)))\n        }\n    }\n\n    /// @dev Returns 1 if `b` is true, else 0. Input must be clean.\n    function rawToUint(bool b) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := b\n        }\n    }\n\n    /// @dev Returns 1 if `b` is true, else 0.\n    function toUint(bool b) internal pure returns (uint256 z) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            z := iszero(iszero(b))\n        }\n    }\n}\n"},{"file_path":"src/ReentrancyGuard.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\n/// @dev Selector for `error NoReentrantCalls()`\nuint256 constant NoReentrantCalls_ErrorSelector = 0x7fa8a987;\n\nuint256 constant _REENTRANCY_GUARD_SLOT = 0x929eee14;\n\n/**\n * @title ReentrancyGuard\n * @author d1ll0n\n * @notice Changes from original:\n *   - Removed the checks for whether tstore is supported.\n * @author Modified from Seaport contract by 0age (https://github.com/ProjectOpenSea/seaport-1.6)\n *\n * @notice ReentrancyGuard contains a transient storage variable and related\n *         functionality for protecting against reentrancy.\n */\ncontract ReentrancyGuard {\n  /**\n   * @dev Revert with an error when a caller attempts to reenter a protected function.\n   *\n   *      Note: Only defined for the sake of the interface and readability - the\n   *      definition is not directly referenced in the contract code.\n   */\n  error NoReentrantCalls();\n\n  uint256 private constant _NOT_ENTERED = 0;\n  uint256 private constant _ENTERED = 1;\n\n  /**\n   * @dev Reentrancy guard for state-changing functions.\n   *      Reverts if the reentrancy guard is currently set; otherwise, sets\n   *      the reentrancy guard, executes the function body, then clears the\n   *      reentrancy guard.\n   */\n  modifier nonReentrant() {\n    _setReentrancyGuard();\n    _;\n    _clearReentrancyGuard();\n  }\n\n  /**\n   * @dev Reentrancy guard for view functions.\n   *      Reverts if the reentrancy guard is currently set.\n   */\n  modifier nonReentrantView() {\n    _assertNonReentrant();\n    _;\n  }\n\n  /**\n   * @dev Internal function to ensure that a sentinel value for the reentrancy\n   *      guard is not currently set and, if not, to set a sentinel value for\n   *      the reentrancy guard.\n   */\n  function _setReentrancyGuard() internal {\n    assembly {\n      // Retrieve the current value of the reentrancy guard slot.\n      let _reentrancyGuard := tload(_REENTRANCY_GUARD_SLOT)\n\n      // Ensure that the reentrancy guard is not already set.\n      // Equivalent to `if (_reentrancyGuard != _NOT_ENTERED) revert NoReentrantCalls();`\n      if _reentrancyGuard {\n        mstore(0, NoReentrantCalls_ErrorSelector)\n        revert(0x1c, 0x04)\n      }\n\n      // Set the reentrancy guard.\n      // Equivalent to `_reentrancyGuard = _ENTERED;`\n      tstore(_REENTRANCY_GUARD_SLOT, _ENTERED)\n    }\n  }\n\n  /**\n   * @dev Internal function to unset the reentrancy guard sentinel value.\n   */\n  function _clearReentrancyGuard() internal {\n    assembly {\n      // Equivalent to `_reentrancyGuard = _NOT_ENTERED;`\n      tstore(_REENTRANCY_GUARD_SLOT, _NOT_ENTERED)\n    }\n  }\n\n  /**\n   * @dev Internal view function to ensure that a sentinel value for the\n   *         reentrancy guard is not currently set.\n   */\n  function _assertNonReentrant() internal view {\n    assembly {\n      // Ensure that the reentrancy guard is not currently set.\n      // Equivalent to `if (_reentrancyGuard != _NOT_ENTERED) revert NoReentrantCalls();`\n      if tload(_REENTRANCY_GUARD_SLOT) {\n        mstore(0, NoReentrantCalls_ErrorSelector)\n        revert(0x1c, 0x04)\n      }\n    }\n  }\n}\n"},{"file_path":"src/interfaces/IMarketEventsAndErrors.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport { MarketState } from '../libraries/MarketState.sol';\n\ninterface IMarketEventsAndErrors {\n  /// @notice Error thrown when deposit exceeds maxTotalSupply\n  error MaxSupplyExceeded();\n\n  /// @notice Error thrown when non-borrower tries accessing borrower-only actions\n  error NotApprovedBorrower();\n\n  /// @notice Error thrown when non-approved lender tries lending to the market\n  error NotApprovedLender();\n\n  /// @notice Error thrown when caller other than factory tries changing protocol fee\n  error NotFactory();\n\n  /// @notice Error thrown when non-sentinel tries to use nukeFromOrbit\n  error BadLaunchCode();\n\n  /// @notice Error thrown when transfer target is blacklisted\n  error AccountBlocked();\n\n  error BadRescueAsset();\n\n  error BorrowAmountTooHigh();\n\n  error InsufficientReservesForFeeWithdrawal();\n\n  error WithdrawalBatchNotExpired();\n\n  error NullMintAmount();\n\n  error NullBurnAmount();\n\n  error NullFeeAmount();\n\n  error NullTransferAmount();\n\n  error NullWithdrawalAmount();\n\n  error NullRepayAmount();\n\n  error NullBuyBackAmount();\n\n  error MarketAlreadyClosed();\n\n  error DepositToClosedMarket();\n\n  error RepayToClosedMarket();\n\n  error BuyBackOnDelinquentMarket();\n\n  error BorrowWhileSanctioned();\n\n  error BorrowFromClosedMarket();\n\n  error AprChangeOnClosedMarket();\n\n  error CapacityChangeOnClosedMarket();\n\n  error ProtocolFeeChangeOnClosedMarket();\n\n  error CloseMarketWithUnpaidWithdrawals();\n\n  error AnnualInterestBipsTooHigh();\n\n  error ReserveRatioBipsTooHigh();\n\n  error ProtocolFeeTooHigh();\n\n  /// @dev Error thrown when reserve ratio is set to a value\n  ///      that would make the market delinquent.\n  error InsufficientReservesForNewLiquidityRatio();\n\n  error InsufficientReservesForOldLiquidityRatio();\n\n  error InvalidArrayLength();\n\n  event Transfer(address indexed from, address indexed to, uint256 value);\n\n  event Approval(address indexed owner, address indexed spender, uint256 value);\n\n  event MaxTotalSupplyUpdated(uint256 assets);\n\n  event ProtocolFeeBipsUpdated(uint256 protocolFeeBips);\n\n  event AnnualInterestBipsUpdated(uint256 annualInterestBipsUpdated);\n\n  event ReserveRatioBipsUpdated(uint256 reserveRatioBipsUpdated);\n\n  event SanctionedAccountAssetsSentToEscrow(\n    address indexed account,\n    address escrow,\n    uint256 amount\n  );\n\n  event SanctionedAccountAssetsQueuedForWithdrawal(\n    address indexed account,\n    uint256 expiry,\n    uint256 scaledAmount,\n    uint256 normalizedAmount\n  );\n\n  event Deposit(address indexed account, uint256 assetAmount, uint256 scaledAmount);\n\n  event Borrow(uint256 assetAmount);\n\n  event DebtRepaid(address indexed from, uint256 assetAmount);\n\n  event MarketClosed(uint256 timestamp);\n\n  event FeesCollected(uint256 assets);\n\n  event StateUpdated(uint256 scaleFactor, bool isDelinquent);\n\n  event InterestAndFeesAccrued(\n    uint256 fromTimestamp,\n    uint256 toTimestamp,\n    uint256 scaleFactor,\n    uint256 baseInterestRay,\n    uint256 delinquencyFeeRay,\n    uint256 protocolFees\n  );\n\n  event AccountSanctioned(address indexed account);\n\n  // =====================================================================//\n  //                          Withdrawl Events                            //\n  // =====================================================================//\n\n  event WithdrawalBatchExpired(\n    uint256 indexed expiry,\n    uint256 scaledTotalAmount,\n    uint256 scaledAmountBurned,\n    uint256 normalizedAmountPaid\n  );\n\n  /// @dev Emitted when a new withdrawal batch is created.\n  event WithdrawalBatchCreated(uint256 indexed expiry);\n\n  /// @dev Emitted when a withdrawal batch is paid off.\n  event WithdrawalBatchClosed(uint256 indexed expiry);\n\n  event WithdrawalBatchPayment(\n    uint256 indexed expiry,\n    uint256 scaledAmountBurned,\n    uint256 normalizedAmountPaid\n  );\n\n  event WithdrawalQueued(\n    uint256 indexed expiry,\n    address indexed account,\n    uint256 scaledAmount,\n    uint256 normalizedAmount\n  );\n\n  event WithdrawalExecuted(\n    uint256 indexed expiry,\n    address indexed account,\n    uint256 normalizedAmount\n  );\n\n  event SanctionedAccountWithdrawalSentToEscrow(\n    address indexed account,\n    address escrow,\n    uint32 expiry,\n    uint256 amount\n  );\n}\n"},{"file_path":"src/interfaces/WildcatStructsAndEnums.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport { MarketState } from '../libraries/MarketState.sol';\n\nimport { HooksConfig } from '../types/HooksConfig.sol';\n\nstruct MarketParameters {\n  address asset;\n  uint8 decimals;\n  bytes32 packedNameWord0;\n  bytes32 packedNameWord1;\n  bytes32 packedSymbolWord0;\n  bytes32 packedSymbolWord1;\n  address borrower;\n  address feeRecipient;\n  address sentinel;\n  uint128 maxTotalSupply;\n  uint16 protocolFeeBips;\n  uint16 annualInterestBips;\n  uint16 delinquencyFeeBips;\n  uint32 withdrawalBatchDuration;\n  uint16 reserveRatioBips;\n  uint32 delinquencyGracePeriod;\n  address archController;\n  address sphereXEngine;\n  HooksConfig hooks;\n}\n\nstruct DeployMarketInputs {\n  address asset;\n  string namePrefix;\n  string symbolPrefix;\n  uint128 maxTotalSupply;\n  uint16 annualInterestBips;\n  uint16 delinquencyFeeBips;\n  uint32 withdrawalBatchDuration;\n  uint16 reserveRatioBips;\n  uint32 delinquencyGracePeriod;\n  HooksConfig hooks;\n}\n\nstruct MarketControllerParameters {\n  address archController;\n  address borrower;\n  address sentinel;\n  address marketInitCodeStorage;\n  uint256 marketInitCodeHash;\n  uint32 minimumDelinquencyGracePeriod;\n  uint32 maximumDelinquencyGracePeriod;\n  uint16 minimumReserveRatioBips;\n  uint16 maximumReserveRatioBips;\n  uint16 minimumDelinquencyFeeBips;\n  uint16 maximumDelinquencyFeeBips;\n  uint32 minimumWithdrawalBatchDuration;\n  uint32 maximumWithdrawalBatchDuration;\n  uint16 minimumAnnualInterestBips;\n  uint16 maximumAnnualInterestBips;\n  address sphereXEngine;\n}\n\nstruct ProtocolFeeConfiguration {\n  address feeRecipient;\n  address originationFeeAsset;\n  uint80 originationFeeAmount;\n  uint16 protocolFeeBips;\n}\n\nstruct MarketParameterConstraints {\n  uint32 minimumDelinquencyGracePeriod;\n  uint32 maximumDelinquencyGracePeriod;\n  uint16 minimumReserveRatioBips;\n  uint16 maximumReserveRatioBips;\n  uint16 minimumDelinquencyFeeBips;\n  uint16 maximumDelinquencyFeeBips;\n  uint32 minimumWithdrawalBatchDuration;\n  uint32 maximumWithdrawalBatchDuration;\n  uint16 minimumAnnualInterestBips;\n  uint16 maximumAnnualInterestBips;\n}\n"},{"file_path":"src/interfaces/IChainalysisSanctionsList.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\ninterface IChainalysisSanctionsList {\n  function isSanctioned(address addr) external view returns (bool);\n}\n"},{"file_path":"src/libraries/Withdrawal.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity >=0.8.20;\n\nimport './MarketState.sol';\nimport './FIFOQueue.sol';\n\nusing MathUtils for uint256;\nusing WithdrawalLib for WithdrawalBatch global;\n\n/**\n * Withdrawals are grouped together in batches with a fixed expiry.\n * Until a withdrawal is paid out, the tokens are not burned from the market\n * and continue to accumulate interest.\n */\nstruct WithdrawalBatch {\n  // Total scaled amount of tokens to be withdrawn\n  uint104 scaledTotalAmount;\n  // Amount of scaled tokens that have been paid by borrower\n  uint104 scaledAmountBurned;\n  // Amount of normalized tokens that have been paid by borrower\n  uint128 normalizedAmountPaid;\n}\n\nstruct AccountWithdrawalStatus {\n  uint104 scaledAmount;\n  uint128 normalizedAmountWithdrawn;\n}\n\nstruct WithdrawalData {\n  FIFOQueue unpaidBatches;\n  mapping(uint32 => WithdrawalBatch) batches;\n  mapping(uint256 => mapping(address => AccountWithdrawalStatus)) accountStatuses;\n}\n\nlibrary WithdrawalLib {\n  function scaledOwedAmount(WithdrawalBatch memory batch) internal pure returns (uint104) {\n    return batch.scaledTotalAmount - batch.scaledAmountBurned;\n  }\n\n  /**\n   * @dev Get the amount of assets which are not already reserved\n   *      for prior withdrawal batches. This must only be used on\n   *      the latest withdrawal batch to expire.\n   */\n  function availableLiquidityForPendingBatch(\n    WithdrawalBatch memory batch,\n    MarketState memory state,\n    uint256 totalAssets\n  ) internal pure returns (uint256) {\n    // Subtract normalized value of pending scaled withdrawals, processed\n    // withdrawals and protocol fees.\n    uint256 priorScaledAmountPending = (state.scaledPendingWithdrawals - batch.scaledOwedAmount());\n    uint256 unavailableAssets = state.normalizedUnclaimedWithdrawals +\n      state.normalizeAmount(priorScaledAmountPending) +\n      state.accruedProtocolFees;\n    return totalAssets.satSub(unavailableAssets);\n  }\n}\n"},{"file_path":"src/libraries/LibERC20.sol","source_code":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.4;\n\nimport './StringQuery.sol';\n\n/// @notice Safe ERC20 library\n/// @author d1ll0n\n/// @notice Changes from solady:\n///   - Removed Permit2 and ETH functions\n///   - `balanceOf(address)` reverts if the call fails or does not return >=32 bytes\n///   - Added queries for `name`, `symbol`, `decimals`\n///   - Set name to LibERC20 as it has queries unrelated to transfers and ETH functions were removed\n/// @author Modified from Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibERC20.sol)\n/// @author Previously modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibERC20.sol)\n///\n/// @dev Note:\n/// - For ERC20s, this implementation won't check that a token has code,\n///   responsibility is delegated to the caller.\nlibrary LibERC20 {\n  /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n  /*                       CUSTOM ERRORS                        */\n  /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n  /// @dev The ERC20 `transferFrom` has failed.\n  error TransferFromFailed();\n\n  /// @dev The ERC20 `transfer` has failed.\n  error TransferFailed();\n\n  /// @dev The ERC20 `balanceOf` call has failed.\n  error BalanceOfFailed();\n\n  /// @dev The ERC20 `name` call has failed.\n  error NameFailed();\n\n  /// @dev The ERC20 `symbol` call has failed.\n  error SymbolFailed();\n\n  /// @dev The ERC20 `decimals` call has failed.\n  error DecimalsFailed();\n\n  /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/\n  /*                      ERC20 OPERATIONS                      */\n  /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/\n\n  /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.\n  /// Reverts upon failure.\n  ///\n  /// The `from` account must have at least `amount` approved for\n  /// the current contract to manage.\n  function safeTransferFrom(address token, address from, address to, uint256 amount) internal {\n    /// @solidity memory-safe-assembly\n    assembly {\n      let m := mload(0x40) // Cache the free memory pointer.\n      mstore(0x60, amount) // Store the `amount` argument.\n      mstore(0x40, to) // Store the `to` argument.\n      mstore(0x2c, shl(96, from)) // Store the `from` argument.\n      mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.\n      // Perform the transfer, reverting upon failure.\n      if iszero(\n        and(\n          // The arguments of `and` are evaluated from right to left.\n          or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n          call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)\n        )\n      ) {\n        mstore(0x00, 0x7939f424) // `TransferFromFailed()`.\n        revert(0x1c, 0x04)\n      }\n      mstore(0x60, 0) // Restore the zero slot to zero.\n      mstore(0x40, m) // Restore the free memory pointer.\n    }\n  }\n\n  /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.\n  /// Reverts upon failure.\n  function safeTransfer(address token, address to, uint256 amount) internal {\n    /// @solidity memory-safe-assembly\n    assembly {\n      mstore(0x14, to) // Store the `to` argument.\n      mstore(0x34, amount) // Store the `amount` argument.\n      mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n      // Perform the transfer, reverting upon failure.\n      if iszero(\n        and(\n          // The arguments of `and` are evaluated from right to left.\n          or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n          call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n        )\n      ) {\n        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n        revert(0x1c, 0x04)\n      }\n      mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n    }\n  }\n\n  /// @dev Sends all of ERC20 `token` from the current contract to `to`.\n  /// Reverts upon failure.\n  function safeTransferAll(address token, address to) internal returns (uint256 amount) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.\n      mstore(0x20, address()) // Store the address of the current contract.\n      // Read the balance, reverting upon failure.\n      if iszero(\n        and(\n          // The arguments of `and` are evaluated from right to left.\n          gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n          staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)\n        )\n      ) {\n        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n        revert(0x1c, 0x04)\n      }\n      mstore(0x14, to) // Store the `to` argument.\n      amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.\n      mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.\n      // Perform the transfer, reverting upon failure.\n      if iszero(\n        and(\n          // The arguments of `and` are evaluated from right to left.\n          or(eq(mload(0x00), 1), iszero(returndatasize())), // Returned 1 or nothing.\n          call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)\n        )\n      ) {\n        mstore(0x00, 0x90b8ec18) // `TransferFailed()`.\n        revert(0x1c, 0x04)\n      }\n      mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.\n    }\n  }\n\n  /// @dev Returns the amount of ERC20 `token` owned by `account`.\n  /// Reverts if the call to `balanceOf` reverts or returns less than 32 bytes.\n  function balanceOf(address token, address account) internal view returns (uint256 amount) {\n    /// @solidity memory-safe-assembly\n    assembly {\n      mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.\n      mstore(0x20, account) // Store the `account` argument.\n      // Read the balance, reverting upon failure.\n      if iszero(\n        and(\n          // The arguments of `and` are evaluated from right to left.\n          gt(returndatasize(), 0x1f), // At least 32 bytes returned.\n          staticcall(gas(), token, 0x1c, 0x24, 0x00, 0x20)\n        )\n      ) {\n        mstore(0x00, 0x4963f6d5) // `BalanceOfFailed()`.\n        revert(0x1c, 0x04)\n      }\n      amount := mload(0x00)\n    }\n  }\n\n  /// @dev Returns the `decimals` of ERC20 `token`.\n  /// Reverts if the call to `decimals` reverts or returns less than 32 bytes.\n  function decimals(address token) internal view returns (uint8 _decimals) {\n    assembly {\n      // Write selector for `decimals()` to the end of the first word\n      // of scratch space.\n      mstore(0, 0x313ce567)\n      // Call `asset.decimals()`, writing up to 32 bytes of returndata\n      // to scratch space, overwriting the calldata used for the call.\n      // Reverts if the call fails, does not return exactly 32 bytes, or the returndata\n      // exceeds 8 bits.\n      if iszero(\n        and(\n          and(eq(returndatasize(), 0x20), lt(mload(0), 0x100)),\n          staticcall(gas(), token, 0x1c, 0x04, 0, 0x20)\n        )\n      ) {\n        mstore(0x00, 0x3394d170) // `DecimalsFailed()`.\n        revert(0x1c, 0x04)\n      }\n      // Read the return value from scratch space\n      _decimals := mload(0)\n    }\n  }\n\n  /// @dev Returns the `name` of ERC20 `token`.\n  /// Reverts if the call to `name` reverts or returns a value which is neither\n  /// a bytes32 string nor a valid ABI-encoded string.\n  function name(address token) internal view returns (string memory) {\n    // The `name` function selector is 0x06fdde03.\n    // The `NameFailed` error selector is 0x2ed09f54.\n    return queryStringOrBytes32AsString(token, 0x06fdde03, 0x2ed09f54);\n  }\n\n  /// @dev Returns the `symbol` of ERC20 `token`.\n  /// Reverts if the call to `symbol` reverts or returns a value which is neither\n  /// a bytes32 string nor a valid ABI-encoded string.\n  function symbol(address token) internal view returns (string memory) {\n    // The `symbol` function selector is 0x95d89b41.\n    // The `SymbolFailed` error selector is 0x3ddcc60a.\n    return queryStringOrBytes32AsString(token, 0x95d89b41, 0x3ddcc60a);\n  }\n}\n"}],"is_verified_via_sourcify":true,"can_be_visualized_via_sol2uml":true,"evm_version":"cancun","language":"solidity","is_verified_via_eth_bytecode_db":true,"is_fully_verified":false,"license_type":"none","is_blueprint":false,"name":"WildcatMarket","creation_bytecode":"0x6102606040523461020357610012610207565b6040516155ef908161045b8239608051818181610f8f015261107a015260a051818181610ca701528181610de2015281816112000152818161190d01528181611b1e01528181611d33015281816120bb0152818161221e01528181612321015281816124db015281816134e50152818161372901528181613c020152818161401a015261418f015260c051818181612053015281816125df01528181614666015261511a015260e05181818161041c01528181610d9d0152818161169301528181611ca2015281816120090152818161247b0152818161463801526150c7015261010051818181611a770152611c6c015261012051818181610efd01526121a3015261014051818181610f3801528181612d4601528181612e2b0152818161311601526131eb01526101605181818161102b01528181612d2501528181612e0a015281816130f501526131ca0152610180518181816118510152613dbf01526101a05181610b8701526101c05181818161045f01528181610c3501528181610d110152818161123701528181611fc3015281816120e6015281816121c401528181612617015281816137f50152818161382c015281816140460152818161414001526150ee01526101e051816106160152610200518161063a015261022051816117ef015261024051816118130152f35b5f80fd5b6103ad6103a861010033815261021b610432565b8051610397906001600160a01b03166101c09081528261038661036f610245602084015160ff1690565b6101a09081526040840151946101e095865261037861036f6060870151976102009889528760808101519c6102209d8e5261032960a083015191610240928352610120926102c26102bb6102b06102a48789015160018060801b031690565b6001600160801b031690565b9a87015161ffff1690565b61ffff1690565b98610160996102d86102bb8c89015161ffff1690565b6102ec6102bb610140809a015161ffff1690565b9260081b5f55676765c793fa10079d606b1b9260201b9060301b179060401b4260c01b1717176003558c015160a0528b015160018060a01b031690565b60c09081528a01516001600160a01b031660e09081528a01516001600160a01b031690526103616102bb610180809b015161ffff1690565b90528a015163ffffffff1690565b63ffffffff1690565b905286015163ffffffff1690565b90528201516001600160a01b031690565b60805201516001600160a01b031690565b6103af565b565b60018060a01b03608051165f80526020527f2ac55ae7ba47db34b5334622acafeb34a65daf143b47019273185d64c73a35a560405fa1807f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d5556020527ff33499cccaa0611882086224cc48cd82ef54b66a4d2edf4ed67108dd516896d560405fa1565b6040516102608082016040526304032dbb5f5280826004601c335afa903d141615610203579056fe60806040526004361015610011575f80fd5b5f3560e01c8062ae3bf8146103ce57806301e1d114146103c957806302372c4f146103c457806306fdde03146103bf578063088fee5e146103ba578063095ea7b3146103b55780630c1e3fea146103b05780630c3f6acf146103ab5780630cd1a5b6146103a657806311057cd0146103a157806314a1c32d1461039c57806318160ddd146103975780631d8557d7146103925780631da24f3e1461038d5780631e3cef531461038857806323b872dd146103835780632ab4d0521461037e578063313ce5671461037957806334bca29c14610374578063371fd8e61461036f57806338d52e0f1461036a5780633c231166146103655780633f3e4c1114610360578063469048401461035b5780634be687c6146103565780634c6c848f14610351578063514a4cd61461034c57806354635570146102b157806354b302c51461034757806354fd4d50146103425780636731ba6d1461033d578063683dd191146103385780636b174f351461033357806370a082311461032e5780637243d96c14610329578063739ccdd314610324578063740588591461031f578063766360171461031a5780637df1f1b914610315578063878eb9211461031057806395d89b411461030b5780639e6f980214610306578063a9059cbb14610301578063ae6ea191146102fc578063b1bf962d146102f7578063b68ce7a2146102f2578063b6b55f25146102ed578063c2b6b58c146102e8578063c45a0155146102e3578063c511ed5e146102de578063c5ebeaec146102d9578063c8796572146102d4578063cd7033c4146102cf578063d98e0fe8146102ca578063dbcd50b4146102c5578063dcd549d4146102c0578063dd62ed3e146102bb578063e5adc635146102b6578063e7e5db4f146102b15763f58c251c146102ac575f80fd5b6125b3565b61104e565b612457565b6123dc565b6122db565b612265565b612241565b612207565b61211e565b611ff3565b611c90565b611c40565b611c1f565b611bde565b611bb5565b611b83565b611a37565b611874565b61183a565b6117d5565b6116f8565b611667565b611623565b6114e9565b611451565b6113cc565b611361565b61129e565b61126a565b6110e6565b6110c2565b61109e565b611014565b610f5b565b610f21565b610ed1565b610d87565b610d35565b610ce5565b610c03565b610bab565b610b6e565b610b3d565b610a41565b6109fa565b61099a565b61095e565b61091d565b6108f1565b6108cd565b61088b565b61085b565b610835565b6107e0565b610661565b6105fc565b61055e565b610506565b6103f5565b73ffffffffffffffffffffffffffffffffffffffff8116036103f157565b5f80fd5b346103f15760206003193601126103f157600435610412816103d3565b61041a612bf8565b7f000000000000000000000000000000000000000000000000000000000000000033186104f95773ffffffffffffffffffffffffffffffffffffffff808216308114917f00000000000000000000000000000000000000000000000000000000000000001614176104ec576370a082315f5230602052602060346024601c845afa601f3d1116156104df575f6044601082602094336014526fa9059cbb00000000000000000000000082525af13d1560015f51141716156104df576104dd612c16565b005b6390b8ec185f526004601cfd5b6311530cde5f526004601cfd5b6302171e6a5f526004601cfd5b346103f1575f6003193601126103f1576020610520612603565b604051908152f35b63ffffffff8116036103f157565b60031960409101126103f15760043561054e816103d3565b9060243561055b81610528565b90565b346103f157604061056e36610536565b6105c0610579612681565b925f845263ffffffff60208501935f8552610592612c1f565b165f526008602052845f209073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b54906cffffffffffffffffffffffffff82168093526fffffffffffffffffffffffffffffffff809260681c168152835192835251166020820152f35b346103f1575f6003193601126103f15760205f525f6020527f0000000000000000000000000000000000000000000000000000000000000000603f527f0000000000000000000000000000000000000000000000000000000000000000605f5260805ff35b346103f15761066f36610536565b90610678612c1f565b63ffffffff9182811691428310156107d3576106f76106f26107819261079696610786966106a4612c2b565b9391506106af61274b565b50160361079a576106cf909563ffffffff165f52600860205260405f2090565b9073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b6127ab565b9161072d61071860208501516fffffffffffffffffffffffffffffffff1690565b6fffffffffffffffffffffffffffffffff1690565b9261076861075461075461071860408601516fffffffffffffffffffffffffffffffff1690565b92516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff809116921690612ea7565b612811565b6040519081529081906020820190565b0390f35b506106cf6107be6107b98763ffffffff165f52600760205260405f2090565b612765565b9563ffffffff165f52600860205260405f2090565b632561b8805f526004601cfd5b346103f15760406003193601126103f157610823600435610800816103d3565b610808612bf8565b61081e610813612edb565b916024359033612f1f565b614d13565b5f63929eee145d602060405160018152f35b346103f1575f6003193601126103f15761084d61281e565b506101c0610859612880565bf35b346103f1575f6003193601126103f15761087361281e565b5061087c612c1f565b6101c0610887612c2b565b5050f35b346103f1575f6003193601126103f1576108a3612c1f565b60206fffffffffffffffffffffffffffffffff60406108c0612c2b565b5050015116604051908152f35b346103f1575f6003193601126103f157602061ffff60035460301c16604051908152f35b346103f1575f6003193601126103f157610909612c1f565b6020610520610916612c2b565b5050612f95565b346103f1575f6003193601126103f157610935612c1f565b6020610520610942612c2b565b50506cffffffffffffffffffffffffff60808201511690613e0d565b346103f1575f6003193601126103f157610976612bf8565b610991610981612edb565b61081e61098c612fe6565b61323f565b5f63929eee145d005b346103f15760206003193601126103f15773ffffffffffffffffffffffffffffffffffffffff6004356109cc816103d3565b6109d4612c1f565b165f52600460205260206cffffffffffffffffffffffffff60405f205416604051908152f35b346103f1575f6003193601126103f1576020610a27610a17612c2b565b5050610a21612603565b906133d4565b6fffffffffffffffffffffffffffffffff60405191168152f35b346103f15760606003193601126103f157600435610a5e816103d3565b602435610a6a816103d3565b604435610a75612bf8565b610a7d612edb565b9173ffffffffffffffffffffffffffffffffffffffff84165f526009602052610ac660405f203373ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8103610b11575b509061081e91610afe94613497565b5f63929eee145d60405160018152602090f35b9190818303928311610b3857610afe94610b2f61081e943383612f1f565b94509091610aef565b6127e4565b346103f1575f6003193601126103f15760206fffffffffffffffffffffffffffffffff5f5460081c16604051908152f35b346103f1575f6003193601126103f157602060405160ff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346103f1576020610bf4610bbe36610536565b9190610bc8612bf8565b61081e610bee610bd6612edb565b92610bdf612fe6565b9560445f523615519187613627565b9361323f565b5f63929eee145d604051908152f35b346103f15760206003193601126103f157600435610c1f612bf8565b610c27612edb565b8115610cd857610c598230337f000000000000000000000000000000000000000000000000000000000000000061385a565b815f52337fe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa660205fa2610c8a612fe6565b918251610ccb576109919261098c61081e9260245f5282361551917f00000000000000000000000000000000000000000000000000000000000000006138d9565b6361d1bc8f5f526004601cfd5b637e0820885f526004601cfd5b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346103f1575f6003193601126103f15760207f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d55473ffffffffffffffffffffffffffffffffffffffff60405191168152f35b346103f15760206003193601126103f1576004357f000000000000000000000000000000000000000000000000000000000000000033186104f957610dca612bf8565b610dd2612edb565b610dda612fe6565b8051610ec4577f000000000000000000000000000000000000000000000000000000000000000060018160571c16610e4b575b5082610e3e61081e9261098c610e25610e439761393f565b6fffffffffffffffffffffffffffffffff166020830152565b61395e565b6104dd612c16565b5f80917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36019082601c6040519363849da12985528960208601526101c088604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc575f610e0d565b3d5f803e3d5ffd5b6381b210785f526004601cfd5b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346103f1575f6003193601126103f15760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346103f15760206003193601126103f157600435610f78816103d3565b73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163303611007577f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d581815491555f526020527ff33499cccaa0611882086224cc48cd82ef54b66a4d2edf4ed67108dd516896d560405fa1005b634ee0b8f85f526004601cfd5b346103f1575f6003193601126103f15760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346103f1575f6003193601126103f15760206105206110bb612c2b565b5050613987565b346103f1575f6003193601126103f1575f6040526101326041526020805260606020f35b346103f15760406003193601126103f157600435611102612bf8565b61110a612edb565b811515918261122f575b61111c612fe6565b926111278451151590565b61122a576111eb575b5061118261113c612603565b61117c61071861115f60608701516fffffffffffffffffffffffffffffffff1690565b60408701516fffffffffffffffffffffffffffffffff16906129a8565b90612811565b9061119f6111916107186139bc565b602435818082039110020190565b5f925b816111ac856129cc565b9410806111e2575b156111d557806111c76111d092876139de565b80820391110290565b6111a2565b610e438361081e8761323f565b508015156111b4565b61122490836111fd60445f5236155190565b917f00000000000000000000000000000000000000000000000000000000000000006138d9565b5f611130565b610ccb565b61125b8130337f000000000000000000000000000000000000000000000000000000000000000061385a565b61126581336138af565b611114565b346103f1575f6003193601126103f157611282612c1f565b60206dffffffffffffffffffffffffffff6101806108c0612c2b565b346103f15760206003193601126103f1576004356112ba612bf8565b6112c2612edb565b6112ca612fe6565b916112ea6dffffffffffffffffffffffffffff61018085015116826151cf565b6113056cffffffffffffffffffffffffff82168092146151b6565b80156113545761079693611336926113309261132033613b42565b9260245f52361551933391613ba6565b91614d13565b5f63929eee145d60405163ffffffff90911681529081906020820190565b63d61c50f85f526004601cfd5b346103f15760206003193601126103f1576020610520600435611383816103d3565b61138b612c1f565b73ffffffffffffffffffffffffffffffffffffffff6113a8612c2b565b505091165f52600483526cffffffffffffffffffffffffff60405f20541690613e0d565b346103f1575f6003193601126103f1576113e4612bf8565b6113ec612edb565b6113f4612fe6565b906113fe33613b42565b916cffffffffffffffffffffffffff8351168015611354576107969382611330926114416dffffffffffffffffffffffffffff610180611336970151168261529f565b9160045f52361551933391613ba6565b346103f1575f6003193601126103f157611469612c1f565b6020610520611476612c2b565b5050613e2d565b9181601f840112156103f15782359167ffffffffffffffff83116103f1576020808501948460051b0101116103f157565b60209060206040818301928281528551809452019301915f5b8281106114d5575050505090565b8351855293810193928101926001016114c7565b346103f15760406003193601126103f15767ffffffffffffffff6004358181116103f15761151b90369060040161147d565b90916024359081116103f15761153590369060040161147d565b919092611540612bf8565b611548612edb565b938383036116165761156161155c846129f9565b612707565b938385527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe061158f856129f9565b0136602087013761159e612fe6565b935f5b8181106115cd57610796876115b98a61081e8a61323f565b6115c1612c16565b604051918291826114ae565b806116056115de6001938589612a3e565b356115e8816103d3565b6115f3838789612a3e565b356115fd81610528565b36918a613627565b61160f828a612a53565b52016115a1565b639d89020a5f526004601cfd5b346103f1575f6003193601126103f15761163b612c1f565b6020611645612c2b565b5050611658611652612603565b91613e2d565b90604051918082039111028152f35b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b60209060206040818301928281528551809452019301915f5b8281106116de575050505090565b835163ffffffff16855293810193928101926001016116d0565b346103f1575f6003193601126103f157611710612c1f565b6005546fffffffffffffffffffffffffffffffff81169060801c818103908111610b385761174061155c826129f9565b918183527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe061176e836129f9565b013660208501375f5b82811061178c576040518061079686826116b7565b806117cf6117ba6117b06117a260019587612a67565b5f52600660205260405f2090565b5463ffffffff1690565b6117c48388612a53565b9063ffffffff169052565b01611777565b346103f1575f6003193601126103f15760205f525f6020527f0000000000000000000000000000000000000000000000000000000000000000603f527f0000000000000000000000000000000000000000000000000000000000000000605f5260805ff35b346103f1575f6003193601126103f15760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346103f15760406003193601126103f157600435611891816103d3565b6024359061189d612bf8565b6118a5612edb565b906118ae612fe6565b926118ce6dffffffffffffffffffffffffffff61018086015116826151cf565b916cffffffffffffffffffffffffff926118ec8482168092146151b6565b8015611a08578561098c8261199661081e976119316108239b611a029789337f0000000000000000000000000000000000000000000000000000000000000000614f73565b61193a33613b42565b9080611949858285511661340b565b168252335f9081526004602052604090205b9151166cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b6119d56119c26119a587613b42565b926119bd84516cffffffffffffffffffffffffff1690565b613476565b6cffffffffffffffffffffffffff168252565b6119fd8573ffffffffffffffffffffffffffffffffffffffff165f52600460205260405f2090565b61342a565b33615011565b63ddee9b305f526004601cfd5b6004359061ffff821682036103f157565b6024359061ffff821682036103f157565b346103f15760206003193601126103f157611a50611a15565b611a58612bf8565b611a60612edb565b73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000163303611b765761ffff82166103e88111611b7157611ab3612fe6565b8051611b6c578061081e92610e4395610120830191611ade611ad7845161ffff1690565b61ffff1690565b8103611aee575b5050505061323f565b81611b6093611b427f4b34705283cdb9398d0e50b216b8fb424c6d4def5db9bfadc661ee3adc6076ee96611b4b947f0000000000000000000000000000000000000000000000000000000000000000613efd565b9061ffff169052565b60405161ffff90911681529081906020820190565b0390a1805f8080611ae5565b613ef0565b613ee3565b6332cc72365f526004601cfd5b346103f1575f6003193601126103f157611b9b612c1f565b60206cffffffffffffffffffffffffff60806108c0612c2b565b346103f15760206003193601126103f1576020611bd0612edb565b610520611330600435613f7b565b346103f15760206003193601126103f157600435611bfa612edb565b90611c0481613f7b565b03611c12576104dd90614d13565b638a164f635f526004601cfd5b346103f1575f6003193601126103f157602060ff5f54166040519015158152f35b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346103f1575f6003193601126103f1577f00000000000000000000000000000000000000000000000000000000000000008033186104f957611cd0612bf8565b611cd8612edb565b611ce0612fe6565b91611ceb8351151590565b611fee57611d9590611cfb612603565b90611d0585612f95565b9081831015611f9e575090611d1d81611d2d93612811565b90611d28828761412c565b612a67565b611d57847f000000000000000000000000000000000000000000000000000000000000000061420d565b5f610140850152600184526127106101608501525f61010085015261117c61071861115f60608701516fffffffffffffffffffffffffffffffff1690565b60c08301805163ffffffff908116918280611e27575b50505050611dba6107186139bc565b905f905b828210611e0f575050506cffffffffffffffffffffffffff611df060a08401516cffffffffffffffffffffffffff1690565b16611e0a57611e01610e439261323f565b61081e4261450a565b6144fd565b611e1f8161117c600193886139de565b910190611dbe565b611e426107b98563ffffffff165f52600760205260405f2090565b6020810180516cffffffffffffffffffffffffff1689611e84611e7285516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff80931610611f42575b5090611f0d92915f8652806fffffffffffffffffffffffffffffffff611f026040611eea611ed688516cffffffffffffffffffffffffff1690565b96516cffffffffffffffffffffffffff1690565b9601516fffffffffffffffffffffffffffffffff1690565b169316911684614477565b611f16816144b1565b4214611f23575b80611dab565b6117c4611f32611f3a94612b53565b9283166144d7565b5f8080611f1d565b886fffffffffffffffffffffffffffffffff611f698695949b8b611f7295611f0d99614264565b90501690612811565b97611f9483611f8f8a63ffffffff165f52600760205260405f2090565b612a74565b9091925089611e9b565b90808311611fae575b5050611d2d565b91610781611fbf611fe79483612811565b80937f00000000000000000000000000000000000000000000000000000000000000006140f2565b5f80611fa7565b6140e5565b346103f15760206003193601126103f1576004357f00000000000000000000000000000000000000000000000000000000000000008033186104f957612037612bf8565b61203f612edb565b906395c098395f5260205260205f6024601c7f00000000000000000000000000000000000000000000000000000000000000005afa60203d141615610ebc575f516121195761208c612fe6565b8051612114576120a361209d612603565b82613eda565b831161210f578261210a826120df61081e94610e43977f000000000000000000000000000000000000000000000000000000000000000061455a565b61098c83337f00000000000000000000000000000000000000000000000000000000000000006140f2565b6145d8565b61454d565b614540565b614533565b346103f1575f6003193601126103f157612136612bf8565b61213e612edb565b612146612fe6565b9060408201916fffffffffffffffffffffffffffffffff9081845116156121fa57612178612172612603565b826133d4565b8281169182156121ed57858461219a6121e89461081e97610e439a5116612b68565b16905261098c837f00000000000000000000000000000000000000000000000000000000000000007f00000000000000000000000000000000000000000000000000000000000000006140f2565b614601565b63f784cfa45f526004601cfd5b6345c835cb5f526004601cfd5b346103f1575f6003193601126103f15760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346103f1575f6003193601126103f157602060035461ffff6040519160401c168152f35b346103f15760206003193601126103f157606061229c60043561228781610528565b61228f61274b565b612297612c1f565b612b8a565b6fffffffffffffffffffffffffffffffff60408051926cffffffffffffffffffffffffff80825116855260208201511660208501520151166040820152f35b346103f15760206003193601126103f1576004356122f8816103d3565b612300612bf8565b612308612edb565b6123118261462a565b156123cf5761231e612fe6565b917f000000000000000000000000000000000000000000000000000000000000000060018160581c1661235e575b508261098c61081e92610e4395614699565b5f80917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36019082601c60405193638b3ce9b385528760208601526101c08a604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc575f61234c565b63a97ab1675f526004601cfd5b346103f15760406003193601126103f157602061244e6004356123fe816103d3565b73ffffffffffffffffffffffffffffffffffffffff60243591612420836103d3565b165f526009835260405f209073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b54604051908152f35b346103f15760406003193601126103f157612470611a15565b612478611a26565b907f000000000000000000000000000000000000000000000000000000000000000033186104f9576124a8612bf8565b6124b0612edb565b906124b9612fe6565b80516125ae576124ff816101608101956124d8611ad7885161ffff1690565b947f0000000000000000000000000000000000000000000000000000000000000000614760565b61ffff959186811694612710978887116125a95783169788116125a4578711928315612588575b61254392612537919061ffff169052565b61ffff16610140840152565b612566575b9261256161081e9261255c610e439661323f565b614831565b61485a565b9261257084613e2d565b612578612603565b106125835792612548565b614824565b61259185613e2d565b612599612603565b101561252657614817565b61480a565b6147fd565b614753565b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b6370a082315f523060205260205f6024601c7f00000000000000000000000000000000000000000000000000000000000000005afa601f3d111615612647575f5190565b634963f6d55f526004601cfd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b604051906040820182811067ffffffffffffffff8211176126a157604052565b612654565b604051906060820182811067ffffffffffffffff8211176126a157604052565b604051906101c0820182811067ffffffffffffffff8211176126a157604052565b604051906020820182811067ffffffffffffffff8211176126a157604052565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f604051930116820182811067ffffffffffffffff8211176126a157604052565b6127536126a6565b905f82525f60208301525f6040830152565b906fffffffffffffffffffffffffffffffff60016127816126a6565b9380546cffffffffffffffffffffffffff90818116875260681c1660208601520154166040830152565b906fffffffffffffffffffffffffffffffff6127c5612681565b92546cffffffffffffffffffffffffff8116845260681c166020830152565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b91908203918211610b3857565b6128266126c6565b905f82525f60208301525f60408301525f60608301525f60808301525f60a08301525f60c08301525f60e08301525f6101008301525f6101208301525f6101408301525f6101608301525f6101808301525f6101a0830152565b6128886126c6565b906128ce5f5461289d60ff8216859015159052565b60081c6fffffffffffffffffffffffffffffffff9081166020850152600154908116604085015260801c6060840152565b6002546cffffffffffffffffffffffffff8082166080850152606882901c1660a084015263ffffffff60d082901c811660c08501526129859161291b9060ff9060f01c16151560e0860152565b60035463ffffffff8282161661010086015261ffff602082901c8116610120870152603082901c8116610140870152604082901c16610160860152605081901c6dffffffffffffffffffffffffffff1661018086015260c01c166101a084019063ffffffff169052565b565b9060016fffffffffffffffffffffffffffffffff80931601918211610b3857565b9190916fffffffffffffffffffffffffffffffff80809416911601918211610b3857565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114610b385760010190565b67ffffffffffffffff81116126a15760051b60200190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b9190811015612a4e5760051b0190565b612a11565b8051821015612a4e5760209160051b010190565b91908201809211610b3857565b604060016fffffffffffffffffffffffffffffffff92612ad86cffffffffffffffffffffffffff86511682906cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b60208501517fffffffffffff00000000000000000000000000ffffffffffffffffffffffffff79ffffffffffffffffffffffffff0000000000000000000000000083549260681b16911617815501920151167fffffffffffffffffffffffffffffffff00000000000000000000000000000000825416179055565b90600163ffffffff80931601918211610b3857565b6fffffffffffffffffffffffffffffffff9182169082160391908211610b3857565b9190612b94612c2b565b915063ffffffff809316928315159116831416612bf357505f5260076020526fffffffffffffffffffffffffffffffff600160405f2080546cffffffffffffffffffffffffff90818116875260681c1660208601520154166040830152565b925050565b63929eee14805c612c09576001905d565b637fa8a9875f526004601cfd5b5f63929eee145d565b63929eee145c612c0957565b612c3361281e565b505f612c3d61274b565b612c45612880565b92612c5f8460c063ffffffff910151168042119015151690565b612d73575b6101a084015163ffffffff904290821603612d1f575b60c085015163ffffffff16908116612c8f5750565b92509050612cae6107b98363ffffffff165f52600760205260405f2090565b90612cc960208301516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff612cf1611e7285516cffffffffffffffffffffffffff1690565b911610612cfa57565b612d0c612d05612603565b85846149e2565b80612d145750565b612985908584614a6b565b612d6b427f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000088614883565b505050612c7a565b91505060c08201612d88815163ffffffff1690565b91612da7612d9e6101a086015163ffffffff1690565b63ffffffff1690565b63ffffffff8416908103612e04575b505f612dd36107b98563ffffffff165f52600760205260405f2090565b92612de6612ddf612603565b87866149e2565b80612df3575b5052612c64565b612dfe908786614a6b565b5f612dec565b612e50907f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000087614883565b5050612db6565b906b033b2e3c9fd0803ce800000091817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048111820215830215612e9a57020490565b63ad251c275f526004601cfd5b817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048111820215830215612e9a57020490565b604051608081019080821067ffffffffffffffff8311176126a15761055b9160405260608152606060208201525f60408201525f60608201525f3560e01c90614c2f565b909173ffffffffffffffffffffffffffffffffffffffff82165f52600960205280612f6b8460405f209073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b555f527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3565b612fb26cffffffffffffffffffffffffff60808301511682613e0d565b906fffffffffffffffffffffffffffffffff90816060820151168301809311610b385760400151168101809111610b385790565b612fee61281e565b50612ff7612880565b906130118260c063ffffffff910151168042119015151690565b61317f575b6101a082015163ffffffff908116428190036130eb575b5060c083015163ffffffff169081166130435750565b61305e6107b98263ffffffff165f52600760205260405f2090565b60208101516cffffffffffffffffffffffffff166cffffffffffffffffffffffffff61309a611e7284516cffffffffffffffffffffffffff1690565b9116106130a6575b5050565b6130b86130b1612603565b85836149e2565b806130c257505050565b826130d5611f8f92612985958886614264565b505063ffffffff165f52600760205260405f2090565b6131799061313b427f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000088614883565b9261317161315e6101808a95949501516dffffffffffffffffffffffffffff1690565b6dffffffffffffffffffffffffffff1690565b904290614d81565b5f61302d565b613193612d9e60c084015163ffffffff1690565b6131a8612d9e6101a085015163ffffffff1690565b8082036131c0575b50506131bb82614dcb565b613016565b81613210613238937f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000088614883565b93909261323261315e6101808a01516dffffffffffffffffffffffffffff1690565b91614d81565b5f806131b0565b6129859061324c81613e2d565b613254612603565b1060e08201819052908051151561328161071860208401516fffffffffffffffffffffffffffffffff1690565b60081b175f556132a761071860408301516fffffffffffffffffffffffffffffffff1690565b6132c761071860608401516fffffffffffffffffffffffffffffffff1690565b60801b176001556132eb611e7260808301516cffffffffffffffffffffffffff1690565b613308611e7260a08401516cffffffffffffffffffffffffff1690565b61331c612d9e60c085015163ffffffff1690565b9060681b9060d01b8460f01b171717600255613343612d9e61010083015163ffffffff1690565b613356611ad761012084015161ffff1690565b613369611ad761014085015161ffff1690565b9061337d611ad761016086015161ffff1690565b916133b2612d9e6101a06133a661315e6101808a01516dffffffffffffffffffffffffffff1690565b97015163ffffffff1690565b9160201b9060301b179160401b908460501b9060c01b17171717600355614f47565b906fffffffffffffffffffffffffffffffff91826060820151168203918211610b3857604083910151169081808203911002011690565b6cffffffffffffffffffffffffff9182169082160391908211610b3857565b6cffffffffffffffffffffffffff6129859251166cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b9190916cffffffffffffffffffffffffff80809416911601918211610b3857565b91906134a1612fe6565b926134c16dffffffffffffffffffffffffffff61018086015116846151cf565b6cffffffffffffffffffffffffff6134dd8183168093146151b6565b8115611a08577f0000000000000000000000000000000000000000000000000000000000000000600181605c1c1661359f575b509461098c61359a926135636129859861352987613b42565b9080613538858285511661340b565b16825261195b8873ffffffffffffffffffffffffffffffffffffffff165f52600460205260405f2090565b6135726119c26119a588613b42565b6119fd8673ffffffffffffffffffffffffffffffffffffffff165f52600460205260405f2090565b615011565b5f80917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c9893983601906040519163a018f90e83523360208401528760408401528860608401528660808401526101c08660a085015e610260808401528061028084015260646102a084013782601c610220360193019160601c5af115610ebc57945f613510565b909291926136466107b98563ffffffff165f52600760205260405f2090565b9361365b612d9e60c085015163ffffffff1690565b9063ffffffff811691821461385557613686836106cf8363ffffffff165f52600860205260405f2090565b946136d96137046136aa60408a01516fffffffffffffffffffffffffffffffff1690565b986136f96107188a54809c6cffffffffffffffffffffffffff968795516cffffffffffffffffffffffffff1690565b6fffffffffffffffffffffffffffffffff97889687921693169116612ea7565b9960681c1689612b68565b9081169788156138505760608761379b6137bc9361055b9b61374d6137d2988f9d8e8e7f0000000000000000000000000000000000000000000000000000000000000000615049565b907fffffff00000000000000000000000000000000ffffffffffffffffffffffffff7cffffffffffffffffffffffffffffffff0000000000000000000000000083549260681b169116179055565b01916137b783516fffffffffffffffffffffffffffffffff1690565b612b68565b6fffffffffffffffffffffffffffffffff169052565b836137dc8461462a565b156138245761381f916137ee856150b9565b61381983827f00000000000000000000000000000000000000000000000000000000000000006140f2565b85615151565b61518b565b61381f9150837f00000000000000000000000000000000000000000000000000000000000000006140f2565b61503c565b6107d3565b601c5f60649281946020966040519860605260405260601b602c526f23b872dd000000000000000000000000600c525af13d1560015f51141716156138a2575f606052604052565b637939f4245f526004601cfd5b905f527fe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa660205fa2565b600181605a1c166138eb575b50505050565b5f601c6101c08296958684973603928392604051986383d9e1eb8a5260208a0152604089015e61020080880152816102208801526102408701376102240193019160601c5af115610ebc575f8080806138e5565b906129856fffffffffffffffffffffffffffffffff83168093146151b6565b5f527ff2672935fc79f5237559e2e2999dbe743bf65430894ac2b37666890e7c69e1af60205fa1565b6111c76fffffffffffffffffffffffffffffffff602083015116916cffffffffffffffffffffffffff60808201511690613e0d565b61055b6005546fffffffffffffffffffffffffffffffff81169060801c612b68565b9190600554906fffffffffffffffffffffffffffffffff918281169060801c8114613afc575f52600660205281613a3d63ffffffff60405f2054169283613a366107b98263ffffffff165f52600760205260405f2090565b9788614264565b90501693613a5d81611f8f8463ffffffff165f52600760205260405f2090565b6cffffffffffffffffffffffffff6020818351169201511614613a7e575050565b600554918083169260801c8314613afc57613acd83612985945f52600660205260405f207fffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000008154169055612987565b167fffffffffffffffffffffffffffffffff0000000000000000000000000000000060055416176005556144b1565b60046040517f87274801000000000000000000000000000000000000000000000000000000008152fd5b906129856cffffffffffffffffffffffffff83168093146151b6565b905f613b4c6126e7565b5273ffffffffffffffffffffffffffffffffffffffff82165f526004602052613b9360405f206cffffffffffffffffffffffffff613b886126e7565b91541681529261462a565b613b9957565b636bc671fd5f526004601cfd5b9392959491909560c0850190613bc0825163ffffffff1690565b9763ffffffff92838a1615613d8e575b50938893613d4b93613d4484613c4961098c99613c266cffffffffffffffffffffffffff6129859e9d9916978d898d8a7f00000000000000000000000000000000000000000000000000000000000000006151f5565b6135726119c284613c4484516cffffffffffffffffffffffffff1690565b61340b565b613c54863086615011565b613ce1613c8e856106cf613c796107b98d63ffffffff165f52600760205260405f2090565b9b63ffffffff165f52600860205260405f2090565b613ca9836119bd83546cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b613d12613cff826119bd8b516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff168952565b613d3160a08b01916119bd83516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff169052565b8a1661526f565b613d5d613d56612603565b84836149e2565b80613d7c575b50611f8f8663ffffffff165f52600760205260405f2090565b613d8890878584614264565b50613d63565b93613dfc9950613d4b93613d44899894613c4961098c9995613ded612d9e613de76129859f613dbd9051151590565b7f000000000000000000000000000000000000000000000000000000000000000090815f03020190565b42612a67565b9e8f809b6117c48883166144d7565b959950509498995050935093613bd0565b906dffffffffffffffffffffffffffff61018061055b930151169061529f565b6cffffffffffffffffffffffffff8060a08301511690608083015116818103908111610b3857613e679061ffff61016085015116906152ee565b908101809111610b3857613e91906dffffffffffffffffffffffffffff610180840151169061529f565b6fffffffffffffffffffffffffffffffff6040830151168101809111610b3857613ed4610718606061055b9401516fffffffffffffffffffffffffffffffff1690565b90612a67565b6111c790613e2d565b63499fddb15f526004601cfd5b6337f1a75f5f526004601cfd5b919060018360551c16613f0f57505050565b5f9283601c81946101c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc360191604051966303473d8d88526020880152604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc57565b613f83612bf8565b613f8b612fe6565b90613f968251151590565b6140e057613fb390613fa783613987565b90818082039110020190565b90613fe4613fdf613fd961315e6101808501516dffffffffffffffffffffffffffff1690565b846151cf565b613b26565b906cffffffffffffffffffffffffff821680156140db576140d2926140b361098c9261409b61401233613b42565b61403e8784337f0000000000000000000000000000000000000000000000000000000000000000615343565b61406a8930337f000000000000000000000000000000000000000000000000000000000000000061385a565b6140886119c2866119bd84516cffffffffffffffffffffffffff1690565b335f90815260046020526040902061342a565b6140ac873361359a5f805236155190565b86336153cf565b613d3160808401916119bd83516cffffffffffffffffffffffffff1690565b90612985612c16565b615336565b615329565b63449e5f505f526004601cfd5b60105f60449260209582956014526034526fa9059cbb00000000000000000000000082525af13d1560015f51141716156104df575f603452565b8115610cd8578051610ccb576141648230337f000000000000000000000000000000000000000000000000000000000000000061385a565b815f52337fe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa660205fa27f000000000000000000000000000000000000000000000000000000000000000091600183605a1c166141bf57505050565b5f9283601c81946101c0600319360191604051966383d9e1eb88526020880152604087015e610200808601526102209080828701526004610240870137360193019160601c5af115610ebc57565b60018160591c1661421c575050565b5f91829182601c60031936016101c060405195639ecc64e68752602087015e6101e0808601526102009080828701526004610220870137360193019160601c5af115610ebc57565b9293916142b69161428285516cffffffffffffffffffffffffff1690565b9460208101956cffffffffffffffffffffffffff9485916142b089516cffffffffffffffffffffffffff1690565b9061340b565b16801561446a5761018083019788516142dc906dffffffffffffffffffffffffffff1690565b6dffffffffffffffffffffffffffff166142f5916151cf565b81811090829003020161430790613b26565b965193871693614327906dffffffffffffffffffffffffffff1685612e57565b6143309061393f565b9587815161434a906cffffffffffffffffffffffffff1690565b9061435491613476565b6cffffffffffffffffffffffffff16905260400180516143879087906fffffffffffffffffffffffffffffffff166129a8565b6fffffffffffffffffffffffffffffffff16905260a0810180516143bb9088906cffffffffffffffffffffffffff1661340b565b6cffffffffffffffffffffffffff1690526060810180516143ef9087906fffffffffffffffffffffffffffffffff166129a8565b6fffffffffffffffffffffffffffffffff16905260800180516144229087906cffffffffffffffffffffffffff1661340b565b6cffffffffffffffffffffffffff1690525f8052361551906fffffffffffffffffffffffffffffffff85169182309161445a92615011565b63ffffffff1691612985926153fd565b505f965086955050505050565b91929092604051935f526020526040527f9262dc39b47cad3a0512e4c08dda248cb345e7163058f300bc63f56bda288b6e60605fa2604052565b7fcbdf25bf6e096dd9030d89bb2ba2e3e7adb82d25a233c3ca3d92e9f098b74e555f80a2565b7f5c9a946d3041134198ebefcd814de7748def6576efd3d1b48f48193e183e89ef5f80a2565b634d7909975f526004601cfd5b5f527f9dc30b8eda31a6a144e092e5de600955523a6a925cc15cc1d1b9b4872cfa615560205fa1565b634a1c13a95f526004601cfd5b63d0242b285f526004601cfd5b63119fe6e35f526004601cfd5b9190600183605b1c1661456c57505050565b5f9283601c81946101c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601916040519663b1cfda0d88526020880152604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc57565b5f527fb848ae6b1253b6cb77e81464128ce8bd94d3d524fea54e801e0da869784dca3360205fa1565b5f527f860c0aa5520013080c2f65981705fcdea474d9f7c3daf954656ed5e65d692d1f60205fa1565b90604051916306e744445f527f000000000000000000000000000000000000000000000000000000000000000060205260405260205f6044601c7f00000000000000000000000000000000000000000000000000000000000000005afa60203d141615610ebc575f5191604052565b9073ffffffffffffffffffffffffffffffffffffffff81165f52600460205260405f20916cffffffffffffffffffffffffff6146d36126e7565b93541692838152836146e55750505050565b81614715918561470b6dffffffffffffffffffffffffffff61018088970151168261529f565b9485923694613ba6565b92604051935f526020526040527fe12b220b92469ae28fb0d79de531f94161431be9f073b96b8aad3effb88be6fa60605fa26040525f8080806138e5565b63b9de88a25f526004601cfd5b91909260018360561c165f146147f65791604093916101c05f947fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbc36019287519563cc4526428752602087015287860152606085015e6102208084015280610240840152604461026084013782601c610200360193019160601c5af11560403d1017610ebc5761ffff90815f5116916020511690565b5090509091565b63cf1f916f5f526004601cfd5b638ec830735f526004601cfd5b630a68e5bf5f526004601cfd5b63253ecbb95f526004601cfd5b5f527fff7b6c8be373823323d3c5d99f5d027dd409dce5db54eae511bbdd5546b7503760205fa1565b5f527f72877a153052500f5edbb2f9da96a0f45d671d4b4555fdf8628a709dc4eab43a60205fa1565b92939190915f925f9261ffff968761014088015116916101a088019363ffffffff93848651168403848111610b38576148bb91615545565b809a6101208b0151168061495d575b50508061493b575b5050614930610180612985959697980161491c6149178b613ed46149118d61490b61315e88516dffffffffffffffffffffffffffff1690565b93612a67565b8261529f565b615464565b6dffffffffffffffffffffffffffff169052565b1663ffffffff169052565b612985959697506149546149309261018092858c61542b565b979695506148d2565b6149a69298509061496d916152ee565b6149a06cffffffffffffffffffffffffff60808c015116916dffffffffffffffffffffffffffff6101808d01511661529f565b9061529f565b604089016fffffffffffffffffffffffffffffffff908181511691838301809311610b38576149d99083168093146151b6565b5295895f6148ca565b614a106cffffffffffffffffffffffffff916142b08360a0860151169184602081835116920151169061340b565b16906fffffffffffffffffffffffffffffffff90614a4b82606083015116936dffffffffffffffffffffffffffff610180840151169061529f565b8301809311610b385760400151168101809111610b385780820391110290565b80516cffffffffffffffffffffffffff1690614aad60208201926cffffffffffffffffffffffffff9182916142b086516cffffffffffffffffffffffffff1690565b168015614c27576101808501958651614ad3906dffffffffffffffffffffffffffff1690565b6dffffffffffffffffffffffffffff16614aec916151cf565b818110908290030201614afe90613b26565b9451614b1e916dffffffffffffffffffffffffffff909116908616612e57565b614b279061393f565b91848151614b41906cffffffffffffffffffffffffff1690565b90614b4b91613476565b6cffffffffffffffffffffffffff1690526040018051614b7e9083906fffffffffffffffffffffffffffffffff166129a8565b6fffffffffffffffffffffffffffffffff16905260a082018051614bb29085906cffffffffffffffffffffffffff1661340b565b6cffffffffffffffffffffffffff16905260608201908151614be3906fffffffffffffffffffffffffffffffff1690565b90614bed916129a8565b6fffffffffffffffffffffffffffffffff169052608001908151614c1d906cffffffffffffffffffffffffff1690565b90613d319161340b565b505050505050565b90819073ffffffffffffffffffffffffffffffffffffffff7f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d55416918260608501528215614d0c575060405190638925ca5a825260405f60209483868601523383860152606080860152366080860152368260a08701373660c4019082601c8701915af1835f51141615610ebc5760808361055b945160051b809460e06003830282010160405282820183823e80885201925f038184015281606084015285019260a08301845260a0019101525a60408401528251905190615481565b9392505050565b606081019073ffffffffffffffffffffffffffffffffffffffff825116156130a2575f8082518051908160061b95614d5060c08884010183615481565b519160051b019360405a91015103604085015283519463f0bd9468855260c4019082601c8601915af115610ebc5752565b927f18247a393d0531b65fbd94f5e78bc5639801a4efda62ae7b43533c4442116c3a959260c09592604051958652602086015260408501526060840152608083015260a0820152a1565b61298590611f8f60c082015f614de5825163ffffffff1690565b91614e016107b98463ffffffff165f52600760205260405f2090565b946020860190614e1e82516cffffffffffffffffffffffffff1690565b90614e39611e7289516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff80931610614f17575b50614ec6614e6b88516cffffffffffffffffffffffffff1690565b92614eb3614e8682516cffffffffffffffffffffffffff1690565b60408b015163ffffffff8a16966fffffffffffffffffffffffffffffffff90911691861690861687614477565b516cffffffffffffffffffffffffff1690565b90614ee1611e7289516cffffffffffffffffffffffffff1690565b9116108314614f095750614ef4836154b9565b5263ffffffff165f52600760205260405f2090565b614f12906144b1565b614ef4565b614f29614f22612603565b828a6149e2565b8681614f37575b5050614e50565b614f41928a614264565b86614f30565b5f526020527f9385f9ff65bcd2fb81cece54b27d4ec7376795fc4dcff686e370e347b0ed86c060405fa1565b9091939293600182605c1c16614f8b575b5050505050565b6101c05f959486957fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbc3601936040519663a018f90e885233602089015260408801526060870152608086015260a085015e610260808401528061028084015260446102a084013782601c610240360193019160601c5af115610ebc575f80808080614f84565b90915f527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa3565b63186334fe5f526004601cfd5b9091600182605d1c1661505d575050505050565b601c5f9594869592836101c08895360393849360405199632970403d8b5260208b015260408a0152606089015e61022080880152816102408801526102608701376102440193019160601c5af115610ebc575f80808080614f84565b906040519163a1054f6b5f527f00000000000000000000000000000000000000000000000000000000000000006020526040527f000000000000000000000000000000000000000000000000000000000000000060605260205f6064601c827f00000000000000000000000000000000000000000000000000000000000000005af160203d141615610ebc575f51916040525f606052565b91929092604051935f526020526040527f0d0843a0fcb8b83f625aafb6e42f234ac48c6728b207d52d97cfa8fbd34d498f60605fa2604052565b90915f527fd6cddb3d69146e96ebc2c87b1b3dd0b20ee2d3b0eadf134e011afb434a3e56e660205fa3565b156151bd57565b634e487b715f5260116020526024601cfd5b8160011c906b033b2e3c9fd0803ce8000000908183190481118415176151bd5702010490565b919394909294600183605e1c1661520e57505050505050565b5f958695836101c0601c94899636039485946040519a633521cccc8c5260208c015260408b015260608a0152608089015e61024080880152816102608801526102808701376102640193019160601c5af115610ebc575f8080808080614c27565b919290925f526020527fecc966b282a372469fa4d3e497c2ac17983c3eaed03f3f17c9acf4b15591663e60405fa3565b817ffffffffffffffffffffffffffffffffffffffffffe6268e1b017bfe18bffffff04811115821517156151bd576b033b2e3c9fd0803ce800000091026b019d971e4fe8401e74000000010490565b817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec7704811115821517156151bd576127109102611388010490565b6322d7c0435f526004601cfd5b63e4aa50555f526004601cfd5b929192600181605f1c166153575750505050565b5f601c81956101c083967fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36019260405197635aeb713f895260208901526040880152606087015e610220908180870152806102408701526024610260870137360193019160601c5af115610ebc575f8080806138e5565b91905f526020527f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a1560405fa2565b91905f526020527f5272034725119f19d7236de4129fdb5093f0dcb80282ca5edbd587df91d2bd8960405fa2565b909392935f9463ffffffff6101a0840151168203918211610b385761544f92615577565b9081615459575050565b61055b929350615545565b906129856dffffffffffffffffffffffffffff83168093146151b6565b9190825190818152602080809501918181019360051b0101915b8281106154a9575050509050565b815154815290840190840161549b565b6155039060055460801c90815f52600660205263ffffffff60405f2091167fffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000825416179055612987565b6fffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffff000000000000000000000000000000006005549260801b16911617600555565b69152d02c7e14af68000008082029180828404036151bd57830202918183041490151715610b38576301e13380900490565b90610100820163ffffffff9060e0828251169401516155b7576155a5858503868611029283168093146151b6565b52808203911102818082039110020190565b848493940191828411610b38576155d29083168093146151b6565b528082039111028082039111029056fea164736f6c6343000819000a","external_libraries":[],"proxy_type":null,"implementations":[],"verified_at":"2025-04-29T12:04:32.222749Z","is_verified_via_verifier_alliance":false,"compiler_version":"0.8.25+commit.b61c2a91","decoded_constructor_args":null,"sourcify_repo_url":"https://repo.sourcify.dev/1/0xC9499006a149C553d18171747ED19Aa7C6Dd19E2","optimization_runs":50000,"compiler_settings":{"evmVersion":"cancun","libraries":{},"metadata":{"bytecodeHash":"none"},"optimizer":{"enabled":true,"runs":50000},"remappings":[":ds-test/=lib/ds-test/src/",":erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",":ethereum-access-token/=lib/ethereum-access-token/contracts/",":forge-std/=lib/forge-std/src/",":openzeppelin-contracts/=lib/openzeppelin-contracts/",":openzeppelin/=lib/openzeppelin-contracts/",":sol-utils/=lib/sol-utils/src/",":solady/=lib/solady/src/",":solmate/=lib/solmate/src/",":src/=src/",":vulcan/=lib/vulcan/src/"],"viaIR":true},"is_verified":true,"verified_twin_address_hash":null,"optimization_enabled":true,"deployed_bytecode":"0x60806040526004361015610011575f80fd5b5f3560e01c8062ae3bf8146103ce57806301e1d114146103c957806302372c4f146103c457806306fdde03146103bf578063088fee5e146103ba578063095ea7b3146103b55780630c1e3fea146103b05780630c3f6acf146103ab5780630cd1a5b6146103a657806311057cd0146103a157806314a1c32d1461039c57806318160ddd146103975780631d8557d7146103925780631da24f3e1461038d5780631e3cef531461038857806323b872dd146103835780632ab4d0521461037e578063313ce5671461037957806334bca29c14610374578063371fd8e61461036f57806338d52e0f1461036a5780633c231166146103655780633f3e4c1114610360578063469048401461035b5780634be687c6146103565780634c6c848f14610351578063514a4cd61461034c57806354635570146102b157806354b302c51461034757806354fd4d50146103425780636731ba6d1461033d578063683dd191146103385780636b174f351461033357806370a082311461032e5780637243d96c14610329578063739ccdd314610324578063740588591461031f578063766360171461031a5780637df1f1b914610315578063878eb9211461031057806395d89b411461030b5780639e6f980214610306578063a9059cbb14610301578063ae6ea191146102fc578063b1bf962d146102f7578063b68ce7a2146102f2578063b6b55f25146102ed578063c2b6b58c146102e8578063c45a0155146102e3578063c511ed5e146102de578063c5ebeaec146102d9578063c8796572146102d4578063cd7033c4146102cf578063d98e0fe8146102ca578063dbcd50b4146102c5578063dcd549d4146102c0578063dd62ed3e146102bb578063e5adc635146102b6578063e7e5db4f146102b15763f58c251c146102ac575f80fd5b6125b3565b61104e565b612457565b6123dc565b6122db565b612265565b612241565b612207565b61211e565b611ff3565b611c90565b611c40565b611c1f565b611bde565b611bb5565b611b83565b611a37565b611874565b61183a565b6117d5565b6116f8565b611667565b611623565b6114e9565b611451565b6113cc565b611361565b61129e565b61126a565b6110e6565b6110c2565b61109e565b611014565b610f5b565b610f21565b610ed1565b610d87565b610d35565b610ce5565b610c03565b610bab565b610b6e565b610b3d565b610a41565b6109fa565b61099a565b61095e565b61091d565b6108f1565b6108cd565b61088b565b61085b565b610835565b6107e0565b610661565b6105fc565b61055e565b610506565b6103f5565b73ffffffffffffffffffffffffffffffffffffffff8116036103f157565b5f80fd5b346103f15760206003193601126103f157600435610412816103d3565b61041a612bf8565b7f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb33186104f95773ffffffffffffffffffffffffffffffffffffffff808216308114917f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb481614176104ec576370a082315f5230602052602060346024601c845afa601f3d1116156104df575f6044601082602094336014526fa9059cbb00000000000000000000000082525af13d1560015f51141716156104df576104dd612c16565b005b6390b8ec185f526004601cfd5b6311530cde5f526004601cfd5b6302171e6a5f526004601cfd5b346103f1575f6003193601126103f1576020610520612603565b604051908152f35b63ffffffff8116036103f157565b60031960409101126103f15760043561054e816103d3565b9060243561055b81610528565b90565b346103f157604061056e36610536565b6105c0610579612681565b925f845263ffffffff60208501935f8552610592612c1f565b165f526008602052845f209073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b54906cffffffffffffffffffffffffff82168093526fffffffffffffffffffffffffffffffff809260681c168152835192835251166020820152f35b346103f1575f6003193601126103f15760205f525f6020527f1b57696e7465726d7574652054726164696e672055534420436f696e00000000603f527f0000000000000000000000000000000000000000000000000000000000000000605f5260805ff35b346103f15761066f36610536565b90610678612c1f565b63ffffffff9182811691428310156107d3576106f76106f26107819261079696610786966106a4612c2b565b9391506106af61274b565b50160361079a576106cf909563ffffffff165f52600860205260405f2090565b9073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b6127ab565b9161072d61071860208501516fffffffffffffffffffffffffffffffff1690565b6fffffffffffffffffffffffffffffffff1690565b9261076861075461075461071860408601516fffffffffffffffffffffffffffffffff1690565b92516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff809116921690612ea7565b612811565b6040519081529081906020820190565b0390f35b506106cf6107be6107b98763ffffffff165f52600760205260405f2090565b612765565b9563ffffffff165f52600860205260405f2090565b632561b8805f526004601cfd5b346103f15760406003193601126103f157610823600435610800816103d3565b610808612bf8565b61081e610813612edb565b916024359033612f1f565b614d13565b5f63929eee145d602060405160018152f35b346103f1575f6003193601126103f15761084d61281e565b506101c0610859612880565bf35b346103f1575f6003193601126103f15761087361281e565b5061087c612c1f565b6101c0610887612c2b565b5050f35b346103f1575f6003193601126103f1576108a3612c1f565b60206fffffffffffffffffffffffffffffffff60406108c0612c2b565b5050015116604051908152f35b346103f1575f6003193601126103f157602061ffff60035460301c16604051908152f35b346103f1575f6003193601126103f157610909612c1f565b6020610520610916612c2b565b5050612f95565b346103f1575f6003193601126103f157610935612c1f565b6020610520610942612c2b565b50506cffffffffffffffffffffffffff60808201511690613e0d565b346103f1575f6003193601126103f157610976612bf8565b610991610981612edb565b61081e61098c612fe6565b61323f565b5f63929eee145d005b346103f15760206003193601126103f15773ffffffffffffffffffffffffffffffffffffffff6004356109cc816103d3565b6109d4612c1f565b165f52600460205260206cffffffffffffffffffffffffff60405f205416604051908152f35b346103f1575f6003193601126103f1576020610a27610a17612c2b565b5050610a21612603565b906133d4565b6fffffffffffffffffffffffffffffffff60405191168152f35b346103f15760606003193601126103f157600435610a5e816103d3565b602435610a6a816103d3565b604435610a75612bf8565b610a7d612edb565b9173ffffffffffffffffffffffffffffffffffffffff84165f526009602052610ac660405f203373ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8103610b11575b509061081e91610afe94613497565b5f63929eee145d60405160018152602090f35b9190818303928311610b3857610afe94610b2f61081e943383612f1f565b94509091610aef565b6127e4565b346103f1575f6003193601126103f15760206fffffffffffffffffffffffffffffffff5f5460081c16604051908152f35b346103f1575f6003193601126103f157602060405160ff7f0000000000000000000000000000000000000000000000000000000000000006168152f35b346103f1576020610bf4610bbe36610536565b9190610bc8612bf8565b61081e610bee610bd6612edb565b92610bdf612fe6565b9560445f523615519187613627565b9361323f565b5f63929eee145d604051908152f35b346103f15760206003193601126103f157600435610c1f612bf8565b610c27612edb565b8115610cd857610c598230337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4861385a565b815f52337fe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa660205fa2610c8a612fe6565b918251610ccb576109919261098c61081e9260245f5282361551917fec6f30250269069b62d7b969a6af731214d20af9d040000000000000000000006138d9565b6361d1bc8f5f526004601cfd5b637e0820885f526004601cfd5b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48168152f35b346103f1575f6003193601126103f15760207f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d55473ffffffffffffffffffffffffffffffffffffffff60405191168152f35b346103f15760206003193601126103f1576004357f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb33186104f957610dca612bf8565b610dd2612edb565b610dda612fe6565b8051610ec4577fec6f30250269069b62d7b969a6af731214d20af9d0400000000000000000000060018160571c16610e4b575b5082610e3e61081e9261098c610e25610e439761393f565b6fffffffffffffffffffffffffffffffff166020830152565b61395e565b6104dd612c16565b5f80917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36019082601c6040519363849da12985528960208601526101c088604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc575f610e0d565b3d5f803e3d5ffd5b6381b210785f526004601cfd5b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f00000000000000000000000035a5d1bd68f3139971027b92c1ee9384a0708554168152f35b346103f1575f6003193601126103f15760206040517f00000000000000000000000000000000000000000000000000000000000001f48152f35b346103f15760206003193601126103f157600435610f78816103d3565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000feb516d9d946dd487a9346f6fee11f40c6945ee4163303611007577f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d581815491555f526020527ff33499cccaa0611882086224cc48cd82ef54b66a4d2edf4ed67108dd516896d560405fa1005b634ee0b8f85f526004601cfd5b346103f1575f6003193601126103f15760206040517f000000000000000000000000000000000000000000000000000000000002a3008152f35b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000feb516d9d946dd487a9346f6fee11f40c6945ee4168152f35b346103f1575f6003193601126103f15760206105206110bb612c2b565b5050613987565b346103f1575f6003193601126103f1575f6040526101326041526020805260606020f35b346103f15760406003193601126103f157600435611102612bf8565b61110a612edb565b811515918261122f575b61111c612fe6565b926111278451151590565b61122a576111eb575b5061118261113c612603565b61117c61071861115f60608701516fffffffffffffffffffffffffffffffff1690565b60408701516fffffffffffffffffffffffffffffffff16906129a8565b90612811565b9061119f6111916107186139bc565b602435818082039110020190565b5f925b816111ac856129cc565b9410806111e2575b156111d557806111c76111d092876139de565b80820391110290565b6111a2565b610e438361081e8761323f565b508015156111b4565b61122490836111fd60445f5236155190565b917fec6f30250269069b62d7b969a6af731214d20af9d040000000000000000000006138d9565b5f611130565b610ccb565b61125b8130337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4861385a565b61126581336138af565b611114565b346103f1575f6003193601126103f157611282612c1f565b60206dffffffffffffffffffffffffffff6101806108c0612c2b565b346103f15760206003193601126103f1576004356112ba612bf8565b6112c2612edb565b6112ca612fe6565b916112ea6dffffffffffffffffffffffffffff61018085015116826151cf565b6113056cffffffffffffffffffffffffff82168092146151b6565b80156113545761079693611336926113309261132033613b42565b9260245f52361551933391613ba6565b91614d13565b5f63929eee145d60405163ffffffff90911681529081906020820190565b63d61c50f85f526004601cfd5b346103f15760206003193601126103f1576020610520600435611383816103d3565b61138b612c1f565b73ffffffffffffffffffffffffffffffffffffffff6113a8612c2b565b505091165f52600483526cffffffffffffffffffffffffff60405f20541690613e0d565b346103f1575f6003193601126103f1576113e4612bf8565b6113ec612edb565b6113f4612fe6565b906113fe33613b42565b916cffffffffffffffffffffffffff8351168015611354576107969382611330926114416dffffffffffffffffffffffffffff610180611336970151168261529f565b9160045f52361551933391613ba6565b346103f1575f6003193601126103f157611469612c1f565b6020610520611476612c2b565b5050613e2d565b9181601f840112156103f15782359167ffffffffffffffff83116103f1576020808501948460051b0101116103f157565b60209060206040818301928281528551809452019301915f5b8281106114d5575050505090565b8351855293810193928101926001016114c7565b346103f15760406003193601126103f15767ffffffffffffffff6004358181116103f15761151b90369060040161147d565b90916024359081116103f15761153590369060040161147d565b919092611540612bf8565b611548612edb565b938383036116165761156161155c846129f9565b612707565b938385527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe061158f856129f9565b0136602087013761159e612fe6565b935f5b8181106115cd57610796876115b98a61081e8a61323f565b6115c1612c16565b604051918291826114ae565b806116056115de6001938589612a3e565b356115e8816103d3565b6115f3838789612a3e565b356115fd81610528565b36918a613627565b61160f828a612a53565b52016115a1565b639d89020a5f526004601cfd5b346103f1575f6003193601126103f15761163b612c1f565b6020611645612c2b565b5050611658611652612603565b91613e2d565b90604051918082039111028152f35b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb168152f35b60209060206040818301928281528551809452019301915f5b8281106116de575050505090565b835163ffffffff16855293810193928101926001016116d0565b346103f1575f6003193601126103f157611710612c1f565b6005546fffffffffffffffffffffffffffffffff81169060801c818103908111610b385761174061155c826129f9565b918183527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe061176e836129f9565b013660208501375f5b82811061178c576040518061079686826116b7565b806117cf6117ba6117b06117a260019587612a67565b5f52600660205260405f2090565b5463ffffffff1690565b6117c48388612a53565b9063ffffffff169052565b01611777565b346103f1575f6003193601126103f15760205f525f6020527f07776d7455534443000000000000000000000000000000000000000000000000603f527f0000000000000000000000000000000000000000000000000000000000000000605f5260805ff35b346103f1575f6003193601126103f15760206040517f00000000000000000000000000000000000000000000000000000000000151808152f35b346103f15760406003193601126103f157600435611891816103d3565b6024359061189d612bf8565b6118a5612edb565b906118ae612fe6565b926118ce6dffffffffffffffffffffffffffff61018086015116826151cf565b916cffffffffffffffffffffffffff926118ec8482168092146151b6565b8015611a08578561098c8261199661081e976119316108239b611a029789337fec6f30250269069b62d7b969a6af731214d20af9d04000000000000000000000614f73565b61193a33613b42565b9080611949858285511661340b565b168252335f9081526004602052604090205b9151166cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b6119d56119c26119a587613b42565b926119bd84516cffffffffffffffffffffffffff1690565b613476565b6cffffffffffffffffffffffffff168252565b6119fd8573ffffffffffffffffffffffffffffffffffffffff165f52600460205260405f2090565b61342a565b33615011565b63ddee9b305f526004601cfd5b6004359061ffff821682036103f157565b6024359061ffff821682036103f157565b346103f15760206003193601126103f157611a50611a15565b611a58612bf8565b611a60612edb565b73ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dd7dd3b5076cf89440d05585ff56d246386207be163303611b765761ffff82166103e88111611b7157611ab3612fe6565b8051611b6c578061081e92610e4395610120830191611ade611ad7845161ffff1690565b61ffff1690565b8103611aee575b5050505061323f565b81611b6093611b427f4b34705283cdb9398d0e50b216b8fb424c6d4def5db9bfadc661ee3adc6076ee96611b4b947fec6f30250269069b62d7b969a6af731214d20af9d04000000000000000000000613efd565b9061ffff169052565b60405161ffff90911681529081906020820190565b0390a1805f8080611ae5565b613ef0565b613ee3565b6332cc72365f526004601cfd5b346103f1575f6003193601126103f157611b9b612c1f565b60206cffffffffffffffffffffffffff60806108c0612c2b565b346103f15760206003193601126103f1576020611bd0612edb565b610520611330600435613f7b565b346103f15760206003193601126103f157600435611bfa612edb565b90611c0481613f7b565b03611c12576104dd90614d13565b638a164f635f526004601cfd5b346103f1575f6003193601126103f157602060ff5f54166040519015158152f35b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000dd7dd3b5076cf89440d05585ff56d246386207be168152f35b346103f1575f6003193601126103f1577f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb8033186104f957611cd0612bf8565b611cd8612edb565b611ce0612fe6565b91611ceb8351151590565b611fee57611d9590611cfb612603565b90611d0585612f95565b9081831015611f9e575090611d1d81611d2d93612811565b90611d28828761412c565b612a67565b611d57847fec6f30250269069b62d7b969a6af731214d20af9d0400000000000000000000061420d565b5f610140850152600184526127106101608501525f61010085015261117c61071861115f60608701516fffffffffffffffffffffffffffffffff1690565b60c08301805163ffffffff908116918280611e27575b50505050611dba6107186139bc565b905f905b828210611e0f575050506cffffffffffffffffffffffffff611df060a08401516cffffffffffffffffffffffffff1690565b16611e0a57611e01610e439261323f565b61081e4261450a565b6144fd565b611e1f8161117c600193886139de565b910190611dbe565b611e426107b98563ffffffff165f52600760205260405f2090565b6020810180516cffffffffffffffffffffffffff1689611e84611e7285516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff80931610611f42575b5090611f0d92915f8652806fffffffffffffffffffffffffffffffff611f026040611eea611ed688516cffffffffffffffffffffffffff1690565b96516cffffffffffffffffffffffffff1690565b9601516fffffffffffffffffffffffffffffffff1690565b169316911684614477565b611f16816144b1565b4214611f23575b80611dab565b6117c4611f32611f3a94612b53565b9283166144d7565b5f8080611f1d565b886fffffffffffffffffffffffffffffffff611f698695949b8b611f7295611f0d99614264565b90501690612811565b97611f9483611f8f8a63ffffffff165f52600760205260405f2090565b612a74565b9091925089611e9b565b90808311611fae575b5050611d2d565b91610781611fbf611fe79483612811565b80937f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486140f2565b5f80611fa7565b6140e5565b346103f15760206003193601126103f1576004357f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb8033186104f957612037612bf8565b61203f612edb565b906395c098395f5260205260205f6024601c7f000000000000000000000000437e0551892c2c9b06d3ffd248fe60572e08cd1a5afa60203d141615610ebc575f516121195761208c612fe6565b8051612114576120a361209d612603565b82613eda565b831161210f578261210a826120df61081e94610e43977fec6f30250269069b62d7b969a6af731214d20af9d0400000000000000000000061455a565b61098c83337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486140f2565b6145d8565b61454d565b614540565b614533565b346103f1575f6003193601126103f157612136612bf8565b61213e612edb565b612146612fe6565b9060408201916fffffffffffffffffffffffffffffffff9081845116156121fa57612178612172612603565b826133d4565b8281169182156121ed57858461219a6121e89461081e97610e439a5116612b68565b16905261098c837f00000000000000000000000035a5d1bd68f3139971027b92c1ee9384a07085547f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486140f2565b614601565b63f784cfa45f526004601cfd5b6345c835cb5f526004601cfd5b346103f1575f6003193601126103f15760206040517fec6f30250269069b62d7b969a6af731214d20af9d040000000000000000000008152f35b346103f1575f6003193601126103f157602060035461ffff6040519160401c168152f35b346103f15760206003193601126103f157606061229c60043561228781610528565b61228f61274b565b612297612c1f565b612b8a565b6fffffffffffffffffffffffffffffffff60408051926cffffffffffffffffffffffffff80825116855260208201511660208501520151166040820152f35b346103f15760206003193601126103f1576004356122f8816103d3565b612300612bf8565b612308612edb565b6123118261462a565b156123cf5761231e612fe6565b917fec6f30250269069b62d7b969a6af731214d20af9d0400000000000000000000060018160581c1661235e575b508261098c61081e92610e4395614699565b5f80917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36019082601c60405193638b3ce9b385528760208601526101c08a604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc575f61234c565b63a97ab1675f526004601cfd5b346103f15760406003193601126103f157602061244e6004356123fe816103d3565b73ffffffffffffffffffffffffffffffffffffffff60243591612420836103d3565b165f526009835260405f209073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b54604051908152f35b346103f15760406003193601126103f157612470611a15565b612478611a26565b907f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb33186104f9576124a8612bf8565b6124b0612edb565b906124b9612fe6565b80516125ae576124ff816101608101956124d8611ad7885161ffff1690565b947fec6f30250269069b62d7b969a6af731214d20af9d04000000000000000000000614760565b61ffff959186811694612710978887116125a95783169788116125a4578711928315612588575b61254392612537919061ffff169052565b61ffff16610140840152565b612566575b9261256161081e9261255c610e439661323f565b614831565b61485a565b9261257084613e2d565b612578612603565b106125835792612548565b614824565b61259185613e2d565b612599612603565b101561252657614817565b61480a565b6147fd565b614753565b346103f1575f6003193601126103f157602060405173ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000437e0551892c2c9b06d3ffd248fe60572e08cd1a168152f35b6370a082315f523060205260205f6024601c7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb485afa601f3d111615612647575f5190565b634963f6d55f526004601cfd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b604051906040820182811067ffffffffffffffff8211176126a157604052565b612654565b604051906060820182811067ffffffffffffffff8211176126a157604052565b604051906101c0820182811067ffffffffffffffff8211176126a157604052565b604051906020820182811067ffffffffffffffff8211176126a157604052565b907fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f604051930116820182811067ffffffffffffffff8211176126a157604052565b6127536126a6565b905f82525f60208301525f6040830152565b906fffffffffffffffffffffffffffffffff60016127816126a6565b9380546cffffffffffffffffffffffffff90818116875260681c1660208601520154166040830152565b906fffffffffffffffffffffffffffffffff6127c5612681565b92546cffffffffffffffffffffffffff8116845260681c166020830152565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b91908203918211610b3857565b6128266126c6565b905f82525f60208301525f60408301525f60608301525f60808301525f60a08301525f60c08301525f60e08301525f6101008301525f6101208301525f6101408301525f6101608301525f6101808301525f6101a0830152565b6128886126c6565b906128ce5f5461289d60ff8216859015159052565b60081c6fffffffffffffffffffffffffffffffff9081166020850152600154908116604085015260801c6060840152565b6002546cffffffffffffffffffffffffff8082166080850152606882901c1660a084015263ffffffff60d082901c811660c08501526129859161291b9060ff9060f01c16151560e0860152565b60035463ffffffff8282161661010086015261ffff602082901c8116610120870152603082901c8116610140870152604082901c16610160860152605081901c6dffffffffffffffffffffffffffff1661018086015260c01c166101a084019063ffffffff169052565b565b9060016fffffffffffffffffffffffffffffffff80931601918211610b3857565b9190916fffffffffffffffffffffffffffffffff80809416911601918211610b3857565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8114610b385760010190565b67ffffffffffffffff81116126a15760051b60200190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b9190811015612a4e5760051b0190565b612a11565b8051821015612a4e5760209160051b010190565b91908201809211610b3857565b604060016fffffffffffffffffffffffffffffffff92612ad86cffffffffffffffffffffffffff86511682906cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b60208501517fffffffffffff00000000000000000000000000ffffffffffffffffffffffffff79ffffffffffffffffffffffffff0000000000000000000000000083549260681b16911617815501920151167fffffffffffffffffffffffffffffffff00000000000000000000000000000000825416179055565b90600163ffffffff80931601918211610b3857565b6fffffffffffffffffffffffffffffffff9182169082160391908211610b3857565b9190612b94612c2b565b915063ffffffff809316928315159116831416612bf357505f5260076020526fffffffffffffffffffffffffffffffff600160405f2080546cffffffffffffffffffffffffff90818116875260681c1660208601520154166040830152565b925050565b63929eee14805c612c09576001905d565b637fa8a9875f526004601cfd5b5f63929eee145d565b63929eee145c612c0957565b612c3361281e565b505f612c3d61274b565b612c45612880565b92612c5f8460c063ffffffff910151168042119015151690565b612d73575b6101a084015163ffffffff904290821603612d1f575b60c085015163ffffffff16908116612c8f5750565b92509050612cae6107b98363ffffffff165f52600760205260405f2090565b90612cc960208301516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff612cf1611e7285516cffffffffffffffffffffffffff1690565b911610612cfa57565b612d0c612d05612603565b85846149e2565b80612d145750565b612985908584614a6b565b612d6b427f000000000000000000000000000000000000000000000000000000000002a3007f00000000000000000000000000000000000000000000000000000000000001f488614883565b505050612c7a565b91505060c08201612d88815163ffffffff1690565b91612da7612d9e6101a086015163ffffffff1690565b63ffffffff1690565b63ffffffff8416908103612e04575b505f612dd36107b98563ffffffff165f52600760205260405f2090565b92612de6612ddf612603565b87866149e2565b80612df3575b5052612c64565b612dfe908786614a6b565b5f612dec565b612e50907f000000000000000000000000000000000000000000000000000000000002a3007f00000000000000000000000000000000000000000000000000000000000001f487614883565b5050612db6565b906b033b2e3c9fd0803ce800000091817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048111820215830215612e9a57020490565b63ad251c275f526004601cfd5b817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff048111820215830215612e9a57020490565b604051608081019080821067ffffffffffffffff8311176126a15761055b9160405260608152606060208201525f60408201525f60608201525f3560e01c90614c2f565b909173ffffffffffffffffffffffffffffffffffffffff82165f52600960205280612f6b8460405f209073ffffffffffffffffffffffffffffffffffffffff165f5260205260405f2090565b555f527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92560205fa3565b612fb26cffffffffffffffffffffffffff60808301511682613e0d565b906fffffffffffffffffffffffffffffffff90816060820151168301809311610b385760400151168101809111610b385790565b612fee61281e565b50612ff7612880565b906130118260c063ffffffff910151168042119015151690565b61317f575b6101a082015163ffffffff908116428190036130eb575b5060c083015163ffffffff169081166130435750565b61305e6107b98263ffffffff165f52600760205260405f2090565b60208101516cffffffffffffffffffffffffff166cffffffffffffffffffffffffff61309a611e7284516cffffffffffffffffffffffffff1690565b9116106130a6575b5050565b6130b86130b1612603565b85836149e2565b806130c257505050565b826130d5611f8f92612985958886614264565b505063ffffffff165f52600760205260405f2090565b6131799061313b427f000000000000000000000000000000000000000000000000000000000002a3007f00000000000000000000000000000000000000000000000000000000000001f488614883565b9261317161315e6101808a95949501516dffffffffffffffffffffffffffff1690565b6dffffffffffffffffffffffffffff1690565b904290614d81565b5f61302d565b613193612d9e60c084015163ffffffff1690565b6131a8612d9e6101a085015163ffffffff1690565b8082036131c0575b50506131bb82614dcb565b613016565b81613210613238937f000000000000000000000000000000000000000000000000000000000002a3007f00000000000000000000000000000000000000000000000000000000000001f488614883565b93909261323261315e6101808a01516dffffffffffffffffffffffffffff1690565b91614d81565b5f806131b0565b6129859061324c81613e2d565b613254612603565b1060e08201819052908051151561328161071860208401516fffffffffffffffffffffffffffffffff1690565b60081b175f556132a761071860408301516fffffffffffffffffffffffffffffffff1690565b6132c761071860608401516fffffffffffffffffffffffffffffffff1690565b60801b176001556132eb611e7260808301516cffffffffffffffffffffffffff1690565b613308611e7260a08401516cffffffffffffffffffffffffff1690565b61331c612d9e60c085015163ffffffff1690565b9060681b9060d01b8460f01b171717600255613343612d9e61010083015163ffffffff1690565b613356611ad761012084015161ffff1690565b613369611ad761014085015161ffff1690565b9061337d611ad761016086015161ffff1690565b916133b2612d9e6101a06133a661315e6101808a01516dffffffffffffffffffffffffffff1690565b97015163ffffffff1690565b9160201b9060301b179160401b908460501b9060c01b17171717600355614f47565b906fffffffffffffffffffffffffffffffff91826060820151168203918211610b3857604083910151169081808203911002011690565b6cffffffffffffffffffffffffff9182169082160391908211610b3857565b6cffffffffffffffffffffffffff6129859251166cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b9190916cffffffffffffffffffffffffff80809416911601918211610b3857565b91906134a1612fe6565b926134c16dffffffffffffffffffffffffffff61018086015116846151cf565b6cffffffffffffffffffffffffff6134dd8183168093146151b6565b8115611a08577fec6f30250269069b62d7b969a6af731214d20af9d04000000000000000000000600181605c1c1661359f575b509461098c61359a926135636129859861352987613b42565b9080613538858285511661340b565b16825261195b8873ffffffffffffffffffffffffffffffffffffffff165f52600460205260405f2090565b6135726119c26119a588613b42565b6119fd8673ffffffffffffffffffffffffffffffffffffffff165f52600460205260405f2090565b615011565b5f80917fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9c9893983601906040519163a018f90e83523360208401528760408401528860608401528660808401526101c08660a085015e610260808401528061028084015260646102a084013782601c610220360193019160601c5af115610ebc57945f613510565b909291926136466107b98563ffffffff165f52600760205260405f2090565b9361365b612d9e60c085015163ffffffff1690565b9063ffffffff811691821461385557613686836106cf8363ffffffff165f52600860205260405f2090565b946136d96137046136aa60408a01516fffffffffffffffffffffffffffffffff1690565b986136f96107188a54809c6cffffffffffffffffffffffffff968795516cffffffffffffffffffffffffff1690565b6fffffffffffffffffffffffffffffffff97889687921693169116612ea7565b9960681c1689612b68565b9081169788156138505760608761379b6137bc9361055b9b61374d6137d2988f9d8e8e7fec6f30250269069b62d7b969a6af731214d20af9d04000000000000000000000615049565b907fffffff00000000000000000000000000000000ffffffffffffffffffffffffff7cffffffffffffffffffffffffffffffff0000000000000000000000000083549260681b169116179055565b01916137b783516fffffffffffffffffffffffffffffffff1690565b612b68565b6fffffffffffffffffffffffffffffffff169052565b836137dc8461462a565b156138245761381f916137ee856150b9565b61381983827f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486140f2565b85615151565b61518b565b61381f9150837f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486140f2565b61503c565b6107d3565b601c5f60649281946020966040519860605260405260601b602c526f23b872dd000000000000000000000000600c525af13d1560015f51141716156138a2575f606052604052565b637939f4245f526004601cfd5b905f527fe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa660205fa2565b600181605a1c166138eb575b50505050565b5f601c6101c08296958684973603928392604051986383d9e1eb8a5260208a0152604089015e61020080880152816102208801526102408701376102240193019160601c5af115610ebc575f8080806138e5565b906129856fffffffffffffffffffffffffffffffff83168093146151b6565b5f527ff2672935fc79f5237559e2e2999dbe743bf65430894ac2b37666890e7c69e1af60205fa1565b6111c76fffffffffffffffffffffffffffffffff602083015116916cffffffffffffffffffffffffff60808201511690613e0d565b61055b6005546fffffffffffffffffffffffffffffffff81169060801c612b68565b9190600554906fffffffffffffffffffffffffffffffff918281169060801c8114613afc575f52600660205281613a3d63ffffffff60405f2054169283613a366107b98263ffffffff165f52600760205260405f2090565b9788614264565b90501693613a5d81611f8f8463ffffffff165f52600760205260405f2090565b6cffffffffffffffffffffffffff6020818351169201511614613a7e575050565b600554918083169260801c8314613afc57613acd83612985945f52600660205260405f207fffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000008154169055612987565b167fffffffffffffffffffffffffffffffff0000000000000000000000000000000060055416176005556144b1565b60046040517f87274801000000000000000000000000000000000000000000000000000000008152fd5b906129856cffffffffffffffffffffffffff83168093146151b6565b905f613b4c6126e7565b5273ffffffffffffffffffffffffffffffffffffffff82165f526004602052613b9360405f206cffffffffffffffffffffffffff613b886126e7565b91541681529261462a565b613b9957565b636bc671fd5f526004601cfd5b9392959491909560c0850190613bc0825163ffffffff1690565b9763ffffffff92838a1615613d8e575b50938893613d4b93613d4484613c4961098c99613c266cffffffffffffffffffffffffff6129859e9d9916978d898d8a7fec6f30250269069b62d7b969a6af731214d20af9d040000000000000000000006151f5565b6135726119c284613c4484516cffffffffffffffffffffffffff1690565b61340b565b613c54863086615011565b613ce1613c8e856106cf613c796107b98d63ffffffff165f52600760205260405f2090565b9b63ffffffff165f52600860205260405f2090565b613ca9836119bd83546cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff167fffffffffffffffffffffffffffffffffffffff00000000000000000000000000825416179055565b613d12613cff826119bd8b516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff168952565b613d3160a08b01916119bd83516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff169052565b8a1661526f565b613d5d613d56612603565b84836149e2565b80613d7c575b50611f8f8663ffffffff165f52600760205260405f2090565b613d8890878584614264565b50613d63565b93613dfc9950613d4b93613d44899894613c4961098c9995613ded612d9e613de76129859f613dbd9051151590565b7f000000000000000000000000000000000000000000000000000000000001518090815f03020190565b42612a67565b9e8f809b6117c48883166144d7565b959950509498995050935093613bd0565b906dffffffffffffffffffffffffffff61018061055b930151169061529f565b6cffffffffffffffffffffffffff8060a08301511690608083015116818103908111610b3857613e679061ffff61016085015116906152ee565b908101809111610b3857613e91906dffffffffffffffffffffffffffff610180840151169061529f565b6fffffffffffffffffffffffffffffffff6040830151168101809111610b3857613ed4610718606061055b9401516fffffffffffffffffffffffffffffffff1690565b90612a67565b6111c790613e2d565b63499fddb15f526004601cfd5b6337f1a75f5f526004601cfd5b919060018360551c16613f0f57505050565b5f9283601c81946101c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc360191604051966303473d8d88526020880152604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc57565b613f83612bf8565b613f8b612fe6565b90613f968251151590565b6140e057613fb390613fa783613987565b90818082039110020190565b90613fe4613fdf613fd961315e6101808501516dffffffffffffffffffffffffffff1690565b846151cf565b613b26565b906cffffffffffffffffffffffffff821680156140db576140d2926140b361098c9261409b61401233613b42565b61403e8784337fec6f30250269069b62d7b969a6af731214d20af9d04000000000000000000000615343565b61406a8930337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4861385a565b6140886119c2866119bd84516cffffffffffffffffffffffffff1690565b335f90815260046020526040902061342a565b6140ac873361359a5f805236155190565b86336153cf565b613d3160808401916119bd83516cffffffffffffffffffffffffff1690565b90612985612c16565b615336565b615329565b63449e5f505f526004601cfd5b60105f60449260209582956014526034526fa9059cbb00000000000000000000000082525af13d1560015f51141716156104df575f603452565b8115610cd8578051610ccb576141648230337f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4861385a565b815f52337fe8b606ac1e5df7657db58d297ca8f41c090fc94c5fd2d6958f043e41736e9fa660205fa27fec6f30250269069b62d7b969a6af731214d20af9d0400000000000000000000091600183605a1c166141bf57505050565b5f9283601c81946101c0600319360191604051966383d9e1eb88526020880152604087015e610200808601526102209080828701526004610240870137360193019160601c5af115610ebc57565b60018160591c1661421c575050565b5f91829182601c60031936016101c060405195639ecc64e68752602087015e6101e0808601526102009080828701526004610220870137360193019160601c5af115610ebc57565b9293916142b69161428285516cffffffffffffffffffffffffff1690565b9460208101956cffffffffffffffffffffffffff9485916142b089516cffffffffffffffffffffffffff1690565b9061340b565b16801561446a5761018083019788516142dc906dffffffffffffffffffffffffffff1690565b6dffffffffffffffffffffffffffff166142f5916151cf565b81811090829003020161430790613b26565b965193871693614327906dffffffffffffffffffffffffffff1685612e57565b6143309061393f565b9587815161434a906cffffffffffffffffffffffffff1690565b9061435491613476565b6cffffffffffffffffffffffffff16905260400180516143879087906fffffffffffffffffffffffffffffffff166129a8565b6fffffffffffffffffffffffffffffffff16905260a0810180516143bb9088906cffffffffffffffffffffffffff1661340b565b6cffffffffffffffffffffffffff1690526060810180516143ef9087906fffffffffffffffffffffffffffffffff166129a8565b6fffffffffffffffffffffffffffffffff16905260800180516144229087906cffffffffffffffffffffffffff1661340b565b6cffffffffffffffffffffffffff1690525f8052361551906fffffffffffffffffffffffffffffffff85169182309161445a92615011565b63ffffffff1691612985926153fd565b505f965086955050505050565b91929092604051935f526020526040527f9262dc39b47cad3a0512e4c08dda248cb345e7163058f300bc63f56bda288b6e60605fa2604052565b7fcbdf25bf6e096dd9030d89bb2ba2e3e7adb82d25a233c3ca3d92e9f098b74e555f80a2565b7f5c9a946d3041134198ebefcd814de7748def6576efd3d1b48f48193e183e89ef5f80a2565b634d7909975f526004601cfd5b5f527f9dc30b8eda31a6a144e092e5de600955523a6a925cc15cc1d1b9b4872cfa615560205fa1565b634a1c13a95f526004601cfd5b63d0242b285f526004601cfd5b63119fe6e35f526004601cfd5b9190600183605b1c1661456c57505050565b5f9283601c81946101c07fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc3601916040519663b1cfda0d88526020880152604087015e610200908180870152806102208701526024610240870137360193019160601c5af115610ebc57565b5f527fb848ae6b1253b6cb77e81464128ce8bd94d3d524fea54e801e0da869784dca3360205fa1565b5f527f860c0aa5520013080c2f65981705fcdea474d9f7c3daf954656ed5e65d692d1f60205fa1565b90604051916306e744445f527f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb60205260405260205f6044601c7f000000000000000000000000437e0551892c2c9b06d3ffd248fe60572e08cd1a5afa60203d141615610ebc575f5191604052565b9073ffffffffffffffffffffffffffffffffffffffff81165f52600460205260405f20916cffffffffffffffffffffffffff6146d36126e7565b93541692838152836146e55750505050565b81614715918561470b6dffffffffffffffffffffffffffff61018088970151168261529f565b9485923694613ba6565b92604051935f526020526040527fe12b220b92469ae28fb0d79de531f94161431be9f073b96b8aad3effb88be6fa60605fa26040525f8080806138e5565b63b9de88a25f526004601cfd5b91909260018360561c165f146147f65791604093916101c05f947fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbc36019287519563cc4526428752602087015287860152606085015e6102208084015280610240840152604461026084013782601c610200360193019160601c5af11560403d1017610ebc5761ffff90815f5116916020511690565b5090509091565b63cf1f916f5f526004601cfd5b638ec830735f526004601cfd5b630a68e5bf5f526004601cfd5b63253ecbb95f526004601cfd5b5f527fff7b6c8be373823323d3c5d99f5d027dd409dce5db54eae511bbdd5546b7503760205fa1565b5f527f72877a153052500f5edbb2f9da96a0f45d671d4b4555fdf8628a709dc4eab43a60205fa1565b92939190915f925f9261ffff968761014088015116916101a088019363ffffffff93848651168403848111610b38576148bb91615545565b809a6101208b0151168061495d575b50508061493b575b5050614930610180612985959697980161491c6149178b613ed46149118d61490b61315e88516dffffffffffffffffffffffffffff1690565b93612a67565b8261529f565b615464565b6dffffffffffffffffffffffffffff169052565b1663ffffffff169052565b612985959697506149546149309261018092858c61542b565b979695506148d2565b6149a69298509061496d916152ee565b6149a06cffffffffffffffffffffffffff60808c015116916dffffffffffffffffffffffffffff6101808d01511661529f565b9061529f565b604089016fffffffffffffffffffffffffffffffff908181511691838301809311610b38576149d99083168093146151b6565b5295895f6148ca565b614a106cffffffffffffffffffffffffff916142b08360a0860151169184602081835116920151169061340b565b16906fffffffffffffffffffffffffffffffff90614a4b82606083015116936dffffffffffffffffffffffffffff610180840151169061529f565b8301809311610b385760400151168101809111610b385780820391110290565b80516cffffffffffffffffffffffffff1690614aad60208201926cffffffffffffffffffffffffff9182916142b086516cffffffffffffffffffffffffff1690565b168015614c27576101808501958651614ad3906dffffffffffffffffffffffffffff1690565b6dffffffffffffffffffffffffffff16614aec916151cf565b818110908290030201614afe90613b26565b9451614b1e916dffffffffffffffffffffffffffff909116908616612e57565b614b279061393f565b91848151614b41906cffffffffffffffffffffffffff1690565b90614b4b91613476565b6cffffffffffffffffffffffffff1690526040018051614b7e9083906fffffffffffffffffffffffffffffffff166129a8565b6fffffffffffffffffffffffffffffffff16905260a082018051614bb29085906cffffffffffffffffffffffffff1661340b565b6cffffffffffffffffffffffffff16905260608201908151614be3906fffffffffffffffffffffffffffffffff1690565b90614bed916129a8565b6fffffffffffffffffffffffffffffffff169052608001908151614c1d906cffffffffffffffffffffffffff1690565b90613d319161340b565b505050505050565b90819073ffffffffffffffffffffffffffffffffffffffff7f1777adabd324f814e2b0e28f6edf876dce01d7d66358c9acfe87b1b5f38338d55416918260608501528215614d0c575060405190638925ca5a825260405f60209483868601523383860152606080860152366080860152368260a08701373660c4019082601c8701915af1835f51141615610ebc5760808361055b945160051b809460e06003830282010160405282820183823e80885201925f038184015281606084015285019260a08301845260a0019101525a60408401528251905190615481565b9392505050565b606081019073ffffffffffffffffffffffffffffffffffffffff825116156130a2575f8082518051908160061b95614d5060c08884010183615481565b519160051b019360405a91015103604085015283519463f0bd9468855260c4019082601c8601915af115610ebc5752565b927f18247a393d0531b65fbd94f5e78bc5639801a4efda62ae7b43533c4442116c3a959260c09592604051958652602086015260408501526060840152608083015260a0820152a1565b61298590611f8f60c082015f614de5825163ffffffff1690565b91614e016107b98463ffffffff165f52600760205260405f2090565b946020860190614e1e82516cffffffffffffffffffffffffff1690565b90614e39611e7289516cffffffffffffffffffffffffff1690565b6cffffffffffffffffffffffffff80931610614f17575b50614ec6614e6b88516cffffffffffffffffffffffffff1690565b92614eb3614e8682516cffffffffffffffffffffffffff1690565b60408b015163ffffffff8a16966fffffffffffffffffffffffffffffffff90911691861690861687614477565b516cffffffffffffffffffffffffff1690565b90614ee1611e7289516cffffffffffffffffffffffffff1690565b9116108314614f095750614ef4836154b9565b5263ffffffff165f52600760205260405f2090565b614f12906144b1565b614ef4565b614f29614f22612603565b828a6149e2565b8681614f37575b5050614e50565b614f41928a614264565b86614f30565b5f526020527f9385f9ff65bcd2fb81cece54b27d4ec7376795fc4dcff686e370e347b0ed86c060405fa1565b9091939293600182605c1c16614f8b575b5050505050565b6101c05f959486957fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffbc3601936040519663a018f90e885233602089015260408801526060870152608086015260a085015e610260808401528061028084015260446102a084013782601c610240360193019160601c5af115610ebc575f80808080614f84565b90915f527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef60205fa3565b63186334fe5f526004601cfd5b9091600182605d1c1661505d575050505050565b601c5f9594869592836101c08895360393849360405199632970403d8b5260208b015260408a0152606089015e61022080880152816102408801526102608701376102440193019160601c5af115610ebc575f80808080614f84565b906040519163a1054f6b5f527f0000000000000000000000005b15f94efc3a6e2c82d7db8efd8d5ba55da11feb6020526040527f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4860605260205f6064601c827f000000000000000000000000437e0551892c2c9b06d3ffd248fe60572e08cd1a5af160203d141615610ebc575f51916040525f606052565b91929092604051935f526020526040527f0d0843a0fcb8b83f625aafb6e42f234ac48c6728b207d52d97cfa8fbd34d498f60605fa2604052565b90915f527fd6cddb3d69146e96ebc2c87b1b3dd0b20ee2d3b0eadf134e011afb434a3e56e660205fa3565b156151bd57565b634e487b715f5260116020526024601cfd5b8160011c906b033b2e3c9fd0803ce8000000908183190481118415176151bd5702010490565b919394909294600183605e1c1661520e57505050505050565b5f958695836101c0601c94899636039485946040519a633521cccc8c5260208c015260408b015260608a0152608089015e61024080880152816102608801526102808701376102640193019160601c5af115610ebc575f8080808080614c27565b919290925f526020527fecc966b282a372469fa4d3e497c2ac17983c3eaed03f3f17c9acf4b15591663e60405fa3565b817ffffffffffffffffffffffffffffffffffffffffffe6268e1b017bfe18bffffff04811115821517156151bd576b033b2e3c9fd0803ce800000091026b019d971e4fe8401e74000000010490565b817fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec7704811115821517156151bd576127109102611388010490565b6322d7c0435f526004601cfd5b63e4aa50555f526004601cfd5b929192600181605f1c166153575750505050565b5f601c81956101c083967fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdc36019260405197635aeb713f895260208901526040880152606087015e610220908180870152806102408701526024610260870137360193019160601c5af115610ebc575f8080806138e5565b91905f526020527f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a1560405fa2565b91905f526020527f5272034725119f19d7236de4129fdb5093f0dcb80282ca5edbd587df91d2bd8960405fa2565b909392935f9463ffffffff6101a0840151168203918211610b385761544f92615577565b9081615459575050565b61055b929350615545565b906129856dffffffffffffffffffffffffffff83168093146151b6565b9190825190818152602080809501918181019360051b0101915b8281106154a9575050509050565b815154815290840190840161549b565b6155039060055460801c90815f52600660205263ffffffff60405f2091167fffffffffffffffffffffffffffffffffffffffffffffffffffffffff00000000825416179055612987565b6fffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffff000000000000000000000000000000006005549260801b16911617600555565b69152d02c7e14af68000008082029180828404036151bd57830202918183041490151715610b38576301e13380900490565b90610100820163ffffffff9060e0828251169401516155b7576155a5858503868611029283168093146151b6565b52808203911102818082039110020190565b848493940191828411610b38576155d29083168093146151b6565b528082039111028082039111029056fea164736f6c6343000819000a","source_code":"// SPDX-License-Identifier: Apache-2.0 WITH LicenseRef-Commons-Clause-1.0\npragma solidity >=0.8.20;\n\nimport './WildcatMarketBase.sol';\nimport './WildcatMarketConfig.sol';\nimport './WildcatMarketToken.sol';\nimport './WildcatMarketWithdrawals.sol';\nimport '../WildcatSanctionsSentinel.sol';\n\ncontract WildcatMarket is\n  WildcatMarketBase,\n  WildcatMarketConfig,\n  WildcatMarketToken,\n  WildcatMarketWithdrawals\n{\n  using MathUtils for uint256;\n  using SafeCastLib for uint256;\n  using LibERC20 for address;\n  using BoolUtils for bool;\n\n  /**\n   * @dev Apply pending interest, delinquency fees and protocol fees\n   *      to the state and process the pending withdrawal batch if\n   *      one exists and has expired, then update the market's\n   *      delinquency status.\n   */\n  function updateState() external nonReentrant sphereXGuardExternal {\n    MarketState memory state = _getUpdatedState();\n    _writeState(state);\n  }\n\n  /**\n   * @dev Token rescue function for recovering tokens sent to the market\n   *      contract by mistake or otherwise outside of the normal course of\n   *      operation.\n   */\n  function rescueTokens(address token) external nonReentrant onlyBorrower {\n    if ((token == asset).or(token == address(this))) {\n      revert_BadRescueAsset();\n    }\n    token.safeTransferAll(msg.sender);\n  }\n\n  /**\n   * @dev Deposit up to `amount` underlying assets and mint market tokens\n   *      for `msg.sender`.\n   *\n   *      The actual deposit amount is limited by the market's maximum deposit\n   *      amount, which is the configured `maxTotalSupply` minus the current\n   *      total supply.\n   *\n   *      Reverts if the market is closed or if the scaled token amount\n   *      that would be minted for the deposit is zero.\n   */\n  function _depositUpTo(\n    uint256 amount\n  ) internal virtual nonReentrant returns (uint256 /* actualAmount */) {\n    // Get current state\n    MarketState memory state = _getUpdatedState();\n\n    if (state.isClosed) revert_DepositToClosedMarket();\n\n    // Reduce amount if it would exceed totalSupply\n    amount = MathUtils.min(amount, state.maximumDeposit());\n\n    // Scale the mint amount\n    uint104 scaledAmount = state.scaleAmount(amount).toUint104();\n    if (scaledAmount == 0) revert_NullMintAmount();\n\n    // Cache account data and revert if not authorized to deposit.\n    Account memory account = _getAccount(msg.sender);\n\n    hooks.onDeposit(msg.sender, scaledAmount, state);\n\n    // Transfer deposit from caller\n    asset.safeTransferFrom(msg.sender, address(this), amount);\n\n    account.scaledBalance += scaledAmount;\n    _accounts[msg.sender] = account;\n\n    emit_Transfer(_runtimeConstant(address(0)), msg.sender, amount);\n    emit_Deposit(msg.sender, amount, scaledAmount);\n\n    // Increase supply\n    state.scaledTotalSupply += scaledAmount;\n\n    // Update stored state\n    _writeState(state);\n\n    return amount;\n  }\n\n  /**\n   * @dev Deposit up to `amount` underlying assets and mint market tokens\n   *      for `msg.sender`.\n   *\n   *      The actual deposit amount is limited by the market's maximum deposit\n   *      amount, which is the configured `maxTotalSupply` minus the current\n   *      total supply.\n   *\n   *      Reverts if the market is closed or if the scaled token amount\n   *      that would be minted for the deposit is zero.\n   */\n  function depositUpTo(\n    uint256 amount\n  ) external virtual sphereXGuardExternal returns (uint256 /* actualAmount */) {\n    return _depositUpTo(amount);\n  }\n\n  /**\n   * @dev Deposit exactly `amount` underlying assets and mint market tokens\n   *      for `msg.sender`.\n   *\n   *     Reverts if the deposit amount would cause the market to exceed the\n   *     configured `maxTotalSupply`.\n   */\n  function deposit(uint256 amount) external virtual sphereXGuardExternal {\n    uint256 actualAmount = _depositUpTo(amount);\n    if (amount != actualAmount) revert_MaxSupplyExceeded();\n  }\n\n  /**\n   * @dev Withdraw available protocol fees to the fee recipient.\n   */\n  function collectFees() external nonReentrant sphereXGuardExternal {\n    MarketState memory state = _getUpdatedState();\n    if (state.accruedProtocolFees == 0) revert_NullFeeAmount();\n\n    uint128 withdrawableFees = state.withdrawableProtocolFees(totalAssets());\n    if (withdrawableFees == 0) revert_InsufficientReservesForFeeWithdrawal();\n\n    state.accruedProtocolFees -= withdrawableFees;\n    asset.safeTransfer(feeRecipient, withdrawableFees);\n    _writeState(state);\n    emit_FeesCollected(withdrawableFees);\n  }\n\n  /**\n   * @dev Withdraw funds from the market to the borrower.\n   *\n   *      Can only withdraw up to the assets that are not required\n   *      to meet the borrower's collateral obligations.\n   *\n   *      Reverts if the market is closed.\n   */\n  function borrow(uint256 amount) external onlyBorrower nonReentrant sphereXGuardExternal {\n    // Check if the borrower is flagged as a sanctioned entity on Chainalysis.\n    // Uses `isFlaggedByChainalysis` instead of `isSanctioned` to prevent the borrower\n    // overriding their sanction status.\n    if (_isFlaggedByChainalysis(borrower)) {\n      revert_BorrowWhileSanctioned();\n    }\n\n    MarketState memory state = _getUpdatedState();\n    if (state.isClosed) revert_BorrowFromClosedMarket();\n\n    uint256 borrowable = state.borrowableAssets(totalAssets());\n    if (amount > borrowable) revert_BorrowAmountTooHigh();\n\n    // Execute borrow hook if enabled\n    hooks.onBorrow(amount, state);\n\n    asset.safeTransfer(msg.sender, amount);\n    _writeState(state);\n    emit_Borrow(amount);\n  }\n\n  function _repay(MarketState memory state, uint256 amount, uint256 baseCalldataSize) internal {\n    if (amount == 0) revert_NullRepayAmount();\n    if (state.isClosed) revert_RepayToClosedMarket();\n\n    asset.safeTransferFrom(msg.sender, address(this), amount);\n    emit_DebtRepaid(msg.sender, amount);\n\n    // Execute repay hook if enabled\n    hooks.onRepay(amount, state, baseCalldataSize);\n  }\n\n  /**\n   * @dev Transfers funds from the caller to the market.\n   *\n   *      Any payments made through this function are considered\n   *      repayments from the borrower. Do *not* use this function\n   *      if you are a lender or an unrelated third party.\n   *\n   *      Reverts if the market is closed or `amount` is 0.\n   */\n  function repay(uint256 amount) external nonReentrant sphereXGuardExternal {\n    if (amount == 0) revert_NullRepayAmount();\n\n    asset.safeTransferFrom(msg.sender, address(this), amount);\n    emit_DebtRepaid(msg.sender, amount);\n\n    MarketState memory state = _getUpdatedState();\n    if (state.isClosed) revert_RepayToClosedMarket();\n\n    // Execute repay hook if enabled\n    hooks.onRepay(amount, state, _runtimeConstant(0x24));\n\n    _writeState(state);\n  }\n\n  /**\n   * @dev Sets the market APR to 0% and marks market as closed.\n   *\n   *      Can not be called if there are any unpaid withdrawal batches.\n   *\n   *      Transfers remaining debts from borrower if market is not fully\n   *      collateralized; otherwise, transfers any assets in excess of\n   *      debts to the borrower.\n   */\n  function closeMarket() external onlyBorrower nonReentrant sphereXGuardExternal {\n    MarketState memory state = _getUpdatedState();\n\n    if (state.isClosed) revert_MarketAlreadyClosed();\n\n    uint256 currentlyHeld = totalAssets();\n    uint256 totalDebts = state.totalDebts();\n    if (currentlyHeld < totalDebts) {\n      // Transfer remaining debts from borrower\n      uint256 remainingDebt = totalDebts - currentlyHeld;\n      _repay(state, remainingDebt, 0x04);\n      currentlyHeld += remainingDebt;\n    } else if (currentlyHeld > totalDebts) {\n      uint256 excessDebt = currentlyHeld - totalDebts;\n      // Transfer excess assets to borrower\n      asset.safeTransfer(borrower, excessDebt);\n      currentlyHeld -= excessDebt;\n    }\n    hooks.onCloseMarket(state);\n    state.annualInterestBips = 0;\n    state.isClosed = true;\n    state.reserveRatioBips = 10000;\n    // Ensures that delinquency fee doesn't increase scale factor further\n    // as doing so would mean last lender in market couldn't fully redeem\n    state.timeDelinquent = 0;\n\n    // Still track available liquidity in case of a rounding error\n    uint256 availableLiquidity = currentlyHeld -\n      (state.normalizedUnclaimedWithdrawals + state.accruedProtocolFees);\n\n    // If there is a pending withdrawal batch which is not fully paid off, set aside\n    // up to the available liquidity for that batch.\n    if (state.pendingWithdrawalExpiry != 0) {\n      uint32 expiry = state.pendingWithdrawalExpiry;\n      WithdrawalBatch memory batch = _withdrawalData.batches[expiry];\n      if (batch.scaledAmountBurned < batch.scaledTotalAmount) {\n        (, uint128 normalizedAmountPaid) = _applyWithdrawalBatchPayment(\n          batch,\n          state,\n          expiry,\n          availableLiquidity\n        );\n        availableLiquidity -= normalizedAmountPaid;\n        _withdrawalData.batches[expiry] = batch;\n      }\n\n      // Remove the pending batch to ensure new withdrawals are not\n      // added to it after the market is closed.\n      state.pendingWithdrawalExpiry = 0;\n      emit_WithdrawalBatchExpired(\n        expiry,\n        batch.scaledTotalAmount,\n        batch.scaledAmountBurned,\n        batch.normalizedAmountPaid\n      );\n      emit_WithdrawalBatchClosed(expiry);\n\n      // If the batch expiry is at the time of the market's closure, create\n      // a new empty batch that expires in one second to ensure new batches\n      // aren't created after the market is closed with the same expiry.\n      if (expiry == block.timestamp) {\n        uint32 newExpiry = expiry + 1;\n        emit_WithdrawalBatchCreated(newExpiry);\n        state.pendingWithdrawalExpiry = newExpiry;\n      }\n    }\n\n    uint256 numBatches = _withdrawalData.unpaidBatches.length();\n    for (uint256 i; i < numBatches; i++) {\n      // Process the next unpaid batch using available liquidity\n      uint256 normalizedAmountPaid = _processUnpaidWithdrawalBatch(state, availableLiquidity);\n      // Reduce liquidity available to next batch\n      availableLiquidity -= normalizedAmountPaid;\n    }\n\n    if (state.scaledPendingWithdrawals != 0) {\n      revert_CloseMarketWithUnpaidWithdrawals();\n    }\n\n    _writeState(state);\n    emit_MarketClosed(block.timestamp);\n  }\n\n  /**\n   * @dev Queues a full withdrawal of a sanctioned account's assets.\n   */\n  function _blockAccount(MarketState memory state, address accountAddress) internal override {\n    Account memory account = _accounts[accountAddress];\n    if (account.scaledBalance > 0) {\n      uint104 scaledAmount = account.scaledBalance;\n\n      uint256 normalizedAmount = state.normalizeAmount(scaledAmount);\n\n      uint32 expiry = _queueWithdrawal(\n        state,\n        account,\n        accountAddress,\n        scaledAmount,\n        normalizedAmount,\n        msg.data.length\n      );\n\n      emit_SanctionedAccountAssetsQueuedForWithdrawal(\n        accountAddress,\n        expiry,\n        scaledAmount,\n        normalizedAmount\n      );\n    }\n  }\n}\n","creation_status":"success","file_path":"src/market/WildcatMarket.sol"}