{"compiler":{"version":"0.8.35+commit.47b9dedd"},"language":"Solidity","output":{"abi":[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AccessControlBadConfirmation","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"bytes32","name":"neededRole","type":"bytes32"}],"name":"AccessControlUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedCall","type":"error"},{"inputs":[],"name":"FailedDeployment","type":"error"},{"inputs":[{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"InsufficientBalance","type":"error"},{"inputs":[],"name":"InvalidInitialization","type":"error"},{"inputs":[],"name":"LoanManager_AlreadyMarginCalled","type":"error"},{"inputs":[],"name":"LoanManager_AlreadyTriggered","type":"error"},{"inputs":[],"name":"LoanManager_CollateralManagerAlreadySet","type":"error"},{"inputs":[],"name":"LoanManager_GracePeriodActive","type":"error"},{"inputs":[],"name":"LoanManager_HubAlreadySet","type":"error"},{"inputs":[],"name":"LoanManager_InvalidRiskParam","type":"error"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"LoanManager_LoanClosed","type":"error"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"LoanManager_LoanExists","type":"error"},{"inputs":[],"name":"LoanManager_MaturityDefault","type":"error"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"LoanManager_NoSuchLoan","type":"error"},{"inputs":[],"name":"LoanManager_NotAContract","type":"error"},{"inputs":[],"name":"LoanManager_NotCollateralManager","type":"error"},{"inputs":[],"name":"LoanManager_NotHub","type":"error"},{"inputs":[],"name":"LoanManager_NotInMarginCallZone","type":"error"},{"inputs":[],"name":"LoanManager_NotLiquidatable","type":"error"},{"inputs":[],"name":"LoanManager_NotMarginCalled","type":"error"},{"inputs":[],"name":"LoanManager_NotTriggered","type":"error"},{"inputs":[],"name":"LoanManager_NothingToLiquidate","type":"error"},{"inputs":[{"internalType":"uint256","name":"seized","type":"uint256"},{"internalType":"uint256","name":"minSeized","type":"uint256"}],"name":"LoanManager_SeizeBelowMinimum","type":"error"},{"inputs":[{"internalType":"uint256","name":"required","type":"uint256"},{"internalType":"uint256","name":"available","type":"uint256"}],"name":"LoanManager_SeizeExceedsCollateral","type":"error"},{"inputs":[{"internalType":"uint256","name":"required","type":"uint256"},{"internalType":"uint256","name":"maxRepay","type":"uint256"}],"name":"LoanManager_SlippageExceeded","type":"error"},{"inputs":[],"name":"LoanManager_StillInMarginCallZone","type":"error"},{"inputs":[],"name":"LoanManager_StillLiquidatable","type":"error"},{"inputs":[],"name":"LoanManager_WrongChain","type":"error"},{"inputs":[],"name":"LoanManager_ZeroAddress","type":"error"},{"inputs":[],"name":"LoanManager_ZeroAmount","type":"error"},{"inputs":[],"name":"NotInitializing","type":"error"},{"inputs":[],"name":"OracleLib_InvalidPrice","type":"error"},{"inputs":[],"name":"OracleLib_StalePrice","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"UUPSUnauthorizedCallContext","type":"error"},{"inputs":[{"internalType":"bytes32","name":"slot","type":"bytes32"}],"name":"UUPSUnsupportedProxiableUUID","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newAmount","type":"uint256"}],"name":"CollateralIncreased","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"collateralManager","type":"address"}],"name":"CollateralManagerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"hub","type":"address"}],"name":"HubSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint64","name":"version","type":"uint64"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"LiquidationCleared","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"triggeredAt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"debt","type":"uint256"},{"indexed":false,"internalType":"uint16","name":"maxBonusBps","type":"uint16"}],"name":"LiquidationTriggered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"LoanClosed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"borrower","type":"address"},{"indexed":true,"internalType":"address","name":"lender","type":"address"},{"indexed":false,"internalType":"address","name":"apn","type":"address"},{"indexed":false,"internalType":"address","name":"principalToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"principalAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"originationFee","type":"uint256"}],"name":"LoanCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"liquidator","type":"address"},{"indexed":false,"internalType":"bool","name":"isPartial","type":"bool"},{"indexed":false,"internalType":"uint256","name":"repaid","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"collateralSeized","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"bonusBps","type":"uint256"}],"name":"LoanLiquidated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"payer","type":"address"},{"indexed":false,"internalType":"uint256","name":"interestPortion","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"protocolFee","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"principalPortion","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outstandingPrincipal","type":"uint256"}],"name":"LoanRepaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"shortfall","type":"uint256"}],"name":"LoanWrittenDown","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"MarginCallCleared","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"matchId","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"triggeredAt","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"currentLtvBps","type":"uint256"}],"name":"MarginCallTriggered","type":"event"},{"anonymous":false,"inputs":[{"components":[{"internalType":"uint32","name":"auctionDuration","type":"uint32"},{"internalType":"uint32","name":"marginCallDeadline","type":"uint32"},{"internalType":"uint32","name":"maturityGracePeriod","type":"uint32"},{"internalType":"uint16","name":"bMin","type":"uint16"},{"internalType":"uint16","name":"hfFloor","type":"uint16"},{"internalType":"uint16","name":"restoreBuffer","type":"uint16"}],"indexed":false,"internalType":"struct ILoanManager.RiskParams","name":"params","type":"tuple"}],"name":"RiskParamsUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UPGRADE_INTERFACE_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"apnImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"auctionOf","outputs":[{"components":[{"internalType":"uint64","name":"marginCallAt","type":"uint64"},{"internalType":"uint64","name":"liquidationAt","type":"uint64"}],"internalType":"struct ILoanManager.Auction","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"clearLiquidation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"clearMarginCall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"collateralManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"debtOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"},{"components":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"address","name":"lender","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"uint256","name":"collateralChainId","type":"uint256"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint8","name":"collateralDecimals","type":"uint8"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"bytes32","name":"oracleType","type":"bytes32"},{"internalType":"uint32","name":"maxStaleness","type":"uint32"},{"internalType":"uint16","name":"ltv","type":"uint16"},{"internalType":"uint16","name":"marginCallThreshold","type":"uint16"},{"internalType":"uint16","name":"liquidationThreshold","type":"uint16"},{"internalType":"uint16","name":"maxLiquidationBonus","type":"uint16"},{"internalType":"uint16","name":"rate","type":"uint16"},{"internalType":"bytes32","name":"rateType","type":"bytes32"},{"internalType":"address","name":"principalToken","type":"address"},{"internalType":"uint256","name":"principalChainId","type":"uint256"},{"internalType":"uint256","name":"principalAmount","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"},{"internalType":"bool","name":"apnTransferable","type":"bool"}],"internalType":"struct ExecutedTerms","name":"terms","type":"tuple"},{"internalType":"string","name":"apnName","type":"string"},{"internalType":"string","name":"apnSymbol","type":"string"}],"name":"execute","outputs":[{"internalType":"address","name":"apn","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"feeRegistry","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"healthOf","outputs":[{"internalType":"uint256","name":"debt","type":"uint256"},{"internalType":"uint256","name":"collateralValue","type":"uint256"},{"internalType":"uint256","name":"ltvBps","type":"uint256"},{"internalType":"uint8","name":"zone","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"hub","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"increaseCollateral","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"admin","type":"address"},{"internalType":"address","name":"upgrader","type":"address"},{"internalType":"address","name":"feeRegistry_","type":"address"},{"internalType":"address","name":"apnImplementation_","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"},{"internalType":"uint256","name":"maxRepay","type":"uint256"},{"internalType":"uint256","name":"minSeized","type":"uint256"}],"name":"liquidate","outputs":[{"internalType":"uint256","name":"repaid","type":"uint256"},{"internalType":"uint256","name":"collateralSeized","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"},{"internalType":"uint256","name":"repayAmount","type":"uint256"},{"internalType":"uint256","name":"minSeized","type":"uint256"}],"name":"liquidatePartial","outputs":[{"internalType":"uint256","name":"repaid","type":"uint256"},{"internalType":"uint256","name":"collateralSeized","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"loanOf","outputs":[{"components":[{"internalType":"address","name":"borrower","type":"address"},{"internalType":"address","name":"apn","type":"address"},{"internalType":"address","name":"collateralToken","type":"address"},{"internalType":"uint256","name":"collateralAmount","type":"uint256"},{"internalType":"uint256","name":"collateralChainId","type":"uint256"},{"internalType":"uint8","name":"collateralDecimals","type":"uint8"},{"internalType":"address","name":"oracle","type":"address"},{"internalType":"bytes32","name":"oracleType","type":"bytes32"},{"internalType":"uint32","name":"maxStaleness","type":"uint32"},{"internalType":"uint16","name":"ltv","type":"uint16"},{"internalType":"uint16","name":"marginCallThreshold","type":"uint16"},{"internalType":"uint16","name":"liquidationThreshold","type":"uint16"},{"internalType":"uint16","name":"maxLiquidationBonus","type":"uint16"},{"internalType":"address","name":"principalToken","type":"address"},{"internalType":"uint8","name":"principalDecimals","type":"uint8"},{"internalType":"uint256","name":"principalChainId","type":"uint256"},{"internalType":"uint256","name":"outstandingPrincipal","type":"uint256"},{"internalType":"uint16","name":"rate","type":"uint16"},{"internalType":"bytes32","name":"rateType","type":"bytes32"},{"internalType":"uint16","name":"interestTakeRateBps","type":"uint16"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"uint256","name":"duration","type":"uint256"},{"internalType":"uint256","name":"lastAccrualTimestamp","type":"uint256"}],"internalType":"struct ILoanManager.Loan","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"proxiableUUID","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"callerConfirmation","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"repay","outputs":[{"internalType":"uint256","name":"interestPortion","type":"uint256"},{"internalType":"uint256","name":"principalPortion","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"riskParams","outputs":[{"components":[{"internalType":"uint32","name":"auctionDuration","type":"uint32"},{"internalType":"uint32","name":"marginCallDeadline","type":"uint32"},{"internalType":"uint32","name":"maturityGracePeriod","type":"uint32"},{"internalType":"uint16","name":"bMin","type":"uint16"},{"internalType":"uint16","name":"hfFloor","type":"uint16"},{"internalType":"uint16","name":"restoreBuffer","type":"uint16"}],"internalType":"struct ILoanManager.RiskParams","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newCollateralManager","type":"address"}],"name":"setCollateralManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newHub","type":"address"}],"name":"setHub","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint32","name":"auctionDuration","type":"uint32"},{"internalType":"uint32","name":"marginCallDeadline","type":"uint32"},{"internalType":"uint32","name":"maturityGracePeriod","type":"uint32"},{"internalType":"uint16","name":"bMin","type":"uint16"},{"internalType":"uint16","name":"hfFloor","type":"uint16"},{"internalType":"uint16","name":"restoreBuffer","type":"uint16"}],"internalType":"struct ILoanManager.RiskParams","name":"params","type":"tuple"}],"name":"setRiskParams","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"triggerLiquidation","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"triggerMarginCall","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"matchId","type":"bytes32"}],"name":"unrealizedValue","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newImplementation","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"upgradeToAndCall","outputs":[],"stateMutability":"payable","type":"function"}],"devdoc":{"details":"UUPS-upgradeable; upgrades are gated by `UPGRADER_ROLE` (a Timelock in production). The Hub      is wired once via {setHub}; the FeeRegistry and APN template are fixed at initialization and      can only change through an upgrade. Storage uses ERC-7201.","errors":{"AccessControlBadConfirmation()":[{"details":"The caller of a function is not the expected one. NOTE: Don't confuse with {AccessControlUnauthorizedAccount}."}],"AccessControlUnauthorizedAccount(address,bytes32)":[{"details":"The `account` is missing a role."}],"AddressEmptyCode(address)":[{"details":"There's no code at `target` (it is not a contract)."}],"ERC1967InvalidImplementation(address)":[{"details":"The `implementation` of the proxy is invalid."}],"ERC1967NonPayable()":[{"details":"An upgrade function sees `msg.value > 0` that may be lost."}],"FailedCall()":[{"details":"A call to an address target failed. The target may have reverted."}],"FailedDeployment()":[{"details":"The deployment failed."}],"InsufficientBalance(uint256,uint256)":[{"details":"The ETH balance of the account is not enough to perform the operation."}],"InvalidInitialization()":[{"details":"The contract is already initialized."}],"NotInitializing()":[{"details":"The contract is not initializing."}],"ReentrancyGuardReentrantCall()":[{"details":"Unauthorized reentrant call."}],"SafeERC20FailedOperation(address)":[{"details":"An operation with an ERC-20 token failed."}],"UUPSUnauthorizedCallContext()":[{"details":"The call is from an unauthorized context."}],"UUPSUnsupportedProxiableUUID(bytes32)":[{"details":"The storage `slot` is unsupported as a UUID."}]},"events":{"Initialized(uint64)":{"details":"Triggered when the contract has been initialized or reinitialized."},"RoleAdminChanged(bytes32,bytes32,bytes32)":{"details":"Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite {RoleAdminChanged} not being emitted to signal this."},"RoleGranted(bytes32,address,address)":{"details":"Emitted when `account` is granted `role`. `sender` is the account that originated the contract call. This account bears the admin role (for the granted role). Expected in cases where the role was granted using the internal {AccessControl-_grantRole}."},"RoleRevoked(bytes32,address,address)":{"details":"Emitted when `account` is revoked `role`. `sender` is the account that originated the contract call:   - if using `revokeRole`, it is the admin role bearer   - if using `renounceRole`, it is the role bearer (i.e. `account`)"},"Upgraded(address)":{"details":"Emitted when the implementation is upgraded."}},"kind":"dev","methods":{"clearMarginCall(bytes32)":{"details":"Repay- and top-up-driven recoveries clear automatically ({_tryClearRemediation}), but a      purely price-driven recovery writes no transaction, so nothing on-chain can observe it.      Left uncleared, the stale timestamp would let a re-dip into Zone 2 be liquidated with no      fresh grace — the borrower or the off-chain monitor calls this on every price recovery."},"execute(bytes32,(address,address,address,uint256,uint256,uint8,address,bytes32,uint32,uint16,uint16,uint16,uint16,uint16,bytes32,address,uint256,uint256,uint256,bool),string,string)":{"params":{"apnName":"Display name for the loan's APN token (executor-supplied, cosmetic).","apnSymbol":"Display symbol for the loan's APN token (executor-supplied, cosmetic)."},"returns":{"apn":"The APN token minted for this loan."}},"getRoleAdmin(bytes32)":{"details":"Returns the admin role that controls `role`. See {grantRole} and {revokeRole}. To change a role's admin, use {_setRoleAdmin}."},"grantRole(bytes32,address)":{"details":"Grants `role` to `account`. If `account` had not been already granted `role`, emits a {RoleGranted} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleGranted} event."},"hasRole(bytes32,address)":{"details":"Returns `true` if `account` has been granted `role`."},"initialize(address,address,address,address)":{"params":{"admin":"Holds DEFAULT_ADMIN_ROLE. Wires the AmishHub once via {setHub} after deployment.","apnImplementation_":"The APN template cloned per loan. Fixed here; upgrade to change.","feeRegistry_":"The FeeRegistry read at execution. Fixed here; upgrade to change.","upgrader":"Holds UPGRADER_ROLE (a Timelock in production)."}},"liquidate(bytes32,uint256,uint256)":{"params":{"maxRepay":"Slippage guard on the pay side: the largest repayment the caller will make;        reverts if the required repayment exceeds it.","minSeized":"Slippage guard on the receive side: the smallest collateral amount the caller        will accept; reverts if the seize comes in below it. Together the two bound the        caller's worst-case exchange rate against oracle/bonus movement between submission and        inclusion. Pass 0 to accept any seize (required to close a dust debt whose seize        rounds to zero)."},"returns":{"collateralSeized":"Collateral base units transferred to the caller.","repaid":"Principal-token amount actually repaid."}},"liquidatePartial(bytes32,uint256,uint256)":{"params":{"minSeized":"Slippage guard on the receive side, expressed as a RATE quote: the collateral        the caller expects for a full `repayAmount` fill. When the engine caps the fill (a        smaller live restoring maximum after a competing partial, or the debt), the floor        scales pro-rata with the actual `repaid`, so a fairly-priced smaller fill executes and        only a worsened exchange rate (price/bonus moved against the caller) reverts. Pass 0        to accept any rate."},"returns":{"collateralSeized":"Collateral base units transferred to the caller.","repaid":"Principal-token amount actually repaid."}},"proxiableUUID()":{"details":"Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the implementation. It is used to validate the implementation's compatibility when performing an upgrade. IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier."},"renounceRole(bytes32,address)":{"details":"Revokes `role` from the calling account. Roles are often managed via {grantRole} and {revokeRole}: this function's purpose is to provide a mechanism for accounts to lose their privileges if they are compromised (such as when a trusted device is misplaced). If the calling account had been revoked `role`, emits a {RoleRevoked} event. Requirements: - the caller must be `callerConfirmation`. May emit a {RoleRevoked} event."},"repay(bytes32,uint256)":{"returns":{"interestPortion":"Interest covered by this payment (protocol take + lender interest).","principalPortion":"Principal repaid by this payment."}},"revokeRole(bytes32,address)":{"details":"Revokes `role` from `account`. If `account` had been granted `role`, emits a {RoleRevoked} event. Requirements: - the caller must have ``role``'s admin role. May emit a {RoleRevoked} event."},"supportsInterface(bytes4)":{"details":"Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] to learn more about how these ids are created. This function call must use less than 30 000 gas."},"upgradeToAndCall(address,bytes)":{"custom:oz-upgrades-unsafe-allow-reachable":"delegatecall","details":"Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call encoded in `data`. Calls {_authorizeUpgrade}. Emits an {Upgraded} event."}},"title":"LoanManager","version":1},"userdoc":{"kind":"user","methods":{"apnImplementation()":{"notice":"The APN template cloned per loan."},"auctionOf(bytes32)":{"notice":"The liquidation-auction state for `matchId` (all-zero if healthy/untriggered)."},"clearLiquidation(bytes32)":{"notice":"Clear a full-liquidation trigger whose loan has recovered below its liquidation threshold         and is not past maturity, closing the auction. Interest was never paused, so the window it         was open stays billed. Permissionless."},"clearMarginCall(bytes32)":{"notice":"Clear a margin call whose loan has recovered below `marginCallThreshold`, so a later         re-crossing starts a fresh grace period. Permissionless."},"collateralManager()":{"notice":"The CollateralManager this manager releases collateral from."},"debtOf(bytes32)":{"notice":"The loan's live gross debt — outstanding principal plus interest accrued to this         second (the exact amount a full repayment would settle right now). Zero for an         unknown or fully-repaid loan. Pure state read: no oracle involved."},"execute(bytes32,(address,address,address,uint256,uint256,uint8,address,bytes32,uint32,uint16,uint16,uint16,uint16,uint16,bytes32,address,uint256,uint256,uint256,bool),string,string)":{"notice":"Create a loan from derived terms: move principal (minus the origination fee), record         the loan, and mint the lender an APN. Restricted to the orchestrator."},"feeRegistry()":{"notice":"The FeeRegistry read at execution."},"healthOf(bytes32)":{"notice":"One-read health snapshot for off-chain monitors: live debt, the collateral's value         in principal base units at the live oracle price, the current LTV in bps, and the         zone. `zone` is trigger eligibility, matching {triggerLiquidation} /         {triggerMarginCall} exactly: 2 = liquidatable (LTV ≥ liquidation threshold or past         the maturity-default deadline), 1 = margin-call band [MCT, LT), 0 = healthy.         All-zero for an unknown or fully-repaid loan. Reverts on a stale or invalid oracle         price, like every other health-dependent path — treat a revert as \"no fresh         classification available\", never as healthy."},"hub()":{"notice":"The AmishHub wired to this manager."},"increaseCollateral(bytes32,uint256)":{"notice":"Increase the loan's denormalized collateral amount by `amount`. Restricted to the         CollateralManager, which calls it from {ICollateralManager-addCollateral} after it has         custodied the additional collateral, keeping the two records in sync. Like a repayment,         a top-up that restores health clears any margin call or pre-maturity liquidation trigger         it cured (best-effort: skipped if the oracle is stale, never blocking the top-up)."},"liquidate(bytes32,uint256,uint256)":{"notice":"Full liquidation of a triggered loan: repay the live debt — or, if the collateral cannot         cover debt plus bonus, as much as the collateral backs, writing down the shortfall — seize         the corresponding collateral (bonus included), return any excess to the borrower, and close         the loan. Permissionless; funds pulled from the caller. A trigger that predates the         maturity default and whose distress has since recovered prices its bonus from the default         deadline rather than its stale clock."},"liquidatePartial(bytes32,uint256,uint256)":{"notice":"Zone-2 partial liquidation after the margin-call grace period: repay up to the amount         that restores the position to `MCT - restoreBuffer`, seizing collateral worth the         repayment plus the time/distress-scaled bonus. The loan persists — except on the knife         edge where the restoring repayment settles the entire debt, which closes the loan and         releases any remaining collateral. Permissionless; funds pulled from the caller.         `repayAmount` is capped to the restoring maximum and the debt."},"loanOf(bytes32)":{"notice":"The loan recorded for `matchId` (zeroed if none)."},"repay(bytes32,uint256)":{"notice":"Repay up to the loan's current debt, applying the interest-first waterfall: interest is         paid first and split between the treasury and the lender (recorded to the APN), the         remainder reduces principal. Permissionless (funds pulled from the caller); an amount         above the total owed is capped. Releases the collateral once principal reaches zero.         Works during a live full-liquidation auction too, letting the borrower de-lever or fully         close mid-auction. Interest is charged live for the whole elapsed window in every case, so         repaying confers no interest advantage over a healthy loan and a seizure confers none over         repaying. A partial payment that restores health clears whatever it cured — a margin call         once back below the margin-call threshold, a pre-maturity liquidation trigger once back         below the liquidation threshold (best-effort: skipped if the oracle is stale, never         blocking the repayment); otherwise the loan stays liquidatable with the auction's bonus         clock intact (a maturity default always stays liquidatable)."},"riskParams()":{"notice":"The global liquidation risk parameters."},"setCollateralManager(address)":{"notice":"Wire the CollateralManager. Callable exactly once; afterwards frozen (upgrade to         change). This is the vault this manager releases collateral from once a loan is         repaid; the reverse wire (CollateralManager -> this) lets add-collateral stay in sync."},"setHub(address)":{"notice":"Wire the AmishHub. Callable exactly once; afterwards frozen (upgrade to change). The         one-time set prevents the admin from ever granting the execution path to any address."},"setRiskParams((uint32,uint32,uint32,uint16,uint16,uint16))":{"notice":"Replace the global liquidation risk parameters. Restricted to `RISK_MANAGER_ROLE`.         Every field is range-checked: durations have floors so grace/auction windows can never         collapse to zero, and the bonus/threshold levers are capped. What makes a specific loan         liquidatable (its MCT/LT/maxLiquidationBonus) is fixed in the signed intent and is not         reachable here."},"triggerLiquidation(bytes32)":{"notice":"Open a full-liquidation auction, starting the reverse-Dutch bonus clock. Interest keeps         accruing live (the auction never pauses it). Valid when current LTV has crossed the         liquidation threshold (Zone 3) or the loan is past maturity plus the grace period         (maturity default). Permissionless."},"triggerMarginCall(bytes32)":{"notice":"Open a Zone-2 margin call on a loan whose current LTV has crossed into         `[marginCallThreshold, liquidationThreshold)`, starting the grace period. Permissionless.         Reverts if the loan is outside that band or already margin-called or in a liquidation auction."},"unrealizedValue(bytes32)":{"notice":"The not-yet-cash part of a loan's APN net asset value: value the note holders are owed         but that has not been repaid into the note yet — outstanding principal plus the lender's         mark-to-market accrued-but-unpaid interest (net of the protocol take), in principal base         units. The APN prices redemptions as `unrealizedValue + cash on hand`. Goes to zero once         principal is fully repaid (all value is then cash) or for an unknown loan."}},"notice":"Singleton that manages all loans on the principal chain. On execution it moves the         principal from the lender to the borrower (net of the origination fee, which goes to the         treasury), records the loan with its collateral parameters denormalized, snapshots the         interest take rate, and mints the lender an APN.","version":1}},"settings":{"compilationTarget":{"amish-contracts/src/LoanManager.sol":"LoanManager"},"evmVersion":"cancun","libraries":{},"metadata":{"bytecodeHash":"ipfs"},"optimizer":{"enabled":true,"runs":200},"remappings":[":@openzeppelin-contracts-5.6.1/=../../../amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/",":@openzeppelin-contracts-upgradeable-5.6.1/=../../../amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/",":@openzeppelin/contracts/=../../../amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/",":amish-test/=../../../amish-contracts/test/",":amish/=../../../amish-contracts/src/",":forge-std-1.16.1/=../../../amish-contracts/dependencies/forge-std-1.16.1/src/",":forge-std/=../../../amish-contracts/dependencies/forge-std-1.16.1/src/"],"viaIR":true},"sources":{"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/access/IAccessControl.sol":{"keccak256":"0xbff9f59c84e5337689161ce7641c0ef8e872d6a7536fbc1f5133f128887aba3c","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev External interface of AccessControl declared to support ERC-165 detection.\n */\ninterface IAccessControl {\n    /**\n     * @dev The `account` is missing a role.\n     */\n    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);\n\n    /**\n     * @dev The caller of a function is not the expected one.\n     *\n     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.\n     */\n    error AccessControlBadConfirmation();\n\n    /**\n     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n     *\n     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n     * {RoleAdminChanged} not being emitted to signal this.\n     */\n    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n    /**\n     * @dev Emitted when `account` is granted `role`.\n     *\n     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).\n     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.\n     */\n    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Emitted when `account` is revoked `role`.\n     *\n     * `sender` is the account that originated the contract call:\n     *   - if using `revokeRole`, it is the admin role bearer\n     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)\n     */\n    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) external view returns (bool);\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function grantRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     */\n    function revokeRole(bytes32 role, address account) external;\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been granted `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) external;\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/interfaces/IERC1363.sol":{"keccak256":"0xd5ea07362ab630a6a3dee4285a74cf2377044ca2e4be472755ad64d7c5d4b69d","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"./IERC20.sol\";\nimport {IERC165} from \"./IERC165.sol\";\n\n/**\n * @title IERC1363\n * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].\n *\n * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract\n * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.\n */\ninterface IERC1363 is IERC20, IERC165 {\n    /*\n     * Note: the ERC-165 identifier for this interface is 0xb0202a11.\n     * 0xb0202a11 ===\n     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^\n     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^\n     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))\n     */\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism\n     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.\n     * @param from The address which you want to send tokens from.\n     * @param to The address which you want to transfer to.\n     * @param value The amount of tokens to be transferred.\n     * @param data Additional data with no specified format, sent in call to `to`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.\n     * @param spender The address which will spend the funds.\n     * @param value The amount of tokens to be spent.\n     * @param data Additional data with no specified format, sent in call to `spender`.\n     * @return A boolean value indicating whether the operation succeeded unless throwing.\n     */\n    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/interfaces/IERC165.sol":{"keccak256":"0x0afcb7e740d1537b252cb2676f600465ce6938398569f09ba1b9ca240dde2dfc","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/interfaces/IERC1967.sol":{"keccak256":"0xbf2aefe54b76d7f7bcd4f6da1080b7b1662611937d870b880db584d09cea56b5","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1967.sol)\n\npragma solidity >=0.4.11;\n\n/**\n * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.\n */\ninterface IERC1967 {\n    /**\n     * @dev Emitted when the implementation is upgraded.\n     */\n    event Upgraded(address indexed implementation);\n\n    /**\n     * @dev Emitted when the admin account has changed.\n     */\n    event AdminChanged(address previousAdmin, address newAdmin);\n\n    /**\n     * @dev Emitted when the beacon is changed.\n     */\n    event BeaconUpgraded(address indexed beacon);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/interfaces/IERC20.sol":{"keccak256":"0x1a6221315ce0307746c2c4827c125d821ee796c74a676787762f4778671d4f44","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)\n\npragma solidity >=0.4.16;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/interfaces/draft-IERC1822.sol":{"keccak256":"0x82f757819bf2429a0d4db141b99a4bbe5039e4ef86dfb94e2e6d40577ed5b28b","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n    /**\n     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n     * address.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy.\n     */\n    function proxiableUUID() external view returns (bytes32);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/interfaces/draft-IERC6093.sol":{"keccak256":"0x1b88b3fb3d85ba5496d7d5f396f83ee1fddcdd6762059ff65992655b67920998","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/draft-IERC6093.sol)\n\npragma solidity >=0.8.4;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-721.\n     * Used in balance queries.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721InvalidOwner(address owner);\n\n    /**\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721NonexistentToken(uint256 tokenId);\n\n    /**\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param tokenId Identifier number of a token.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC721InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC721InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC721InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC721InvalidOperator(address operator);\n}\n\n/**\n * @dev Standard ERC-1155 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\n */\ninterface IERC1155Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     * @param tokenId Identifier number of a token.\n     */\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC1155InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC1155InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     * @param owner Address of the current owner of a token.\n     */\n    error ERC1155MissingApprovalForAll(address operator, address owner);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC1155InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC1155InvalidOperator(address operator);\n\n    /**\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\n     * Used in batch transfers.\n     * @param idsLength Length of the array of token identifiers\n     * @param valuesLength Length of the array of token amounts\n     */\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/proxy/Clones.sol":{"keccak256":"0x5a1847c0c6b92d60711f04cba9eaff572ae1f657cff1b8ca4ba065bcdbd68d8b","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Clones.sol)\n\npragma solidity ^0.8.20;\n\nimport {Create2} from \"../utils/Create2.sol\";\nimport {Errors} from \"../utils/Errors.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for\n * deploying minimal proxy contracts, also known as \"clones\".\n *\n * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * > a minimal bytecode implementation that delegates all calls to a known, fixed address.\n *\n * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`\n * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the\n * deterministic method.\n */\nlibrary Clones {\n    error CloneArgumentsTooLong();\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.\n     *\n     * This function uses the create opcode, which should never revert.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     */\n    function clone(address implementation) internal returns (address instance) {\n        return clone(implementation, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency\n     * to the new contract.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     *\n     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)\n     * to always have enough balance for new deployments. Consider exposing this function under a payable method.\n     */\n    function clone(address implementation, uint256 value) internal returns (address instance) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        assembly (\"memory-safe\") {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create(value, 0x09, 0x37)\n        }\n        if (instance == address(0)) {\n            revert Errors.FailedDeployment();\n        }\n    }\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.\n     *\n     * This function uses the create2 opcode and a `salt` to deterministically deploy\n     * the clone. Using the same `implementation` and `salt` multiple times will revert, since\n     * the clones cannot be deployed twice at the same address.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     */\n    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {\n        return cloneDeterministic(implementation, salt, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with\n     * a `value` parameter to send native currency to the new contract.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     *\n     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)\n     * to always have enough balance for new deployments. Consider exposing this function under a payable method.\n     */\n    function cloneDeterministic(\n        address implementation,\n        bytes32 salt,\n        uint256 value\n    ) internal returns (address instance) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        assembly (\"memory-safe\") {\n            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n            // of the `implementation` address with the bytecode before the address.\n            mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n            mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n            instance := create2(value, 0x09, 0x37, salt)\n        }\n        if (instance == address(0)) {\n            revert Errors.FailedDeployment();\n        }\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt,\n        address deployer\n    ) internal pure returns (address predicted) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            mstore(add(ptr, 0x38), deployer)\n            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)\n            mstore(add(ptr, 0x14), implementation)\n            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)\n            mstore(add(ptr, 0x58), salt)\n            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))\n            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)\n        }\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n     */\n    function predictDeterministicAddress(\n        address implementation,\n        bytes32 salt\n    ) internal view returns (address predicted) {\n        return predictDeterministicAddress(implementation, salt, address(this));\n    }\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom\n     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To\n     * access the arguments within the implementation, use {fetchCloneArgs}.\n     *\n     * This function uses the create opcode, which should never revert.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     */\n    function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {\n        return cloneWithImmutableArgs(implementation, args, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`\n     * parameter to send native currency to the new contract.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     *\n     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)\n     * to always have enough balance for new deployments. Consider exposing this function under a payable method.\n     */\n    function cloneWithImmutableArgs(\n        address implementation,\n        bytes memory args,\n        uint256 value\n    ) internal returns (address instance) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);\n        assembly (\"memory-safe\") {\n            instance := create(value, add(bytecode, 0x20), mload(bytecode))\n        }\n        if (instance == address(0)) {\n            revert Errors.FailedDeployment();\n        }\n    }\n\n    /**\n     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom\n     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To\n     * access the arguments within the implementation, use {fetchCloneArgs}.\n     *\n     * This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same\n     * `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice\n     * at the same address.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     */\n    function cloneDeterministicWithImmutableArgs(\n        address implementation,\n        bytes memory args,\n        bytes32 salt\n    ) internal returns (address instance) {\n        return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],\n     * but with a `value` parameter to send native currency to the new contract.\n     *\n     * WARNING: This function does not check if `implementation` has code. A clone that points to an address\n     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they\n     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.\n     *\n     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)\n     * to always have enough balance for new deployments. Consider exposing this function under a payable method.\n     */\n    function cloneDeterministicWithImmutableArgs(\n        address implementation,\n        bytes memory args,\n        bytes32 salt,\n        uint256 value\n    ) internal returns (address instance) {\n        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);\n        return Create2.deploy(value, salt, bytecode);\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.\n     */\n    function predictDeterministicAddressWithImmutableArgs(\n        address implementation,\n        bytes memory args,\n        bytes32 salt,\n        address deployer\n    ) internal pure returns (address predicted) {\n        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);\n        return Create2.computeAddress(salt, keccak256(bytecode), deployer);\n    }\n\n    /**\n     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.\n     */\n    function predictDeterministicAddressWithImmutableArgs(\n        address implementation,\n        bytes memory args,\n        bytes32 salt\n    ) internal view returns (address predicted) {\n        return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));\n    }\n\n    /**\n     * @dev Get the immutable args attached to a clone.\n     *\n     * - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this\n     *   function will return an empty array.\n     * - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or\n     *   `cloneDeterministicWithImmutableArgs`, this function will return the args array used at\n     *   creation.\n     * - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This\n     *   function should only be used to check addresses that are known to be clones.\n     */\n    function fetchCloneArgs(address instance) internal view returns (bytes memory) {\n        bytes memory result = new bytes(instance.code.length - 0x2d); // revert if length is too short\n        assembly (\"memory-safe\") {\n            extcodecopy(instance, add(result, 0x20), 0x2d, mload(result))\n        }\n        return result;\n    }\n\n    /**\n     * @dev Helper that prepares the initcode of the proxy with immutable args.\n     *\n     * An assembly variant of this function requires copying the `args` array, which can be efficiently done using\n     * `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using\n     * abi.encodePacked is more expensive but also more portable and easier to review.\n     *\n     * NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.\n     * With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.\n     */\n    function _cloneCodeWithImmutableArgs(\n        address implementation,\n        bytes memory args\n    ) private pure returns (bytes memory) {\n        if (args.length > 0x5fd3) revert CloneArgumentsTooLong();\n        return\n            abi.encodePacked(\n                hex\"61\",\n                uint16(args.length + 0x2d),\n                hex\"3d81600a3d39f3363d3d373d3d3d363d73\",\n                implementation,\n                hex\"5af43d82803e903d91602b57fd5bf3\",\n                args\n            );\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/proxy/ERC1967/ERC1967Utils.sol":{"keccak256":"0x3d8b816f00b4cabe9a9fb7e84908ef785d6e5b0ef988bcd3c52fe811b4559686","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.6.0) (proxy/ERC1967/ERC1967Utils.sol)\n\npragma solidity ^0.8.21;\n\nimport {IBeacon} from \"../beacon/IBeacon.sol\";\nimport {IERC1967} from \"../../interfaces/IERC1967.sol\";\nimport {Address} from \"../../utils/Address.sol\";\nimport {StorageSlot} from \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This library provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.\n */\nlibrary ERC1967Utils {\n    /**\n     * @dev Storage slot with the address of the current implementation.\n     * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n    /**\n     * @dev The `implementation` of the proxy is invalid.\n     */\n    error ERC1967InvalidImplementation(address implementation);\n\n    /**\n     * @dev The `admin` of the proxy is invalid.\n     */\n    error ERC1967InvalidAdmin(address admin);\n\n    /**\n     * @dev The `beacon` of the proxy is invalid.\n     */\n    error ERC1967InvalidBeacon(address beacon);\n\n    /**\n     * @dev An upgrade function sees `msg.value > 0` that may be lost.\n     */\n    error ERC1967NonPayable();\n\n    /**\n     * @dev Returns the current implementation address.\n     */\n    function getImplementation() internal view returns (address) {\n        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 implementation slot.\n     */\n    function _setImplementation(address newImplementation) private {\n        if (newImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(newImplementation);\n        }\n        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;\n    }\n\n    /**\n     * @dev Performs implementation upgrade with additional setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) internal {\n        _setImplementation(newImplementation);\n        emit IERC1967.Upgraded(newImplementation);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(newImplementation, data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Storage slot with the admin of the contract.\n     * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n    /**\n     * @dev Returns the current admin.\n     *\n     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using\n     * the https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat[`eth_getStorageAt`] RPC call.\n     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n     */\n    function getAdmin() internal view returns (address) {\n        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new address in the ERC-1967 admin slot.\n     */\n    function _setAdmin(address newAdmin) private {\n        if (newAdmin == address(0)) {\n            revert ERC1967InvalidAdmin(address(0));\n        }\n        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;\n    }\n\n    /**\n     * @dev Changes the admin of the proxy.\n     *\n     * Emits an {IERC1967-AdminChanged} event.\n     */\n    function changeAdmin(address newAdmin) internal {\n        emit IERC1967.AdminChanged(getAdmin(), newAdmin);\n        _setAdmin(newAdmin);\n    }\n\n    /**\n     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n     * This is the keccak-256 hash of \"eip1967.proxy.beacon\" subtracted by 1.\n     */\n    // solhint-disable-next-line private-vars-leading-underscore\n    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n    /**\n     * @dev Returns the current beacon.\n     */\n    function getBeacon() internal view returns (address) {\n        return StorageSlot.getAddressSlot(BEACON_SLOT).value;\n    }\n\n    /**\n     * @dev Stores a new beacon in the ERC-1967 beacon slot.\n     */\n    function _setBeacon(address newBeacon) private {\n        if (newBeacon.code.length == 0) {\n            revert ERC1967InvalidBeacon(newBeacon);\n        }\n\n        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;\n\n        address beaconImplementation = IBeacon(newBeacon).implementation();\n        if (beaconImplementation.code.length == 0) {\n            revert ERC1967InvalidImplementation(beaconImplementation);\n        }\n    }\n\n    /**\n     * @dev Change the beacon and trigger a setup call if data is nonempty.\n     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected\n     * to avoid stuck value in the contract.\n     *\n     * Emits an {IERC1967-BeaconUpgraded} event.\n     *\n     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since\n     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for\n     * efficiency.\n     */\n    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {\n        _setBeacon(newBeacon);\n        emit IERC1967.BeaconUpgraded(newBeacon);\n\n        if (data.length > 0) {\n            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n        } else {\n            _checkNonPayable();\n        }\n    }\n\n    /**\n     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract\n     * if an upgrade doesn't perform an initialization call.\n     */\n    function _checkNonPayable() private {\n        if (msg.value > 0) {\n            revert ERC1967NonPayable();\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/proxy/beacon/IBeacon.sol":{"keccak256":"0x20462ddb2665e9521372c76b001d0ce196e59dbbd989de9af5576cad0bd5628b","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n    /**\n     * @dev Must return an address that can be used as a delegate call target.\n     *\n     * {UpgradeableBeacon} will check that this address is a contract.\n     */\n    function implementation() external view returns (address);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/proxy/utils/Initializable.sol":{"keccak256":"0xdb4d24ee2c087c391d587cd17adfe5b3f9d93b3110b1388c2ab6c7c0ad1dcd05","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n *     function initialize() initializer public {\n *         __ERC20_init(\"MyToken\", \"MTK\");\n *     }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n *     function initializeV2() reinitializer(2) public {\n *         __ERC20Permit_init(\"MyToken\");\n *     }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n *     _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n    /**\n     * @dev Storage of the initializable contract.\n     *\n     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions\n     * when using with upgradeable contracts.\n     *\n     * @custom:storage-location erc7201:openzeppelin.storage.Initializable\n     */\n    struct InitializableStorage {\n        /**\n         * @dev Indicates that the contract has been initialized.\n         */\n        uint64 _initialized;\n        /**\n         * @dev Indicates that the contract is in the process of being initialized.\n         */\n        bool _initializing;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Initializable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;\n\n    /**\n     * @dev The contract is already initialized.\n     */\n    error InvalidInitialization();\n\n    /**\n     * @dev The contract is not initializing.\n     */\n    error NotInitializing();\n\n    /**\n     * @dev Triggered when the contract has been initialized or reinitialized.\n     */\n    event Initialized(uint64 version);\n\n    /**\n     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n     * `onlyInitializing` functions can be used to initialize parent contracts.\n     *\n     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any\n     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in\n     * production.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier initializer() {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        // Cache values to avoid duplicated sloads\n        bool isTopLevelCall = !$._initializing;\n        uint64 initialized = $._initialized;\n\n        // Allowed calls:\n        // - initialSetup: the contract is not in the initializing state and no previous version was\n        //                 initialized\n        // - construction: the contract is initialized at version 1 (no reinitialization) and the\n        //                 current contract is just being deployed\n        bool initialSetup = initialized == 0 && isTopLevelCall;\n        bool construction = initialized == 1 && address(this).code.length == 0;\n\n        if (!initialSetup && !construction) {\n            revert InvalidInitialization();\n        }\n        $._initialized = 1;\n        if (isTopLevelCall) {\n            $._initializing = true;\n        }\n        _;\n        if (isTopLevelCall) {\n            $._initializing = false;\n            emit Initialized(1);\n        }\n    }\n\n    /**\n     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n     * used to initialize parent contracts.\n     *\n     * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n     * are added through upgrades and that require initialization.\n     *\n     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n     * cannot be nested. If one is invoked in the context of another, execution will revert.\n     *\n     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n     * a contract, executing them in the right order is up to the developer or operator.\n     *\n     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.\n     *\n     * Emits an {Initialized} event.\n     */\n    modifier reinitializer(uint64 version) {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing || $._initialized >= version) {\n            revert InvalidInitialization();\n        }\n        $._initialized = version;\n        $._initializing = true;\n        _;\n        $._initializing = false;\n        emit Initialized(version);\n    }\n\n    /**\n     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n     * {initializer} and {reinitializer} modifiers, directly or indirectly.\n     */\n    modifier onlyInitializing() {\n        _checkInitializing();\n        _;\n    }\n\n    /**\n     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.\n     */\n    function _checkInitializing() internal view virtual {\n        if (!_isInitializing()) {\n            revert NotInitializing();\n        }\n    }\n\n    /**\n     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n     * through proxies.\n     *\n     * Emits an {Initialized} event the first time it is successfully executed.\n     */\n    function _disableInitializers() internal virtual {\n        // solhint-disable-next-line var-name-mixedcase\n        InitializableStorage storage $ = _getInitializableStorage();\n\n        if ($._initializing) {\n            revert InvalidInitialization();\n        }\n        if ($._initialized != type(uint64).max) {\n            $._initialized = type(uint64).max;\n            emit Initialized(type(uint64).max);\n        }\n    }\n\n    /**\n     * @dev Returns the highest version that has been initialized. See {reinitializer}.\n     */\n    function _getInitializedVersion() internal view returns (uint64) {\n        return _getInitializableStorage()._initialized;\n    }\n\n    /**\n     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.\n     */\n    function _isInitializing() internal view returns (bool) {\n        return _getInitializableStorage()._initializing;\n    }\n\n    /**\n     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.\n     *\n     * NOTE: Consider following the ERC-7201 formula to derive storage locations.\n     */\n    function _initializableStorageSlot() internal pure virtual returns (bytes32) {\n        return INITIALIZABLE_STORAGE;\n    }\n\n    /**\n     * @dev Returns a pointer to the storage namespace.\n     */\n    // solhint-disable-next-line var-name-mixedcase\n    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {\n        bytes32 slot = _initializableStorageSlot();\n        assembly {\n            $.slot := slot\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/proxy/utils/UUPSUpgradeable.sol":{"keccak256":"0x1a26353563a2c63b4120ea0b94727253eeff84fe2241d42c1452308b9080e66a","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.22;\n\nimport {IERC1822Proxiable} from \"../../interfaces/draft-IERC1822.sol\";\nimport {ERC1967Utils} from \"../ERC1967/ERC1967Utils.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n *\n * @custom:stateless\n */\nabstract contract UUPSUpgradeable is IERC1822Proxiable {\n    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable\n    address private immutable __self = address(this);\n\n    /**\n     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`\n     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,\n     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.\n     * If the getter returns `\"5.0.0\"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must\n     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function\n     * during an upgrade.\n     */\n    string public constant UPGRADE_INTERFACE_VERSION = \"5.0.0\";\n\n    /**\n     * @dev The call is from an unauthorized context.\n     */\n    error UUPSUnauthorizedCallContext();\n\n    /**\n     * @dev The storage `slot` is unsupported as a UUID.\n     */\n    error UUPSUnsupportedProxiableUUID(bytes32 slot);\n\n    /**\n     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case\n     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n     * fail.\n     */\n    modifier onlyProxy() {\n        _checkProxy();\n        _;\n    }\n\n    /**\n     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n     * callable on the implementing contract but not through proxies.\n     */\n    modifier notDelegated() {\n        _checkNotDelegated();\n        _;\n    }\n\n    /**\n     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the\n     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n     *\n     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n     */\n    function proxiableUUID() external view notDelegated returns (bytes32) {\n        return ERC1967Utils.IMPLEMENTATION_SLOT;\n    }\n\n    /**\n     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n     * encoded in `data`.\n     *\n     * Calls {_authorizeUpgrade}.\n     *\n     * Emits an {Upgraded} event.\n     *\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n        _authorizeUpgrade(newImplementation);\n        _upgradeToAndCallUUPS(newImplementation, data);\n    }\n\n    /**\n     * @dev Reverts if the execution is not performed via delegatecall or the execution\n     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.\n     */\n    function _checkProxy() internal view virtual {\n        if (\n            address(this) == __self || // Must be called through delegatecall\n            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy\n        ) {\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Reverts if the execution is performed via delegatecall.\n     * See {notDelegated}.\n     */\n    function _checkNotDelegated() internal view virtual {\n        if (address(this) != __self) {\n            // Must not be called through delegatecall\n            revert UUPSUnauthorizedCallContext();\n        }\n    }\n\n    /**\n     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n     * {upgradeToAndCall}.\n     *\n     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n     *\n     * ```solidity\n     * function _authorizeUpgrade(address) internal onlyOwner {}\n     * ```\n     */\n    function _authorizeUpgrade(address newImplementation) internal virtual;\n\n    /**\n     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.\n     *\n     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value\n     * is expected to be the implementation slot in ERC-1967.\n     *\n     * Emits an {IERC1967-Upgraded} event.\n     */\n    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {\n        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {\n                revert UUPSUnsupportedProxiableUUID(slot);\n            }\n            ERC1967Utils.upgradeToAndCall(newImplementation, data);\n        } catch {\n            // The implementation is not UUPS\n            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/token/ERC20/IERC20.sol":{"keccak256":"0x74ed01eb66b923d0d0cfe3be84604ac04b76482a55f9dd655e1ef4d367f95bc2","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/token/ERC20/extensions/IERC20Metadata.sol":{"keccak256":"0xd6fa4088198f04eef10c5bce8a2f4d60554b7ec4b987f684393c01bf79b94d9f","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/token/ERC20/utils/SafeERC20.sol":{"keccak256":"0x304d732678032a9781ae85c8f204c8fba3d3a5e31c02616964e75cfdc5049098","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../IERC20.sol\";\nimport {IERC1363} from \"../../../interfaces/IERC1363.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC-20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n    /**\n     * @dev An operation with an ERC-20 token failed.\n     */\n    error SafeERC20FailedOperation(address token);\n\n    /**\n     * @dev Indicates a failed `decreaseAllowance` request.\n     */\n    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);\n\n    /**\n     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     */\n    function safeTransfer(IERC20 token, address to, uint256 value) internal {\n        if (!_safeTransfer(token, to, value, true)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the\n     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.\n     */\n    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n        if (!_safeTransferFrom(token, from, to, value, true)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {\n        return _safeTransfer(token, to, value, false);\n    }\n\n    /**\n     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.\n     */\n    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {\n        return _safeTransferFrom(token, from, to, value, false);\n    }\n\n    /**\n     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n        uint256 oldAllowance = token.allowance(address(this), spender);\n        forceApprove(token, spender, oldAllowance + value);\n    }\n\n    /**\n     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no\n     * value, non-reverting calls are assumed to be successful.\n     *\n     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the \"client\"\n     * smart contract uses ERC-7674 to set temporary allowances, then the \"client\" smart contract should avoid using\n     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract\n     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.\n     */\n    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {\n        unchecked {\n            uint256 currentAllowance = token.allowance(address(this), spender);\n            if (currentAllowance < requestedDecrease) {\n                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);\n            }\n            forceApprove(token, spender, currentAllowance - requestedDecrease);\n        }\n    }\n\n    /**\n     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,\n     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval\n     * to be set to zero before setting it to a non-zero value, such as USDT.\n     *\n     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function\n     * only sets the \"standard\" allowance. Any temporary allowance will remain active, in addition to the value being\n     * set here.\n     */\n    function forceApprove(IERC20 token, address spender, uint256 value) internal {\n        if (!_safeApprove(token, spender, value, false)) {\n            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));\n            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            safeTransfer(token, to, value);\n        } else if (!token.transferAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target\n     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function transferFromAndCallRelaxed(\n        IERC1363 token,\n        address from,\n        address to,\n        uint256 value,\n        bytes memory data\n    ) internal {\n        if (to.code.length == 0) {\n            safeTransferFrom(token, from, to, value);\n        } else if (!token.transferFromAndCall(from, to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no\n     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when\n     * targeting contracts.\n     *\n     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.\n     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}\n     * once without retrying, and relies on the returned value to be true.\n     *\n     * Reverts if the returned value is other than `true`.\n     */\n    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {\n        if (to.code.length == 0) {\n            forceApprove(token, to, value);\n        } else if (!token.approveAndCall(to, value, data)) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the\n     * return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param to The recipient of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {\n        bytes4 selector = IERC20.transfer.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(to, shr(96, not(0))))\n            mstore(0x24, value)\n            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return\n     * value: the return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param from The sender of the tokens\n     * @param to The recipient of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeTransferFrom(\n        IERC20 token,\n        address from,\n        address to,\n        uint256 value,\n        bool bubble\n    ) private returns (bool success) {\n        bytes4 selector = IERC20.transferFrom.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(from, shr(96, not(0))))\n            mstore(0x24, and(to, shr(96, not(0))))\n            mstore(0x44, value)\n            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n            mstore(0x60, 0)\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:\n     * the return value is optional (but if data is returned, it must not be false).\n     *\n     * @param token The token targeted by the call.\n     * @param spender The spender of the tokens\n     * @param value The amount of token to transfer\n     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.\n     */\n    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {\n        bytes4 selector = IERC20.approve.selector;\n\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            mstore(0x00, selector)\n            mstore(0x04, and(spender, shr(96, not(0))))\n            mstore(0x24, value)\n            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)\n            // if call success and return is true, all is good.\n            // otherwise (not success or return is not true), we need to perform further checks\n            if iszero(and(success, eq(mload(0x00), 1))) {\n                // if the call was a failure and bubble is enabled, bubble the error\n                if and(iszero(success), bubble) {\n                    returndatacopy(fmp, 0x00, returndatasize())\n                    revert(fmp, returndatasize())\n                }\n                // if the return value is not true, then the call is only successful if:\n                // - the token address has code\n                // - the returndata is empty\n                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))\n            }\n            mstore(0x40, fmp)\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/Address.sol":{"keccak256":"0x0fa9e0d3a859900b5a46f70a03c73adf259603d5e05027a37fe0b45529d85346","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\nimport {LowLevelCall} from \"./LowLevelCall.sol\";\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n    /**\n     * @dev There's no code at `target` (it is not a contract).\n     */\n    error AddressEmptyCode(address target);\n\n    /**\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n     * `recipient`, forwarding all available gas and reverting on errors.\n     *\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\n     * imposed by `transfer`, making them unable to receive funds via\n     * `transfer`. {sendValue} removes this limitation.\n     *\n     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n     *\n     * IMPORTANT: because control is transferred to `recipient`, care must be\n     * taken to not create reentrancy vulnerabilities. Consider using\n     * {ReentrancyGuard} or the\n     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n     */\n    function sendValue(address payable recipient, uint256 amount) internal {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n        if (LowLevelCall.callNoReturn(recipient, amount, \"\")) {\n            // call successful, nothing to do\n            return;\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Performs a Solidity function call using a low level `call`. A\n     * plain `call` is an unsafe replacement for a function call: use this\n     * function instead.\n     *\n     * If `target` reverts with a revert reason or custom error, it is bubbled\n     * up by this function (like regular Solidity function calls). However, if\n     * the call reverted with no returned reason, this function reverts with a\n     * {Errors.FailedCall} error.\n     *\n     * Returns the raw returned data. To convert to the expected return value,\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n     *\n     * Requirements:\n     *\n     * - `target` must be a contract.\n     * - calling `target` with `data` must not revert.\n     */\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n        return functionCallWithValue(target, data, 0);\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but also transferring `value` wei to `target`.\n     *\n     * Requirements:\n     *\n     * - the calling contract must have an ETH balance of at least `value`.\n     * - the called Solidity function must be `payable`.\n     */\n    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n        if (address(this).balance < value) {\n            revert Errors.InsufficientBalance(address(this).balance, value);\n        }\n        bool success = LowLevelCall.callNoReturn(target, value, data);\n        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {\n            return LowLevelCall.returnData();\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a static call.\n     */\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n        bool success = LowLevelCall.staticcallNoReturn(target, data);\n        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {\n            return LowLevelCall.returnData();\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n     * but performing a delegate call.\n     */\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n        bool success = LowLevelCall.delegatecallNoReturn(target, data);\n        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {\n            return LowLevelCall.returnData();\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (LowLevelCall.returnDataSize() > 0) {\n            LowLevelCall.bubbleRevert();\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target\n     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case\n     * of an unsuccessful call.\n     *\n     * NOTE: This function is DEPRECATED and may be removed in the next major release.\n     */\n    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        // only check if target is a contract if the call was successful and the return data is empty\n        // otherwise we already know that it was a contract\n        if (success && (returndata.length > 0 || target.code.length > 0)) {\n            return returndata;\n        } else if (success) {\n            revert AddressEmptyCode(target);\n        } else if (returndata.length > 0) {\n            LowLevelCall.bubbleRevert(returndata);\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n\n    /**\n     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the\n     * revert reason or with a default {Errors.FailedCall} error.\n     */\n    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {\n        if (success) {\n            return returndata;\n        } else if (returndata.length > 0) {\n            LowLevelCall.bubbleRevert(returndata);\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/Create2.sol":{"keccak256":"0xe06ddfff69f3ba154d92102d9a85db2780e045303a587360cf12195216e851ca","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/Create2.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.sol\";\nimport {LowLevelCall} from \"./LowLevelCall.sol\";\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n    /**\n     * @dev There's no code to deploy.\n     */\n    error Create2EmptyBytecode();\n\n    /**\n     * @dev Deploys a contract using `CREATE2`. The address where the contract\n     * will be deployed can be known in advance via {computeAddress}.\n     *\n     * The bytecode for a contract can be obtained from Solidity with\n     * `type(contractName).creationCode`.\n     *\n     * Requirements:\n     *\n     * - `bytecode` must not be empty.\n     * - `salt` must have not been used for `bytecode` already.\n     * - the factory must have a balance of at least `amount`.\n     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n     */\n    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {\n        if (address(this).balance < amount) {\n            revert Errors.InsufficientBalance(address(this).balance, amount);\n        }\n        if (bytecode.length == 0) {\n            revert Create2EmptyBytecode();\n        }\n        assembly (\"memory-safe\") {\n            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n        }\n        if (addr == address(0)) {\n            if (LowLevelCall.returnDataSize() == 0) {\n                revert Errors.FailedDeployment();\n            } else {\n                LowLevelCall.bubbleRevert();\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n     * `bytecodeHash` or `salt` will result in a new destination address.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n        return computeAddress(salt, bytecodeHash, address(this));\n    }\n\n    /**\n     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n     */\n    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40) // Get free memory pointer\n\n            // |                     | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |\n            // |---------------------|---------------------------------------------------------------------------|\n            // | bytecodeHash        |                                                        CCCCCCCCCCCCC...CC |\n            // | salt                |                                      BBBBBBBBBBBBB...BB                   |\n            // | deployer            | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |\n            // | 0xFF                |            FF                                                             |\n            // |---------------------|---------------------------------------------------------------------------|\n            // | memory              | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n            // | keccak(start, 0x55) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n            mstore(add(ptr, 0x40), bytecodeHash)\n            mstore(add(ptr, 0x20), salt)\n            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n            mstore8(start, 0xff)\n            addr := and(keccak256(start, 0x55), 0xffffffffffffffffffffffffffffffffffffffff)\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/Errors.sol":{"keccak256":"0x6afa713bfd42cf0f7656efa91201007ac465e42049d7de1d50753a373648c123","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Collection of common custom errors used in multiple contracts\n *\n * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.\n * It is recommended to avoid relying on the error API for critical functionality.\n *\n * _Available since v5.1._\n */\nlibrary Errors {\n    /**\n     * @dev The ETH balance of the account is not enough to perform the operation.\n     */\n    error InsufficientBalance(uint256 balance, uint256 needed);\n\n    /**\n     * @dev A call to an address target failed. The target may have reverted.\n     */\n    error FailedCall();\n\n    /**\n     * @dev The deployment failed.\n     */\n    error FailedDeployment();\n\n    /**\n     * @dev A necessary precompile is missing.\n     */\n    error MissingPrecompile(address);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/LowLevelCall.sol":{"keccak256":"0x6ba3db1346fc75a832aa6cd075e12f6f1fa172fa2122a020f324c319fe5be75e","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library of low level call functions that implement different calling strategies to deal with the return data.\n *\n * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended\n * to use the {Address} library instead.\n */\nlibrary LowLevelCall {\n    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.\n    function callNoReturn(address target, bytes memory data) internal returns (bool success) {\n        return callNoReturn(target, 0, data);\n    }\n\n    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.\n    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function callReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        return callReturn64Bytes(target, 0, data);\n    }\n\n    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.\n    function callReturn64Bytes(\n        address target,\n        uint256 value,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.\n    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function staticcallReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.\n    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {\n        assembly (\"memory-safe\") {\n            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)\n        }\n    }\n\n    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result\n    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.\n    ///\n    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated\n    /// and this function doesn't zero it out.\n    function delegatecallReturn64Bytes(\n        address target,\n        bytes memory data\n    ) internal returns (bool success, bytes32 result1, bytes32 result2) {\n        assembly (\"memory-safe\") {\n            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)\n            result1 := mload(0x00)\n            result2 := mload(0x20)\n        }\n    }\n\n    /// @dev Returns the size of the return data buffer.\n    function returnDataSize() internal pure returns (uint256 size) {\n        assembly (\"memory-safe\") {\n            size := returndatasize()\n        }\n    }\n\n    /// @dev Returns a buffer containing the return data from the last call.\n    function returnData() internal pure returns (bytes memory result) {\n        assembly (\"memory-safe\") {\n            result := mload(0x40)\n            mstore(result, returndatasize())\n            returndatacopy(add(result, 0x20), 0x00, returndatasize())\n            mstore(0x40, add(result, add(0x20, returndatasize())))\n        }\n    }\n\n    /// @dev Revert with the return data from the last call.\n    function bubbleRevert() internal pure {\n        assembly (\"memory-safe\") {\n            let fmp := mload(0x40)\n            returndatacopy(fmp, 0x00, returndatasize())\n            revert(fmp, returndatasize())\n        }\n    }\n\n    function bubbleRevert(bytes memory returndata) internal pure {\n        assembly (\"memory-safe\") {\n            revert(add(returndata, 0x20), mload(returndata))\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/Panic.sol":{"keccak256":"0xf7fe324703a64fc51702311dc51562d5cb1497734f074e4f483bfb6717572d7a","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Helper library for emitting standardized panic codes.\n *\n * ```solidity\n * contract Example {\n *      using Panic for uint256;\n *\n *      // Use any of the declared internal constants\n *      function foo() { Panic.GENERIC.panic(); }\n *\n *      // Alternatively\n *      function foo() { Panic.panic(Panic.GENERIC); }\n * }\n * ```\n *\n * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].\n *\n * _Available since v5.1._\n */\n// slither-disable-next-line unused-state\nlibrary Panic {\n    /// @dev generic / unspecified error\n    uint256 internal constant GENERIC = 0x00;\n    /// @dev used by the assert() builtin\n    uint256 internal constant ASSERT = 0x01;\n    /// @dev arithmetic underflow or overflow\n    uint256 internal constant UNDER_OVERFLOW = 0x11;\n    /// @dev division or modulo by zero\n    uint256 internal constant DIVISION_BY_ZERO = 0x12;\n    /// @dev enum conversion error\n    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;\n    /// @dev invalid encoding in storage\n    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;\n    /// @dev empty array pop\n    uint256 internal constant EMPTY_ARRAY_POP = 0x31;\n    /// @dev array out of bounds access\n    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;\n    /// @dev resource error (too large allocation or too large array)\n    uint256 internal constant RESOURCE_ERROR = 0x41;\n    /// @dev calling invalid internal function\n    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;\n\n    /// @dev Reverts with a panic code. Recommended to use with\n    /// the internal constants with predefined codes.\n    function panic(uint256 code) internal pure {\n        assembly (\"memory-safe\") {\n            mstore(0x00, 0x4e487b71)\n            mstore(0x20, code)\n            revert(0x1c, 0x24)\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/ReentrancyGuardTransient.sol":{"keccak256":"0x8b95459390767d84c984d18faee298ce913e69cf0be8d2fe7785e2ad487ffed8","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)\n\npragma solidity ^0.8.24;\n\nimport {TransientSlot} from \"./TransientSlot.sol\";\n\n/**\n * @dev Variant of {ReentrancyGuard} that uses transient storage.\n *\n * NOTE: This variant only works on networks where EIP-1153 is available.\n *\n * _Available since v5.1._\n *\n * @custom:stateless\n */\nabstract contract ReentrancyGuardTransient {\n    using TransientSlot for *;\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant REENTRANCY_GUARD_STORAGE =\n        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    /**\n     * @dev Prevents a contract from calling itself, directly or indirectly.\n     * Calling a `nonReentrant` function from another `nonReentrant`\n     * function is not supported. It is possible to prevent this from happening\n     * by making the `nonReentrant` function external, and making it call a\n     * `private` function that does the actual work.\n     */\n    modifier nonReentrant() {\n        _nonReentrantBefore();\n        _;\n        _nonReentrantAfter();\n    }\n\n    /**\n     * @dev A `view` only version of {nonReentrant}. Use to block view functions\n     * from being called, preventing reading from inconsistent contract state.\n     *\n     * CAUTION: This is a \"view\" modifier and does not change the reentrancy\n     * status. Use it only on view functions. For payable or non-payable functions,\n     * use the standard {nonReentrant} modifier instead.\n     */\n    modifier nonReentrantView() {\n        _nonReentrantBeforeView();\n        _;\n    }\n\n    function _nonReentrantBeforeView() private view {\n        if (_reentrancyGuardEntered()) {\n            revert ReentrancyGuardReentrantCall();\n        }\n    }\n\n    function _nonReentrantBefore() private {\n        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false\n        _nonReentrantBeforeView();\n\n        // Any calls to nonReentrant after this point will fail\n        _reentrancyGuardStorageSlot().asBoolean().tstore(true);\n    }\n\n    function _nonReentrantAfter() private {\n        _reentrancyGuardStorageSlot().asBoolean().tstore(false);\n    }\n\n    /**\n     * @dev Returns true if the reentrancy guard is currently set to \"entered\", which indicates there is a\n     * `nonReentrant` function in the call stack.\n     */\n    function _reentrancyGuardEntered() internal view returns (bool) {\n        return _reentrancyGuardStorageSlot().asBoolean().tload();\n    }\n\n    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {\n        return REENTRANCY_GUARD_STORAGE;\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/StorageSlot.sol":{"keccak256":"0xcf74f855663ce2ae00ed8352666b7935f6cddea2932fdf2c3ecd30a9b1cd0e97","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC-1967 implementation slot:\n * ```solidity\n * contract ERC1967 {\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n *     function _getImplementation() internal view returns (address) {\n *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n *     }\n *\n *     function _setImplementation(address newImplementation) internal {\n *         require(newImplementation.code.length > 0);\n *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary StorageSlot {\n    struct AddressSlot {\n        address value;\n    }\n\n    struct BooleanSlot {\n        bool value;\n    }\n\n    struct Bytes32Slot {\n        bytes32 value;\n    }\n\n    struct Uint256Slot {\n        uint256 value;\n    }\n\n    struct Int256Slot {\n        int256 value;\n    }\n\n    struct StringSlot {\n        string value;\n    }\n\n    struct BytesSlot {\n        bytes value;\n    }\n\n    /**\n     * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n     */\n    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.\n     */\n    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.\n     */\n    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.\n     */\n    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `Int256Slot` with member `value` located at `slot`.\n     */\n    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns a `StringSlot` with member `value` located at `slot`.\n     */\n    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.\n     */\n    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n\n    /**\n     * @dev Returns a `BytesSlot` with member `value` located at `slot`.\n     */\n    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := slot\n        }\n    }\n\n    /**\n     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.\n     */\n    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {\n        assembly (\"memory-safe\") {\n            r.slot := store.slot\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/TransientSlot.sol":{"keccak256":"0xac673fa1e374d9e6107504af363333e3e5f6344d2e83faf57d9bfd41d77cc946","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)\n// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.\n\npragma solidity ^0.8.24;\n\n/**\n * @dev Library for reading and writing value-types to specific transient storage slots.\n *\n * Transient slots are often used to store temporary values that are removed after the current transaction.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n *  * Example reading and writing values using transient storage:\n * ```solidity\n * contract Lock {\n *     using TransientSlot for *;\n *\n *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.\n *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;\n *\n *     modifier locked() {\n *         require(!_LOCK_SLOT.asBoolean().tload());\n *\n *         _LOCK_SLOT.asBoolean().tstore(true);\n *         _;\n *         _LOCK_SLOT.asBoolean().tstore(false);\n *     }\n * }\n * ```\n *\n * TIP: Consider using this library along with {SlotDerivation}.\n */\nlibrary TransientSlot {\n    /**\n     * @dev UDVT that represents a slot holding an address.\n     */\n    type AddressSlot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a AddressSlot.\n     */\n    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {\n        return AddressSlot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a bool.\n     */\n    type BooleanSlot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a BooleanSlot.\n     */\n    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {\n        return BooleanSlot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a bytes32.\n     */\n    type Bytes32Slot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a Bytes32Slot.\n     */\n    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {\n        return Bytes32Slot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a uint256.\n     */\n    type Uint256Slot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a Uint256Slot.\n     */\n    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {\n        return Uint256Slot.wrap(slot);\n    }\n\n    /**\n     * @dev UDVT that represents a slot holding a int256.\n     */\n    type Int256Slot is bytes32;\n\n    /**\n     * @dev Cast an arbitrary slot to a Int256Slot.\n     */\n    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {\n        return Int256Slot.wrap(slot);\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(AddressSlot slot) internal view returns (address value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(AddressSlot slot, address value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(BooleanSlot slot) internal view returns (bool value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(BooleanSlot slot, bool value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(Bytes32Slot slot, bytes32 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(Uint256Slot slot) internal view returns (uint256 value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(Uint256Slot slot, uint256 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n\n    /**\n     * @dev Load the value held at location `slot` in transient storage.\n     */\n    function tload(Int256Slot slot) internal view returns (int256 value) {\n        assembly (\"memory-safe\") {\n            value := tload(slot)\n        }\n    }\n\n    /**\n     * @dev Store `value` at location `slot` in transient storage.\n     */\n    function tstore(Int256Slot slot, int256 value) internal {\n        assembly (\"memory-safe\") {\n            tstore(slot, value)\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/introspection/IERC165.sol":{"keccak256":"0x8891738ffe910f0cf2da09566928589bf5d63f4524dd734fd9cedbac3274dd5c","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\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[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/math/Math.sol":{"keccak256":"0x59973a93b1f983f94e10529f46ca46544a9fec2b5f56fb1390bbe9e0dc79f857","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2²⁵⁶ + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.\n     *\n     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.\n     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * SafeCast.toUint(condition));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        unchecked {\n            // (a + b) / 2 can overflow.\n            return (a & b) + (a ^ b) / 2;\n        }\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds towards infinity instead\n     * of rounding towards zero.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        if (b == 0) {\n            // Guarantee the same behavior as in a regular Solidity division.\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n\n        // The following calculation ensures accurate ceiling division without overflow.\n        // Since a is non-zero, (a - 1) / b will not overflow.\n        // The largest possible result occurs when (a - 1) / b is type(uint256).max,\n        // but the largest value we can obtain is type(uint256).max - 1, which happens\n        // when a = type(uint256).max and b = 1.\n        unchecked {\n            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);\n        }\n    }\n\n    /**\n     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or\n     * denominator == 0.\n     *\n     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by\n     * Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory buffer) private pure returns (bool) {\n        uint256 chunk;\n        for (uint256 i = 0; i < buffer.length; i += 0x20) {\n            // See _unsafeReadBytesOffset from utils/Bytes.sol\n            assembly (\"memory-safe\") {\n                chunk := mload(add(add(buffer, 0x20), i))\n            }\n            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded\n     * towards zero.\n     *\n     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only\n     * using integer operations.\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        unchecked {\n            // Take care of easy edge cases when a == 0 or a == 1\n            if (a <= 1) {\n                return a;\n            }\n\n            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a\n            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between\n            // the current value as `ε_n = | x_n - sqrt(a) |`.\n            //\n            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root\n            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is\n            // bigger than any uint256.\n            //\n            // By noticing that\n            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`\n            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar\n            // to the msb function.\n            uint256 aa = a;\n            uint256 xn = 1;\n\n            if (aa >= (1 << 128)) {\n                aa >>= 128;\n                xn <<= 64;\n            }\n            if (aa >= (1 << 64)) {\n                aa >>= 64;\n                xn <<= 32;\n            }\n            if (aa >= (1 << 32)) {\n                aa >>= 32;\n                xn <<= 16;\n            }\n            if (aa >= (1 << 16)) {\n                aa >>= 16;\n                xn <<= 8;\n            }\n            if (aa >= (1 << 8)) {\n                aa >>= 8;\n                xn <<= 4;\n            }\n            if (aa >= (1 << 4)) {\n                aa >>= 4;\n                xn <<= 2;\n            }\n            if (aa >= (1 << 2)) {\n                xn <<= 1;\n            }\n\n            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).\n            //\n            // We can refine our estimation by noticing that the middle of that interval minimizes the error.\n            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).\n            // This is going to be our x_0 (and ε_0)\n            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)\n\n            // From here, Newton's method give us:\n            // x_{n+1} = (x_n + a / x_n) / 2\n            //\n            // One should note that:\n            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a\n            //              = ((x_n² + a) / (2 * x_n))² - a\n            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a\n            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)\n            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)\n            //              = (x_n² - a)² / (2 * x_n)²\n            //              = ((x_n² - a) / (2 * x_n))²\n            //              ≥ 0\n            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n\n            //\n            // This gives us the proof of quadratic convergence of the sequence:\n            // ε_{n+1} = | x_{n+1} - sqrt(a) |\n            //         = | (x_n + a / x_n) / 2 - sqrt(a) |\n            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |\n            //         = | (x_n - sqrt(a))² / (2 * x_n) |\n            //         = | ε_n² / (2 * x_n) |\n            //         = ε_n² / | (2 * x_n) |\n            //\n            // For the first iteration, we have a special case where x_0 is known:\n            // ε_1 = ε_0² / | (2 * x_0) |\n            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))\n            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))\n            //     ≤ 2**(e-3) / 3\n            //     ≤ 2**(e-3-log2(3))\n            //     ≤ 2**(e-4.5)\n            //\n            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:\n            // ε_{n+1} = ε_n² / | (2 * x_n) |\n            //         ≤ (2**(e-k))² / (2 * 2**(e-1))\n            //         ≤ 2**(2*e-2*k) / 2**e\n            //         ≤ 2**(e-2*k)\n            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above\n            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5\n            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9\n            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18\n            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36\n            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72\n\n            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision\n            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either\n            // sqrt(a) or sqrt(a) + 1.\n            return xn - SafeCast.toUint(xn > a / xn);\n        }\n    }\n\n    /**\n     * @dev Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n\n    /**\n     * @dev Counts the number of leading zero bits in a uint256.\n     */\n    function clz(uint256 x) internal pure returns (uint256) {\n        return ternary(x == 0, 256, 255 - log2(x));\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-5.6.1/utils/math/SafeCast.sol":{"keccak256":"0xc8cae21c9ae4a46e5162ff9bf5b351d6fa6a6eba72d515f3bc1bdfeda7fdf083","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeCast {\n    /**\n     * @dev Value doesn't fit in a uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in a uint of `bits` size.\n     */\n    error SafeCastOverflowedIntToUint(int256 value);\n\n    /**\n     * @dev Value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);\n\n    /**\n     * @dev A uint value doesn't fit in an int of `bits` size.\n     */\n    error SafeCastOverflowedUintToInt(uint256 value);\n\n    /**\n     * @dev Returns the downcasted uint248 from uint256, reverting on\n     * overflow (when the input is greater than largest uint248).\n     *\n     * Counterpart to Solidity's `uint248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toUint248(uint256 value) internal pure returns (uint248) {\n        if (value > type(uint248).max) {\n            revert SafeCastOverflowedUintDowncast(248, value);\n        }\n        return uint248(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint240 from uint256, reverting on\n     * overflow (when the input is greater than largest uint240).\n     *\n     * Counterpart to Solidity's `uint240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toUint240(uint256 value) internal pure returns (uint240) {\n        if (value > type(uint240).max) {\n            revert SafeCastOverflowedUintDowncast(240, value);\n        }\n        return uint240(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint232 from uint256, reverting on\n     * overflow (when the input is greater than largest uint232).\n     *\n     * Counterpart to Solidity's `uint232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toUint232(uint256 value) internal pure returns (uint232) {\n        if (value > type(uint232).max) {\n            revert SafeCastOverflowedUintDowncast(232, value);\n        }\n        return uint232(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint224 from uint256, reverting on\n     * overflow (when the input is greater than largest uint224).\n     *\n     * Counterpart to Solidity's `uint224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toUint224(uint256 value) internal pure returns (uint224) {\n        if (value > type(uint224).max) {\n            revert SafeCastOverflowedUintDowncast(224, value);\n        }\n        return uint224(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint216 from uint256, reverting on\n     * overflow (when the input is greater than largest uint216).\n     *\n     * Counterpart to Solidity's `uint216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toUint216(uint256 value) internal pure returns (uint216) {\n        if (value > type(uint216).max) {\n            revert SafeCastOverflowedUintDowncast(216, value);\n        }\n        return uint216(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint208 from uint256, reverting on\n     * overflow (when the input is greater than largest uint208).\n     *\n     * Counterpart to Solidity's `uint208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toUint208(uint256 value) internal pure returns (uint208) {\n        if (value > type(uint208).max) {\n            revert SafeCastOverflowedUintDowncast(208, value);\n        }\n        return uint208(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint200 from uint256, reverting on\n     * overflow (when the input is greater than largest uint200).\n     *\n     * Counterpart to Solidity's `uint200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toUint200(uint256 value) internal pure returns (uint200) {\n        if (value > type(uint200).max) {\n            revert SafeCastOverflowedUintDowncast(200, value);\n        }\n        return uint200(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint192 from uint256, reverting on\n     * overflow (when the input is greater than largest uint192).\n     *\n     * Counterpart to Solidity's `uint192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toUint192(uint256 value) internal pure returns (uint192) {\n        if (value > type(uint192).max) {\n            revert SafeCastOverflowedUintDowncast(192, value);\n        }\n        return uint192(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint184 from uint256, reverting on\n     * overflow (when the input is greater than largest uint184).\n     *\n     * Counterpart to Solidity's `uint184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toUint184(uint256 value) internal pure returns (uint184) {\n        if (value > type(uint184).max) {\n            revert SafeCastOverflowedUintDowncast(184, value);\n        }\n        return uint184(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint176 from uint256, reverting on\n     * overflow (when the input is greater than largest uint176).\n     *\n     * Counterpart to Solidity's `uint176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toUint176(uint256 value) internal pure returns (uint176) {\n        if (value > type(uint176).max) {\n            revert SafeCastOverflowedUintDowncast(176, value);\n        }\n        return uint176(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint168 from uint256, reverting on\n     * overflow (when the input is greater than largest uint168).\n     *\n     * Counterpart to Solidity's `uint168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toUint168(uint256 value) internal pure returns (uint168) {\n        if (value > type(uint168).max) {\n            revert SafeCastOverflowedUintDowncast(168, value);\n        }\n        return uint168(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint160 from uint256, reverting on\n     * overflow (when the input is greater than largest uint160).\n     *\n     * Counterpart to Solidity's `uint160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toUint160(uint256 value) internal pure returns (uint160) {\n        if (value > type(uint160).max) {\n            revert SafeCastOverflowedUintDowncast(160, value);\n        }\n        return uint160(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint152 from uint256, reverting on\n     * overflow (when the input is greater than largest uint152).\n     *\n     * Counterpart to Solidity's `uint152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toUint152(uint256 value) internal pure returns (uint152) {\n        if (value > type(uint152).max) {\n            revert SafeCastOverflowedUintDowncast(152, value);\n        }\n        return uint152(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint144 from uint256, reverting on\n     * overflow (when the input is greater than largest uint144).\n     *\n     * Counterpart to Solidity's `uint144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toUint144(uint256 value) internal pure returns (uint144) {\n        if (value > type(uint144).max) {\n            revert SafeCastOverflowedUintDowncast(144, value);\n        }\n        return uint144(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint136 from uint256, reverting on\n     * overflow (when the input is greater than largest uint136).\n     *\n     * Counterpart to Solidity's `uint136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toUint136(uint256 value) internal pure returns (uint136) {\n        if (value > type(uint136).max) {\n            revert SafeCastOverflowedUintDowncast(136, value);\n        }\n        return uint136(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint128 from uint256, reverting on\n     * overflow (when the input is greater than largest uint128).\n     *\n     * Counterpart to Solidity's `uint128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toUint128(uint256 value) internal pure returns (uint128) {\n        if (value > type(uint128).max) {\n            revert SafeCastOverflowedUintDowncast(128, value);\n        }\n        return uint128(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint120 from uint256, reverting on\n     * overflow (when the input is greater than largest uint120).\n     *\n     * Counterpart to Solidity's `uint120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toUint120(uint256 value) internal pure returns (uint120) {\n        if (value > type(uint120).max) {\n            revert SafeCastOverflowedUintDowncast(120, value);\n        }\n        return uint120(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint112 from uint256, reverting on\n     * overflow (when the input is greater than largest uint112).\n     *\n     * Counterpart to Solidity's `uint112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toUint112(uint256 value) internal pure returns (uint112) {\n        if (value > type(uint112).max) {\n            revert SafeCastOverflowedUintDowncast(112, value);\n        }\n        return uint112(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint104 from uint256, reverting on\n     * overflow (when the input is greater than largest uint104).\n     *\n     * Counterpart to Solidity's `uint104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toUint104(uint256 value) internal pure returns (uint104) {\n        if (value > type(uint104).max) {\n            revert SafeCastOverflowedUintDowncast(104, value);\n        }\n        return uint104(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint96 from uint256, reverting on\n     * overflow (when the input is greater than largest uint96).\n     *\n     * Counterpart to Solidity's `uint96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toUint96(uint256 value) internal pure returns (uint96) {\n        if (value > type(uint96).max) {\n            revert SafeCastOverflowedUintDowncast(96, value);\n        }\n        return uint96(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint88 from uint256, reverting on\n     * overflow (when the input is greater than largest uint88).\n     *\n     * Counterpart to Solidity's `uint88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toUint88(uint256 value) internal pure returns (uint88) {\n        if (value > type(uint88).max) {\n            revert SafeCastOverflowedUintDowncast(88, value);\n        }\n        return uint88(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint80 from uint256, reverting on\n     * overflow (when the input is greater than largest uint80).\n     *\n     * Counterpart to Solidity's `uint80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toUint80(uint256 value) internal pure returns (uint80) {\n        if (value > type(uint80).max) {\n            revert SafeCastOverflowedUintDowncast(80, value);\n        }\n        return uint80(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint72 from uint256, reverting on\n     * overflow (when the input is greater than largest uint72).\n     *\n     * Counterpart to Solidity's `uint72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toUint72(uint256 value) internal pure returns (uint72) {\n        if (value > type(uint72).max) {\n            revert SafeCastOverflowedUintDowncast(72, value);\n        }\n        return uint72(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint64 from uint256, reverting on\n     * overflow (when the input is greater than largest uint64).\n     *\n     * Counterpart to Solidity's `uint64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toUint64(uint256 value) internal pure returns (uint64) {\n        if (value > type(uint64).max) {\n            revert SafeCastOverflowedUintDowncast(64, value);\n        }\n        return uint64(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint56 from uint256, reverting on\n     * overflow (when the input is greater than largest uint56).\n     *\n     * Counterpart to Solidity's `uint56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toUint56(uint256 value) internal pure returns (uint56) {\n        if (value > type(uint56).max) {\n            revert SafeCastOverflowedUintDowncast(56, value);\n        }\n        return uint56(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint48 from uint256, reverting on\n     * overflow (when the input is greater than largest uint48).\n     *\n     * Counterpart to Solidity's `uint48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toUint48(uint256 value) internal pure returns (uint48) {\n        if (value > type(uint48).max) {\n            revert SafeCastOverflowedUintDowncast(48, value);\n        }\n        return uint48(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint40 from uint256, reverting on\n     * overflow (when the input is greater than largest uint40).\n     *\n     * Counterpart to Solidity's `uint40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toUint40(uint256 value) internal pure returns (uint40) {\n        if (value > type(uint40).max) {\n            revert SafeCastOverflowedUintDowncast(40, value);\n        }\n        return uint40(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint32 from uint256, reverting on\n     * overflow (when the input is greater than largest uint32).\n     *\n     * Counterpart to Solidity's `uint32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toUint32(uint256 value) internal pure returns (uint32) {\n        if (value > type(uint32).max) {\n            revert SafeCastOverflowedUintDowncast(32, value);\n        }\n        return uint32(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint24 from uint256, reverting on\n     * overflow (when the input is greater than largest uint24).\n     *\n     * Counterpart to Solidity's `uint24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toUint24(uint256 value) internal pure returns (uint24) {\n        if (value > type(uint24).max) {\n            revert SafeCastOverflowedUintDowncast(24, value);\n        }\n        return uint24(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint16 from uint256, reverting on\n     * overflow (when the input is greater than largest uint16).\n     *\n     * Counterpart to Solidity's `uint16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toUint16(uint256 value) internal pure returns (uint16) {\n        if (value > type(uint16).max) {\n            revert SafeCastOverflowedUintDowncast(16, value);\n        }\n        return uint16(value);\n    }\n\n    /**\n     * @dev Returns the downcasted uint8 from uint256, reverting on\n     * overflow (when the input is greater than largest uint8).\n     *\n     * Counterpart to Solidity's `uint8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toUint8(uint256 value) internal pure returns (uint8) {\n        if (value > type(uint8).max) {\n            revert SafeCastOverflowedUintDowncast(8, value);\n        }\n        return uint8(value);\n    }\n\n    /**\n     * @dev Converts a signed int256 into an unsigned uint256.\n     *\n     * Requirements:\n     *\n     * - input must be greater than or equal to 0.\n     */\n    function toUint256(int256 value) internal pure returns (uint256) {\n        if (value < 0) {\n            revert SafeCastOverflowedIntToUint(value);\n        }\n        return uint256(value);\n    }\n\n    /**\n     * @dev Returns the downcasted int248 from int256, reverting on\n     * overflow (when the input is less than smallest int248 or\n     * greater than largest int248).\n     *\n     * Counterpart to Solidity's `int248` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 248 bits\n     */\n    function toInt248(int256 value) internal pure returns (int248 downcasted) {\n        downcasted = int248(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(248, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int240 from int256, reverting on\n     * overflow (when the input is less than smallest int240 or\n     * greater than largest int240).\n     *\n     * Counterpart to Solidity's `int240` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 240 bits\n     */\n    function toInt240(int256 value) internal pure returns (int240 downcasted) {\n        downcasted = int240(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(240, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int232 from int256, reverting on\n     * overflow (when the input is less than smallest int232 or\n     * greater than largest int232).\n     *\n     * Counterpart to Solidity's `int232` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 232 bits\n     */\n    function toInt232(int256 value) internal pure returns (int232 downcasted) {\n        downcasted = int232(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(232, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int224 from int256, reverting on\n     * overflow (when the input is less than smallest int224 or\n     * greater than largest int224).\n     *\n     * Counterpart to Solidity's `int224` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 224 bits\n     */\n    function toInt224(int256 value) internal pure returns (int224 downcasted) {\n        downcasted = int224(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(224, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int216 from int256, reverting on\n     * overflow (when the input is less than smallest int216 or\n     * greater than largest int216).\n     *\n     * Counterpart to Solidity's `int216` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 216 bits\n     */\n    function toInt216(int256 value) internal pure returns (int216 downcasted) {\n        downcasted = int216(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(216, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int208 from int256, reverting on\n     * overflow (when the input is less than smallest int208 or\n     * greater than largest int208).\n     *\n     * Counterpart to Solidity's `int208` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 208 bits\n     */\n    function toInt208(int256 value) internal pure returns (int208 downcasted) {\n        downcasted = int208(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(208, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int200 from int256, reverting on\n     * overflow (when the input is less than smallest int200 or\n     * greater than largest int200).\n     *\n     * Counterpart to Solidity's `int200` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 200 bits\n     */\n    function toInt200(int256 value) internal pure returns (int200 downcasted) {\n        downcasted = int200(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(200, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int192 from int256, reverting on\n     * overflow (when the input is less than smallest int192 or\n     * greater than largest int192).\n     *\n     * Counterpart to Solidity's `int192` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 192 bits\n     */\n    function toInt192(int256 value) internal pure returns (int192 downcasted) {\n        downcasted = int192(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(192, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int184 from int256, reverting on\n     * overflow (when the input is less than smallest int184 or\n     * greater than largest int184).\n     *\n     * Counterpart to Solidity's `int184` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 184 bits\n     */\n    function toInt184(int256 value) internal pure returns (int184 downcasted) {\n        downcasted = int184(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(184, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int176 from int256, reverting on\n     * overflow (when the input is less than smallest int176 or\n     * greater than largest int176).\n     *\n     * Counterpart to Solidity's `int176` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 176 bits\n     */\n    function toInt176(int256 value) internal pure returns (int176 downcasted) {\n        downcasted = int176(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(176, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int168 from int256, reverting on\n     * overflow (when the input is less than smallest int168 or\n     * greater than largest int168).\n     *\n     * Counterpart to Solidity's `int168` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 168 bits\n     */\n    function toInt168(int256 value) internal pure returns (int168 downcasted) {\n        downcasted = int168(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(168, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int160 from int256, reverting on\n     * overflow (when the input is less than smallest int160 or\n     * greater than largest int160).\n     *\n     * Counterpart to Solidity's `int160` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 160 bits\n     */\n    function toInt160(int256 value) internal pure returns (int160 downcasted) {\n        downcasted = int160(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(160, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int152 from int256, reverting on\n     * overflow (when the input is less than smallest int152 or\n     * greater than largest int152).\n     *\n     * Counterpart to Solidity's `int152` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 152 bits\n     */\n    function toInt152(int256 value) internal pure returns (int152 downcasted) {\n        downcasted = int152(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(152, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int144 from int256, reverting on\n     * overflow (when the input is less than smallest int144 or\n     * greater than largest int144).\n     *\n     * Counterpart to Solidity's `int144` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 144 bits\n     */\n    function toInt144(int256 value) internal pure returns (int144 downcasted) {\n        downcasted = int144(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(144, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int136 from int256, reverting on\n     * overflow (when the input is less than smallest int136 or\n     * greater than largest int136).\n     *\n     * Counterpart to Solidity's `int136` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 136 bits\n     */\n    function toInt136(int256 value) internal pure returns (int136 downcasted) {\n        downcasted = int136(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(136, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int128 from int256, reverting on\n     * overflow (when the input is less than smallest int128 or\n     * greater than largest int128).\n     *\n     * Counterpart to Solidity's `int128` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 128 bits\n     */\n    function toInt128(int256 value) internal pure returns (int128 downcasted) {\n        downcasted = int128(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(128, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int120 from int256, reverting on\n     * overflow (when the input is less than smallest int120 or\n     * greater than largest int120).\n     *\n     * Counterpart to Solidity's `int120` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 120 bits\n     */\n    function toInt120(int256 value) internal pure returns (int120 downcasted) {\n        downcasted = int120(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(120, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int112 from int256, reverting on\n     * overflow (when the input is less than smallest int112 or\n     * greater than largest int112).\n     *\n     * Counterpart to Solidity's `int112` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 112 bits\n     */\n    function toInt112(int256 value) internal pure returns (int112 downcasted) {\n        downcasted = int112(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(112, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int104 from int256, reverting on\n     * overflow (when the input is less than smallest int104 or\n     * greater than largest int104).\n     *\n     * Counterpart to Solidity's `int104` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 104 bits\n     */\n    function toInt104(int256 value) internal pure returns (int104 downcasted) {\n        downcasted = int104(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(104, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int96 from int256, reverting on\n     * overflow (when the input is less than smallest int96 or\n     * greater than largest int96).\n     *\n     * Counterpart to Solidity's `int96` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 96 bits\n     */\n    function toInt96(int256 value) internal pure returns (int96 downcasted) {\n        downcasted = int96(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(96, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int88 from int256, reverting on\n     * overflow (when the input is less than smallest int88 or\n     * greater than largest int88).\n     *\n     * Counterpart to Solidity's `int88` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 88 bits\n     */\n    function toInt88(int256 value) internal pure returns (int88 downcasted) {\n        downcasted = int88(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(88, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int80 from int256, reverting on\n     * overflow (when the input is less than smallest int80 or\n     * greater than largest int80).\n     *\n     * Counterpart to Solidity's `int80` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 80 bits\n     */\n    function toInt80(int256 value) internal pure returns (int80 downcasted) {\n        downcasted = int80(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(80, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int72 from int256, reverting on\n     * overflow (when the input is less than smallest int72 or\n     * greater than largest int72).\n     *\n     * Counterpart to Solidity's `int72` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 72 bits\n     */\n    function toInt72(int256 value) internal pure returns (int72 downcasted) {\n        downcasted = int72(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(72, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int64 from int256, reverting on\n     * overflow (when the input is less than smallest int64 or\n     * greater than largest int64).\n     *\n     * Counterpart to Solidity's `int64` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 64 bits\n     */\n    function toInt64(int256 value) internal pure returns (int64 downcasted) {\n        downcasted = int64(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(64, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int56 from int256, reverting on\n     * overflow (when the input is less than smallest int56 or\n     * greater than largest int56).\n     *\n     * Counterpart to Solidity's `int56` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 56 bits\n     */\n    function toInt56(int256 value) internal pure returns (int56 downcasted) {\n        downcasted = int56(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(56, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int48 from int256, reverting on\n     * overflow (when the input is less than smallest int48 or\n     * greater than largest int48).\n     *\n     * Counterpart to Solidity's `int48` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 48 bits\n     */\n    function toInt48(int256 value) internal pure returns (int48 downcasted) {\n        downcasted = int48(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(48, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int40 from int256, reverting on\n     * overflow (when the input is less than smallest int40 or\n     * greater than largest int40).\n     *\n     * Counterpart to Solidity's `int40` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 40 bits\n     */\n    function toInt40(int256 value) internal pure returns (int40 downcasted) {\n        downcasted = int40(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(40, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int32 from int256, reverting on\n     * overflow (when the input is less than smallest int32 or\n     * greater than largest int32).\n     *\n     * Counterpart to Solidity's `int32` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 32 bits\n     */\n    function toInt32(int256 value) internal pure returns (int32 downcasted) {\n        downcasted = int32(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(32, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int24 from int256, reverting on\n     * overflow (when the input is less than smallest int24 or\n     * greater than largest int24).\n     *\n     * Counterpart to Solidity's `int24` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 24 bits\n     */\n    function toInt24(int256 value) internal pure returns (int24 downcasted) {\n        downcasted = int24(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(24, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int16 from int256, reverting on\n     * overflow (when the input is less than smallest int16 or\n     * greater than largest int16).\n     *\n     * Counterpart to Solidity's `int16` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 16 bits\n     */\n    function toInt16(int256 value) internal pure returns (int16 downcasted) {\n        downcasted = int16(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(16, value);\n        }\n    }\n\n    /**\n     * @dev Returns the downcasted int8 from int256, reverting on\n     * overflow (when the input is less than smallest int8 or\n     * greater than largest int8).\n     *\n     * Counterpart to Solidity's `int8` operator.\n     *\n     * Requirements:\n     *\n     * - input must fit into 8 bits\n     */\n    function toInt8(int256 value) internal pure returns (int8 downcasted) {\n        downcasted = int8(value);\n        if (downcasted != value) {\n            revert SafeCastOverflowedIntDowncast(8, value);\n        }\n    }\n\n    /**\n     * @dev Converts an unsigned uint256 into a signed int256.\n     *\n     * Requirements:\n     *\n     * - input must be less than or equal to maxInt256.\n     */\n    function toInt256(uint256 value) internal pure returns (int256) {\n        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n        if (value > uint256(type(int256).max)) {\n            revert SafeCastOverflowedUintToInt(value);\n        }\n        return int256(value);\n    }\n\n    /**\n     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.\n     */\n    function toUint(bool b) internal pure returns (uint256 u) {\n        assembly (\"memory-safe\") {\n            u := iszero(iszero(b))\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/access/AccessControlUpgradeable.sol":{"keccak256":"0xe3a2cff969716ebedd6f9fc7f4cbc499449e9bd0377afa49dab9e9c21212a50e","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.6.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.20;\n\nimport {IAccessControl} from \"@openzeppelin/contracts/access/IAccessControl.sol\";\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {ERC165Upgradeable} from \"../utils/introspection/ERC165Upgradeable.sol\";\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```solidity\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```solidity\n * function foo() public {\n *     require(hasRole(MY_ROLE, msg.sender));\n *     ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}\n * to enforce additional security measures for this role.\n */\nabstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {\n    struct RoleData {\n        mapping(address account => bool) hasRole;\n        bytes32 adminRole;\n    }\n\n    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl\n    struct AccessControlStorage {\n        mapping(bytes32 role => RoleData) _roles;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.AccessControl\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;\n\n    function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {\n        assembly {\n            $.slot := AccessControlStorageLocation\n        }\n    }\n\n    /**\n     * @dev Modifier that checks that an account has a specific role. Reverts\n     * with an {AccessControlUnauthorizedAccount} error including the required role.\n     */\n    modifier onlyRole(bytes32 role) {\n        _checkRole(role);\n        _;\n    }\n\n    function __AccessControl_init() internal onlyInitializing {\n    }\n\n    function __AccessControl_init_unchained() internal onlyInitializing {\n    }\n    /// @inheritdoc ERC165Upgradeable\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /**\n     * @dev Returns `true` if `account` has been granted `role`.\n     */\n    function hasRole(bytes32 role, address account) public view virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].hasRole[account];\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`\n     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.\n     */\n    function _checkRole(bytes32 role) internal view virtual {\n        _checkRole(role, _msgSender());\n    }\n\n    /**\n     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`\n     * is missing `role`.\n     */\n    function _checkRole(bytes32 role, address account) internal view virtual {\n        if (!hasRole(role, account)) {\n            revert AccessControlUnauthorizedAccount(account, role);\n        }\n    }\n\n    /**\n     * @dev Returns the admin role that controls `role`. See {grantRole} and\n     * {revokeRole}.\n     *\n     * To change a role's admin, use {_setRoleAdmin}.\n     */\n    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        return $._roles[role].adminRole;\n    }\n\n    /**\n     * @dev Grants `role` to `account`.\n     *\n     * If `account` had not been already granted `role`, emits a {RoleGranted}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _grantRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from `account`.\n     *\n     * If `account` had been granted `role`, emits a {RoleRevoked} event.\n     *\n     * Requirements:\n     *\n     * - the caller must have ``role``'s admin role.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {\n        _revokeRole(role, account);\n    }\n\n    /**\n     * @dev Revokes `role` from the calling account.\n     *\n     * Roles are often managed via {grantRole} and {revokeRole}: this function's\n     * purpose is to provide a mechanism for accounts to lose their privileges\n     * if they are compromised (such as when a trusted device is misplaced).\n     *\n     * If the calling account had been revoked `role`, emits a {RoleRevoked}\n     * event.\n     *\n     * Requirements:\n     *\n     * - the caller must be `callerConfirmation`.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function renounceRole(bytes32 role, address callerConfirmation) public virtual {\n        if (callerConfirmation != _msgSender()) {\n            revert AccessControlBadConfirmation();\n        }\n\n        _revokeRole(role, callerConfirmation);\n    }\n\n    /**\n     * @dev Sets `adminRole` as ``role``'s admin role.\n     *\n     * Emits a {RoleAdminChanged} event.\n     */\n    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        bytes32 previousAdminRole = getRoleAdmin(role);\n        $._roles[role].adminRole = adminRole;\n        emit RoleAdminChanged(role, previousAdminRole, adminRole);\n    }\n\n    /**\n     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleGranted} event.\n     */\n    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (!hasRole(role, account)) {\n            $._roles[role].hasRole[account] = true;\n            emit RoleGranted(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.\n     *\n     * Internal function without access restriction.\n     *\n     * May emit a {RoleRevoked} event.\n     */\n    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {\n        AccessControlStorage storage $ = _getAccessControlStorage();\n        if (hasRole(role, account)) {\n            $._roles[role].hasRole[account] = false;\n            emit RoleRevoked(role, account, _msgSender());\n            return true;\n        } else {\n            return false;\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/proxy/utils/Initializable.sol":{"keccak256":"0x30d125b8417684dbfea3e8d57284b353a86b22077237b4aaf098c0b54b153e16","license":"MIT","content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n"},"amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/proxy/utils/UUPSUpgradeable.sol":{"keccak256":"0x4918e374e9ce84e9b196486bafbd46851d5e72ab315e31f0b1d7c443dcfea5bf","license":"MIT","content":"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.22;\n\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol\";\n"},"amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/token/ERC20/ERC20Upgradeable.sol":{"keccak256":"0xd518def45c722a6e803e1e26e625db25e01497f672ca566cca585d234ec903b0","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.5.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {ContextUpgradeable} from \"../../utils/ContextUpgradeable.sol\";\nimport {IERC20Errors} from \"@openzeppelin/contracts/interfaces/draft-IERC6093.sol\";\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * The default value of {decimals} is 18. To change this, you should override\n * this function so it returns a different value.\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC-20\n * applications.\n */\nabstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {\n    /// @custom:storage-location erc7201:openzeppelin.storage.ERC20\n    struct ERC20Storage {\n        mapping(address account => uint256) _balances;\n\n        mapping(address account => mapping(address spender => uint256)) _allowances;\n\n        uint256 _totalSupply;\n\n        string _name;\n        string _symbol;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ERC20\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;\n\n    function _getERC20Storage() private pure returns (ERC20Storage storage $) {\n        assembly {\n            $.slot := ERC20StorageLocation\n        }\n    }\n\n    /**\n     * @dev Sets the values for {name} and {symbol}.\n     *\n     * Both values are immutable: they can only be set once during construction.\n     */\n    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n        __ERC20_init_unchained(name_, symbol_);\n    }\n\n    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n        ERC20Storage storage $ = _getERC20Storage();\n        $._name = name_;\n        $._symbol = symbol_;\n    }\n\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() public view virtual returns (string memory) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev Returns the symbol of the token, usually a shorter version of the\n     * name.\n     */\n    function symbol() public view virtual returns (string memory) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._symbol;\n    }\n\n    /**\n     * @dev Returns the number of decimals used to get its user representation.\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n     *\n     * Tokens usually opt for a value of 18, imitating the relationship between\n     * Ether and Wei. This is the default value returned by this function, unless\n     * it's overridden.\n     *\n     * NOTE: This information is only used for _display_ purposes: it in\n     * no way affects any of the arithmetic of the contract, including\n     * {IERC20-balanceOf} and {IERC20-transfer}.\n     */\n    function decimals() public view virtual returns (uint8) {\n        return 18;\n    }\n\n    /// @inheritdoc IERC20\n    function totalSupply() public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._totalSupply;\n    }\n\n    /// @inheritdoc IERC20\n    function balanceOf(address account) public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._balances[account];\n    }\n\n    /**\n     * @dev See {IERC20-transfer}.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - the caller must have a balance of at least `value`.\n     */\n    function transfer(address to, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _transfer(owner, to, value);\n        return true;\n    }\n\n    /// @inheritdoc IERC20\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._allowances[owner][spender];\n    }\n\n    /**\n     * @dev See {IERC20-approve}.\n     *\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     */\n    function approve(address spender, uint256 value) public virtual returns (bool) {\n        address owner = _msgSender();\n        _approve(owner, spender, value);\n        return true;\n    }\n\n    /**\n     * @dev See {IERC20-transferFrom}.\n     *\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\n     *\n     * NOTE: Does not update the allowance if the current allowance\n     * is the maximum `uint256`.\n     *\n     * Requirements:\n     *\n     * - `from` and `to` cannot be the zero address.\n     * - `from` must have a balance of at least `value`.\n     * - the caller must have allowance for ``from``'s tokens of at least\n     * `value`.\n     */\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\n        address spender = _msgSender();\n        _spendAllowance(from, spender, value);\n        _transfer(from, to, value);\n        return true;\n    }\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\n     *\n     * This internal function is equivalent to {transfer}, and can be used to\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _transfer(address from, address to, uint256 value) internal {\n        if (from == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        if (to == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(from, to, value);\n    }\n\n    /**\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\n     * this function.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _update(address from, address to, uint256 value) internal virtual {\n        ERC20Storage storage $ = _getERC20Storage();\n        if (from == address(0)) {\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\n            $._totalSupply += value;\n        } else {\n            uint256 fromBalance = $._balances[from];\n            if (fromBalance < value) {\n                revert ERC20InsufficientBalance(from, fromBalance, value);\n            }\n            unchecked {\n                // Overflow not possible: value <= fromBalance <= totalSupply.\n                $._balances[from] = fromBalance - value;\n            }\n        }\n\n        if (to == address(0)) {\n            unchecked {\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\n                $._totalSupply -= value;\n            }\n        } else {\n            unchecked {\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\n                $._balances[to] += value;\n            }\n        }\n\n        emit Transfer(from, to, value);\n    }\n\n    /**\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\n     * Relies on the `_update` mechanism\n     *\n     * Emits a {Transfer} event with `from` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\n     */\n    function _mint(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidReceiver(address(0));\n        }\n        _update(address(0), account, value);\n    }\n\n    /**\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\n     * Relies on the `_update` mechanism.\n     *\n     * Emits a {Transfer} event with `to` set to the zero address.\n     *\n     * NOTE: This function is not virtual, {_update} should be overridden instead\n     */\n    function _burn(address account, uint256 value) internal {\n        if (account == address(0)) {\n            revert ERC20InvalidSender(address(0));\n        }\n        _update(account, address(0), value);\n    }\n\n    /**\n     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.\n     *\n     * This internal function is equivalent to `approve`, and can be used to\n     * e.g. set automatic allowances for certain subsystems, etc.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `owner` cannot be the zero address.\n     * - `spender` cannot be the zero address.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address owner, address spender, uint256 value) internal {\n        _approve(owner, spender, value, true);\n    }\n\n    /**\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\n     *\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\n     * `_spendAllowance` during the `transferFrom` operation sets the flag to false. This saves gas by not emitting any\n     * `Approval` event during `transferFrom` operations.\n     *\n     * Anyone who wishes to continue emitting `Approval` events on the `transferFrom` operation can force the flag to\n     * true using the following override:\n     *\n     * ```solidity\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\n     *     super._approve(owner, spender, value, true);\n     * }\n     * ```\n     *\n     * Requirements are the same as {_approve}.\n     */\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\n        ERC20Storage storage $ = _getERC20Storage();\n        if (owner == address(0)) {\n            revert ERC20InvalidApprover(address(0));\n        }\n        if (spender == address(0)) {\n            revert ERC20InvalidSpender(address(0));\n        }\n        $._allowances[owner][spender] = value;\n        if (emitEvent) {\n            emit Approval(owner, spender, value);\n        }\n    }\n\n    /**\n     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.\n     *\n     * Does not update the allowance value in case of infinite allowance.\n     * Revert if not enough allowance is available.\n     *\n     * Does not emit an {Approval} event.\n     */\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\n        uint256 currentAllowance = allowance(owner, spender);\n        if (currentAllowance < type(uint256).max) {\n            if (currentAllowance < value) {\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\n            }\n            unchecked {\n                _approve(owner, spender, currentAllowance - value, false);\n            }\n        }\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/utils/ContextUpgradeable.sol":{"keccak256":"0xad316bdc3ee64a0e29773256245045dc57b92660799ff14f668f7c0da9456a9d","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n    function __Context_init() internal onlyInitializing {\n    }\n\n    function __Context_init_unchained() internal onlyInitializing {\n    }\n    function _msgSender() internal view virtual returns (address) {\n        return msg.sender;\n    }\n\n    function _msgData() internal view virtual returns (bytes calldata) {\n        return msg.data;\n    }\n\n    function _contextSuffixLength() internal view virtual returns (uint256) {\n        return 0;\n    }\n}\n"},"amish-contracts/dependencies/@openzeppelin-contracts-upgradeable-5.6.1/utils/introspection/ERC165Upgradeable.sol":{"keccak256":"0x16b88aca1f1c3aa38783416d86207ce6fe574fcd1993dfe54403b5c8b6c74224","license":"MIT","content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"@openzeppelin/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165 {\n    function __ERC165_init() internal onlyInitializing {\n    }\n\n    function __ERC165_init_unchained() internal onlyInitializing {\n    }\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"amish-contracts/src/APNImplementation.sol":{"keccak256":"0x6c9707e946debb4557b362c1f540f2d3f1bc51c11f0cdcbdb93f0989603b5121","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {ERC20Upgradeable} from \"@openzeppelin-contracts-upgradeable-5.6.1/token/ERC20/ERC20Upgradeable.sol\";\nimport {ReentrancyGuardTransient} from \"@openzeppelin-contracts-5.6.1/utils/ReentrancyGuardTransient.sol\";\nimport {IERC20} from \"@openzeppelin-contracts-5.6.1/token/ERC20/IERC20.sol\";\nimport {SafeERC20} from \"@openzeppelin-contracts-5.6.1/token/ERC20/utils/SafeERC20.sol\";\nimport {Math} from \"@openzeppelin-contracts-5.6.1/utils/math/Math.sol\";\n\nimport {IAPN} from \"./interfaces/IAPN.sol\";\nimport {ILoanManager} from \"./interfaces/ILoanManager.sol\";\n\n/// @title APNImplementation\n/// @notice Amish Position Note (APN) — the ERC-20 a lender receives for a loan.\n///         Deployed once as a template and cloned per loan via EIP-1167 by the LoanManager, so it\n///         is initializer-based rather than constructor-based. Total supply equals the loan\n///         principal and is minted to the lender at creation.\n/// @dev Redemption is **ERC-4626-style** against a mark-to-market NAV, not a par bearer claim:\n///        NAV = (outstanding principal + lender's accrued-but-unpaid interest)   [illiquid claim,\n///               read live from the LoanManager]\n///            + principal-token cash already repaid into this note               [liquid part]\n///      `sharePrice = NAV / totalSupply`. Redeeming burns the presented shares and pays\n///      `shares · sharePrice`, but only up to the cash on hand ({maxRedeem}); the illiquid part of\n///      NAV raises the price without being directly withdrawable. Because redemption is value-neutral\n///      (it removes proportional value and shares together) the price is invariant under redemption,\n///      and interest accrual raises it over the *current* supply — so a holder who exits early forgoes\n///      the later appreciation, and whoever remains earns proportionally more. No per-holder accounting\n///      and no transfer hooks are needed: a changing supply is handled by the share price itself.\n///      There is no separate non-burning \"interest claim\", which is what made an earlier design\n///      drainable across repeated calls. Repaid funds live in this note (the LoanManager transfers them\n///      here); redemption pays out of this note's own balance.\ncontract APNImplementation is IAPN, ERC20Upgradeable, ReentrancyGuardTransient {\n    using SafeERC20 for IERC20;\n\n    /// @notice The LoanManager that created this note (the caller that initialized the clone);\n    ///         also the source of the loan's live outstanding + accrued-interest claim.\n    address public loanManager;\n\n    /// @notice The loan this note represents.\n    bytes32 public matchId;\n\n    /// @notice The loan's principal token (the asset repayments/redemptions are denominated in).\n    address public principalToken;\n\n    /// @notice When false, the note is soulbound to the original lender (regulatory mode).\n    bool public transferable;\n\n    uint8 private _decimalsValue;\n\n    event Redeemed(address indexed holder, uint256 shares, uint256 assets);\n\n    error APNImplementation_NonTransferable();\n    error APNImplementation_NothingToRedeem();\n    error APNImplementation_InsufficientCash(uint256 requested, uint256 available);\n\n    constructor() {\n        // Lock the template so it can never be initialized directly; only clones are usable.\n        _disableInitializers();\n    }\n\n    /// @notice Initialize a freshly deployed clone. Callable exactly once (per clone). The\n    ///         initializing caller (`msg.sender`, i.e. the LoanManager) becomes `loanManager`.\n    /// @param matchId_ Loan identifier.\n    /// @param principalToken_ Loan principal token.\n    /// @param lender Recipient of the full initial supply.\n    /// @param principalAmount Loan principal, in principal-token base units; the minted supply.\n    /// @param transferable_ False = soulbound to `lender`.\n    /// @param decimals_ Token decimals (mirrors the principal token for 1:1 readability).\n    /// @param name_ ERC-20 name.\n    /// @param symbol_ ERC-20 symbol.\n    function initialize(\n        bytes32 matchId_,\n        address principalToken_,\n        address lender,\n        uint256 principalAmount,\n        bool transferable_,\n        uint8 decimals_,\n        string calldata name_,\n        string calldata symbol_\n    ) external initializer {\n        __ERC20_init(name_, symbol_);\n        loanManager = msg.sender;\n        matchId = matchId_;\n        principalToken = principalToken_;\n        transferable = transferable_;\n        _decimalsValue = decimals_;\n        _mint(lender, principalAmount);\n    }\n\n    /// @inheritdoc IAPN\n    function totalAssets() public view returns (uint256) {\n        return ILoanManager(loanManager).unrealizedValue(matchId) + _cash();\n    }\n\n    /// @inheritdoc IAPN\n    /// @dev Applies the share price (`totalAssets / totalSupply`): shares → assets.\n    function convertToAssets(uint256 shares) public view returns (uint256) {\n        uint256 supply = totalSupply();\n        if (supply == 0) return 0;\n        return Math.mulDiv(shares, totalAssets(), supply, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IAPN\n    /// @dev The inverse of {convertToAssets} at the same price: assets → shares. Floors, so the\n    ///      returned share count's value never rounds above `assets`.\n    function convertToShares(uint256 assets) public view returns (uint256) {\n        uint256 nav = totalAssets();\n        if (nav == 0) return 0;\n        return Math.mulDiv(assets, totalSupply(), nav, Math.Rounding.Floor);\n    }\n\n    /// @inheritdoc IAPN\n    function maxRedeem(address owner) public view returns (uint256) {\n        // The lesser of what the holder owns and what the cash on hand can buy back at the current\n        // price (redemption is cash-capped). `convertToShares(cash)` is cash / sharePrice.\n        uint256 cashShares = convertToShares(_cash());\n        uint256 bal = balanceOf(owner);\n        return bal < cashShares ? bal : cashShares;\n    }\n\n    /// @inheritdoc IAPN\n    function redeem(uint256 shares) external nonReentrant returns (uint256 assets) {\n        return _redeem(shares);\n    }\n\n    /// @inheritdoc IAPN\n    function redeemMax() external nonReentrant returns (uint256 assets) {\n        return _redeem(maxRedeem(msg.sender));\n    }\n\n    /// @inheritdoc ERC20Upgradeable\n    function decimals() public view override returns (uint8) {\n        return _decimalsValue;\n    }\n\n    /// @dev Burn `shares` at the current share price and pay the proportional assets, capped by the\n    ///      cash on hand. Effects (burn) precede the transfer; `nonReentrant` guards the entry points.\n    function _redeem(uint256 shares) private returns (uint256 assets) {\n        if (shares == 0) revert APNImplementation_NothingToRedeem();\n        assets = convertToAssets(shares); // shares -> assets at the current price (0 if supply is 0)\n        // Never burn shares for nothing. `assets` can floor to zero once the share price drops below\n        // one (a loss/write-down leaves NAV < supply) or for sub-price-unit dust; reject rather than\n        // let the caller destroy notes for a zero payout.\n        if (assets == 0) revert APNImplementation_NothingToRedeem();\n        uint256 cash = _cash();\n        if (assets > cash) revert APNImplementation_InsufficientCash(assets, cash);\n\n        _burn(msg.sender, shares); // reverts if the caller lacks the shares\n        emit Redeemed(msg.sender, shares, assets);\n        IERC20(principalToken).safeTransfer(msg.sender, assets);\n    }\n\n    /// @dev The liquid part of NAV: principal-token repaid into this note and not yet redeemed.\n    function _cash() private view returns (uint256) {\n        return IERC20(principalToken).balanceOf(address(this));\n    }\n\n    /// @dev Enforces the soulbound rule: mints (from == 0) and burns (to == 0) are always\n    ///      allowed; holder-to-holder transfers are blocked when the note is non-transferable.\n    function _update(address from, address to, uint256 value) internal override {\n        if (!transferable && from != address(0) && to != address(0)) {\n            revert APNImplementation_NonTransferable();\n        }\n        super._update(from, to, value);\n    }\n}\n"},"amish-contracts/src/LoanManager.sol":{"keccak256":"0x513503f5175d4731ee088130d3e1a3ad2fcdbf262e207b917d0912f7aff68819","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {Initializable} from \"@openzeppelin-contracts-upgradeable-5.6.1/proxy/utils/Initializable.sol\";\nimport {AccessControlUpgradeable} from \"@openzeppelin-contracts-upgradeable-5.6.1/access/AccessControlUpgradeable.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin-contracts-upgradeable-5.6.1/proxy/utils/UUPSUpgradeable.sol\";\nimport {ReentrancyGuardTransient} from \"@openzeppelin-contracts-5.6.1/utils/ReentrancyGuardTransient.sol\";\nimport {IERC20} from \"@openzeppelin-contracts-5.6.1/token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"@openzeppelin-contracts-5.6.1/token/ERC20/extensions/IERC20Metadata.sol\";\nimport {SafeERC20} from \"@openzeppelin-contracts-5.6.1/token/ERC20/utils/SafeERC20.sol\";\nimport {Clones} from \"@openzeppelin-contracts-5.6.1/proxy/Clones.sol\";\nimport {Math} from \"@openzeppelin-contracts-5.6.1/utils/math/Math.sol\";\n\nimport {ILoanManager} from \"./interfaces/ILoanManager.sol\";\nimport {IFeeRegistry} from \"./interfaces/IFeeRegistry.sol\";\nimport {ICollateralManager} from \"./interfaces/ICollateralManager.sol\";\nimport {APNImplementation} from \"./APNImplementation.sol\";\nimport {ExecutedTerms} from \"./types/DataTypes.sol\";\nimport {Constants} from \"./libraries/Constants.sol\";\nimport {InterestMath} from \"./libraries/InterestMath.sol\";\nimport {LtvMath} from \"./libraries/LtvMath.sol\";\nimport {OracleLib} from \"./libraries/OracleLib.sol\";\nimport {AuctionMath} from \"./libraries/AuctionMath.sol\";\nimport {Roles} from \"./libraries/Roles.sol\";\n\n/// @title LoanManager\n/// @notice Singleton that manages all loans on the principal chain. On execution it moves the\n///         principal from the lender to the borrower (net of the origination fee, which goes to the\n///         treasury), records the loan with its collateral parameters denormalized, snapshots the\n///         interest take rate, and mints the lender an APN.\n/// @dev UUPS-upgradeable; upgrades are gated by `UPGRADER_ROLE` (a Timelock in production). The Hub\n///      is wired once via {setHub}; the FeeRegistry and APN template are fixed at initialization and\n///      can only change through an upgrade. Storage uses ERC-7201.\ncontract LoanManager is\n    ILoanManager,\n    Initializable,\n    AccessControlUpgradeable,\n    UUPSUpgradeable,\n    ReentrancyGuardTransient\n{\n    using SafeERC20 for IERC20;\n    using Clones for address;\n\n    /// @custom:storage-location erc7201:amish.storage.LoanManager\n    struct LoanManagerStorage {\n        mapping(bytes32 matchId => Loan) loans;\n        address hub;\n        address feeRegistry;\n        address apnImplementation;\n        address collateralManager;\n        // Liquidation state, declared last so the preceding layout is never shifted across upgrades.\n        mapping(bytes32 matchId => Auction) auctions;\n        RiskParams risk;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"amish.storage.LoanManager\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant STORAGE_LOCATION = 0x176143601c23619fa9e6d00dff558ebd44b17fb15cc48c460fe77cd55f46ee00;\n\n    // --- Risk-parameter bounds (govern how far the admin can tune the auction) ---\n    // The floors on durations stop the admin from collapsing the grace/auction to zero (which would\n    // make a position instantly seizable at max bonus); the caps keep the levers in a sane range.\n    uint32 internal constant MIN_AUCTION_DURATION = 5 minutes;\n    uint32 internal constant MAX_AUCTION_DURATION = 7 days;\n    uint32 internal constant MIN_GRACE_PERIOD = 1 hours;\n    uint32 internal constant MAX_GRACE_PERIOD = 30 days;\n    uint16 internal constant MAX_B_MIN = 500; // 5%\n    uint16 internal constant MIN_HF_FLOOR = 5_000; // 0.50\n    uint16 internal constant MAX_HF_FLOOR = 9_900; // 0.99 (< BPS so Zone-3 distress never divides by zero)\n    uint16 internal constant MAX_RESTORE_BUFFER = 2_000; // 20%\n\n    event LoanCreated(\n        bytes32 indexed matchId,\n        address indexed borrower,\n        address indexed lender,\n        address apn,\n        address principalToken,\n        uint256 principalAmount,\n        uint256 originationFee\n    );\n    event LoanRepaid(\n        bytes32 indexed matchId,\n        address indexed payer,\n        uint256 interestPortion,\n        uint256 protocolFee,\n        uint256 principalPortion,\n        uint256 outstandingPrincipal\n    );\n    event LoanClosed(bytes32 indexed matchId);\n    event CollateralIncreased(bytes32 indexed matchId, uint256 amount, uint256 newAmount);\n    event MarginCallTriggered(bytes32 indexed matchId, uint256 triggeredAt, uint256 currentLtvBps);\n    event MarginCallCleared(bytes32 indexed matchId);\n    event LiquidationTriggered(bytes32 indexed matchId, uint256 triggeredAt, uint256 debt, uint16 maxBonusBps);\n    event LiquidationCleared(bytes32 indexed matchId);\n    event LoanLiquidated(\n        bytes32 indexed matchId,\n        address indexed liquidator,\n        bool isPartial,\n        uint256 repaid,\n        uint256 collateralSeized,\n        uint256 bonusBps\n    );\n    event LoanWrittenDown(bytes32 indexed matchId, uint256 shortfall);\n    event RiskParamsUpdated(RiskParams params);\n    event HubSet(address indexed hub);\n    event CollateralManagerSet(address indexed collateralManager);\n\n    error LoanManager_ZeroAddress();\n    error LoanManager_NotAContract();\n    error LoanManager_NotHub();\n    error LoanManager_NotCollateralManager();\n    error LoanManager_HubAlreadySet();\n    error LoanManager_CollateralManagerAlreadySet();\n    error LoanManager_WrongChain();\n    error LoanManager_LoanExists(bytes32 matchId);\n    error LoanManager_NoSuchLoan(bytes32 matchId);\n    error LoanManager_LoanClosed(bytes32 matchId);\n    error LoanManager_ZeroAmount();\n    error LoanManager_NotInMarginCallZone();\n    error LoanManager_AlreadyMarginCalled();\n    error LoanManager_NotMarginCalled();\n    error LoanManager_GracePeriodActive();\n    error LoanManager_NotLiquidatable();\n    error LoanManager_AlreadyTriggered();\n    error LoanManager_NotTriggered();\n    error LoanManager_StillInMarginCallZone();\n    error LoanManager_StillLiquidatable();\n    error LoanManager_MaturityDefault();\n    error LoanManager_SeizeExceedsCollateral(uint256 required, uint256 available);\n    error LoanManager_NothingToLiquidate();\n    error LoanManager_SlippageExceeded(uint256 required, uint256 maxRepay);\n    error LoanManager_SeizeBelowMinimum(uint256 seized, uint256 minSeized);\n    error LoanManager_InvalidRiskParam();\n\n    modifier onlyHub() {\n        if (msg.sender != _getStorage().hub) revert LoanManager_NotHub();\n        _;\n    }\n\n    modifier onlyCollateralManager() {\n        if (msg.sender != _getStorage().collateralManager) revert LoanManager_NotCollateralManager();\n        _;\n    }\n\n    constructor() {\n        _disableInitializers();\n    }\n\n    /// @param admin Holds DEFAULT_ADMIN_ROLE. Wires the AmishHub once via {setHub} after deployment.\n    /// @param upgrader Holds UPGRADER_ROLE (a Timelock in production).\n    /// @param feeRegistry_ The FeeRegistry read at execution. Fixed here; upgrade to change.\n    /// @param apnImplementation_ The APN template cloned per loan. Fixed here; upgrade to change.\n    function initialize(address admin, address upgrader, address feeRegistry_, address apnImplementation_)\n        external\n        initializer\n    {\n        if (admin == address(0) || upgrader == address(0)) revert LoanManager_ZeroAddress();\n        if (feeRegistry_.code.length == 0 || apnImplementation_.code.length == 0) revert LoanManager_NotAContract();\n        __AccessControl_init();\n        _grantRole(DEFAULT_ADMIN_ROLE, admin);\n        _grantRole(Roles.UPGRADER_ROLE, upgrader);\n\n        LoanManagerStorage storage $ = _getStorage();\n        $.feeRegistry = feeRegistry_;\n        $.apnImplementation = apnImplementation_;\n\n        // Default risk parameters; tunable within bounds via {setRiskParams}.\n        $.risk = RiskParams({\n            auctionDuration: 60 minutes,\n            marginCallDeadline: 72 hours,\n            maturityGracePeriod: 72 hours,\n            bMin: 50, // 0.50%\n            hfFloor: 8_500, // 0.85\n            restoreBuffer: 200 // 2%\n        });\n    }\n\n    // --- admin: wiring & risk parameters ---------------------------------\n\n    /// @notice Replace the global liquidation risk parameters. Restricted to `RISK_MANAGER_ROLE`.\n    ///         Every field is range-checked: durations have floors so grace/auction windows can never\n    ///         collapse to zero, and the bonus/threshold levers are capped. What makes a specific loan\n    ///         liquidatable (its MCT/LT/maxLiquidationBonus) is fixed in the signed intent and is not\n    ///         reachable here.\n    function setRiskParams(RiskParams calldata params) external onlyRole(Roles.RISK_MANAGER_ROLE) {\n        if (params.auctionDuration < MIN_AUCTION_DURATION || params.auctionDuration > MAX_AUCTION_DURATION) {\n            revert LoanManager_InvalidRiskParam();\n        }\n        if (params.marginCallDeadline < MIN_GRACE_PERIOD || params.marginCallDeadline > MAX_GRACE_PERIOD) {\n            revert LoanManager_InvalidRiskParam();\n        }\n        if (params.maturityGracePeriod < MIN_GRACE_PERIOD || params.maturityGracePeriod > MAX_GRACE_PERIOD) {\n            revert LoanManager_InvalidRiskParam();\n        }\n        if (params.bMin > MAX_B_MIN) revert LoanManager_InvalidRiskParam();\n        if (params.hfFloor < MIN_HF_FLOOR || params.hfFloor > MAX_HF_FLOOR) revert LoanManager_InvalidRiskParam();\n        if (params.restoreBuffer > MAX_RESTORE_BUFFER) revert LoanManager_InvalidRiskParam();\n\n        _getStorage().risk = params;\n        emit RiskParamsUpdated(params);\n    }\n\n    /// @notice Wire the AmishHub. Callable exactly once; afterwards frozen (upgrade to change). The\n    ///         one-time set prevents the admin from ever granting the execution path to any address.\n    function setHub(address newHub) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        if (newHub == address(0)) revert LoanManager_ZeroAddress();\n        if (newHub.code.length == 0) revert LoanManager_NotAContract();\n        LoanManagerStorage storage $ = _getStorage();\n        if ($.hub != address(0)) revert LoanManager_HubAlreadySet();\n        $.hub = newHub;\n        emit HubSet(newHub);\n    }\n\n    /// @notice Wire the CollateralManager. Callable exactly once; afterwards frozen (upgrade to\n    ///         change). This is the vault this manager releases collateral from once a loan is\n    ///         repaid; the reverse wire (CollateralManager -> this) lets add-collateral stay in sync.\n    function setCollateralManager(address newCollateralManager) external onlyRole(DEFAULT_ADMIN_ROLE) {\n        if (newCollateralManager == address(0)) revert LoanManager_ZeroAddress();\n        if (newCollateralManager.code.length == 0) revert LoanManager_NotAContract();\n        LoanManagerStorage storage $ = _getStorage();\n        if ($.collateralManager != address(0)) revert LoanManager_CollateralManagerAlreadySet();\n        $.collateralManager = newCollateralManager;\n        emit CollateralManagerSet(newCollateralManager);\n    }\n\n    // --- lifecycle: execution & servicing --------------------------------\n\n    /// @inheritdoc ILoanManager\n    function execute(bytes32 matchId, ExecutedTerms calldata terms, string calldata apnName, string calldata apnSymbol)\n        external\n        onlyHub\n        nonReentrant\n        returns (address apn)\n    {\n        LoanManagerStorage storage $ = _getStorage();\n        if (terms.principalChainId != block.chainid) revert LoanManager_WrongChain(); // principal is issued on this chain\n        if ($.loans[matchId].borrower != address(0)) revert LoanManager_LoanExists(matchId);\n\n        (uint16 originationFeeBps, uint16 interestTakeRateBps) =\n            IFeeRegistry($.feeRegistry).feesFor(terms.principalToken);\n        address treasury = IFeeRegistry($.feeRegistry).treasury();\n        uint256 originationFee =\n            Math.mulDiv(terms.principalAmount, originationFeeBps, Constants.BPS, Math.Rounding.Floor);\n\n        // Read the principal token's decimals once and denormalize it into the loan, so later health\n        // and liquidation math never has to make an external call for this constant (mirrors how the\n        // collateral decimals are denormalized).\n        uint8 principalDecimals = IERC20Metadata(terms.principalToken).decimals();\n\n        // Effects: record the loan at the deterministic APN address before any external interaction.\n        apn = $.apnImplementation.predictDeterministicAddress(matchId, address(this));\n        _recordLoan($, matchId, terms, apn, interestTakeRateBps, principalDecimals);\n\n        // Interactions: deploy + mint the APN, then move principal.\n        address deployed = _createApn($, matchId, terms, apnName, apnSymbol, principalDecimals);\n        assert(deployed == apn); // cloneDeterministic lands at the predicted address\n        _distributePrincipal(terms, treasury, originationFee);\n\n        emit LoanCreated(\n            matchId, terms.borrower, terms.lender, apn, terms.principalToken, terms.principalAmount, originationFee\n        );\n    }\n\n    /// @inheritdoc ILoanManager\n    function repay(bytes32 matchId, uint256 amount)\n        external\n        nonReentrant\n        returns (uint256 interestPortion, uint256 principalPortion)\n    {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _activeLoan($, matchId);\n        if (amount == 0) revert LoanManager_ZeroAmount();\n\n        // Interest bills live in every case — opening an auction never touches `lastAccrualTimestamp` —\n        // so servicing a loan mid-auction costs exactly what servicing a healthy one does. The trigger\n        // is permissionless; anything less would let a borrower open their own auction to stop the clock.\n        uint256 protocolFee;\n        uint256 outstanding;\n        (interestPortion, protocolFee, principalPortion, outstanding) = _applyWaterfall($, loan, amount);\n\n        emit LoanRepaid(matchId, msg.sender, interestPortion, protocolFee, principalPortion, outstanding);\n\n        // Fully repaid: close atomically — remediation state dropped, collateral back to the borrower.\n        if (outstanding == 0) {\n            _closeLoan($, matchId);\n            return (interestPortion, principalPortion);\n        }\n\n        // A partial repay may have restored the position; clear whatever remediation state it cured\n        // (a recovered margin call, a recovered pre-maturity liquidation trigger) so the borrower is\n        // not left holding a stale, fully-elapsed grace/bonus clock. A repay that cures nothing leaves\n        // the clocks alone: a dust repay must not stall a live auction by restarting its ramp, and a\n        // liquidator simply settles the now-reduced live debt.\n        _tryClearRemediation($, loan, matchId);\n    }\n\n    // --- risk, Zone 2: margin call & partial liquidation ------------------\n\n    /// @inheritdoc ILoanManager\n    function triggerMarginCall(bytes32 matchId) external nonReentrant {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _activeLoan($, matchId);\n        Auction storage auction = $.auctions[matchId];\n        if (auction.liquidationAt != 0) revert LoanManager_AlreadyTriggered();\n        if (auction.marginCallAt != 0) revert LoanManager_AlreadyMarginCalled();\n\n        (,, uint256 ltv) = _valueAndLtv(loan, _liveDebt(loan));\n        // Only Zone 2: at/above MCT but below LT (Zone 3 goes straight to {triggerLiquidation}).\n        if (ltv < loan.marginCallThreshold || ltv >= loan.liquidationThreshold) {\n            revert LoanManager_NotInMarginCallZone();\n        }\n\n        auction.marginCallAt = uint64(block.timestamp);\n        emit MarginCallTriggered(matchId, block.timestamp, ltv);\n    }\n\n    /// @inheritdoc ILoanManager\n    /// @dev Repay- and top-up-driven recoveries clear automatically ({_tryClearRemediation}), but a\n    ///      purely price-driven recovery writes no transaction, so nothing on-chain can observe it.\n    ///      Left uncleared, the stale timestamp would let a re-dip into Zone 2 be liquidated with no\n    ///      fresh grace — the borrower or the off-chain monitor calls this on every price recovery.\n    function clearMarginCall(bytes32 matchId) external nonReentrant {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _existingLoan($, matchId);\n        Auction storage auction = $.auctions[matchId];\n        if (auction.marginCallAt == 0) revert LoanManager_NotMarginCalled();\n        // Only clear once the position has genuinely recovered below the margin-call threshold, so a\n        // later re-crossing starts a fresh grace window.\n        (,, uint256 ltv) = _valueAndLtv(loan, _liveDebt(loan));\n        if (ltv >= loan.marginCallThreshold) revert LoanManager_StillInMarginCallZone();\n\n        auction.marginCallAt = 0;\n        emit MarginCallCleared(matchId);\n    }\n\n    /// @inheritdoc ILoanManager\n    function liquidatePartial(bytes32 matchId, uint256 repayAmount, uint256 minSeized)\n        external\n        nonReentrant\n        returns (uint256 repaid, uint256 collateralSeized)\n    {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _activeLoan($, matchId);\n        Auction storage auction = $.auctions[matchId];\n        if (auction.liquidationAt != 0) revert LoanManager_AlreadyTriggered();\n        if (auction.marginCallAt == 0) revert LoanManager_NotMarginCalled();\n        if (block.timestamp < uint256(auction.marginCallAt) + $.risk.marginCallDeadline) {\n            revert LoanManager_GracePeriodActive();\n        }\n\n        uint256 debt = _liveDebt(loan);\n        (uint256 collValue, uint256 normalizedPrice, uint256 ltv) = _valueAndLtv(loan, debt);\n        // Must still be in Zone 2: below MCT the position has recovered (clear it via {clearMarginCall}),\n        // at/above LT it needs a full liquidation instead. Either way, refuse the partial.\n        if (ltv < loan.marginCallThreshold || ltv >= loan.liquidationThreshold) {\n            revert LoanManager_NotInMarginCallZone();\n        }\n\n        uint256 bonus = _bonus($, loan, uint256(auction.marginCallAt) + $.risk.marginCallDeadline, ltv);\n        uint16 targetLtv =\n            loan.marginCallThreshold > $.risk.restoreBuffer ? loan.marginCallThreshold - $.risk.restoreBuffer : 0;\n        uint256 maxRepay = AuctionMath.partialMaxRepay(debt, collValue, targetLtv, bonus);\n\n        repaid = repayAmount < maxRepay ? repayAmount : maxRepay;\n        if (repaid > debt) repaid = debt;\n        if (repaid == 0) revert LoanManager_NothingToLiquidate();\n\n        collateralSeized = LtvMath.valueToCollateral(AuctionMath.grossUpValue(repaid, bonus), normalizedPrice);\n        if (collateralSeized > loan.collateralAmount) {\n            revert LoanManager_SeizeExceedsCollateral(collateralSeized, loan.collateralAmount);\n        }\n        // The floor is a rate quote against `repayAmount`, scaled pro-rata to the actual fill: the\n        // engine caps `repaid` (to the live restoring maximum, or the debt), so an absolute floor\n        // would revert every capped fill even when the caller's exchange rate held exactly. Floor\n        // rounding is guard-lenient by at most one base unit.\n        uint256 seizeFloor = Math.mulDiv(minSeized, repaid, repayAmount);\n        if (collateralSeized < seizeFloor) revert LoanManager_SeizeBelowMinimum(collateralSeized, seizeFloor);\n\n        // Effects: apply the repayment (interest-first, principal reduced, clock advanced) and reduce\n        // the denormalized collateral before the external seize (checks-effects-interactions).\n        (,,, uint256 outstanding) = _applyWaterfall($, loan, repaid);\n        loan.collateralAmount -= collateralSeized;\n\n        // Interactions: hand the seized collateral (bonus included) to the liquidator; this also\n        // reduces the CollateralManager's deposit, keeping the two records in sync.\n        ICollateralManager($.collateralManager).seizeCollateral(matchId, msg.sender, collateralSeized);\n        emit LoanLiquidated(matchId, msg.sender, true, repaid, collateralSeized, bonus);\n\n        // A partial that settles the entire debt (the knife edge where the LTV sits exactly at\n        // 1/(1+bonus)) closes the loan just as {repay} would — otherwise the deposit would strand on\n        // a closed loan that {repay} and {liquidate} both refuse to touch.\n        if (outstanding == 0) {\n            _closeLoan($, matchId);\n            return (repaid, collateralSeized);\n        }\n\n        // Clear the margin call only if the position genuinely restored below MCT: a partial that\n        // leaves it in Zone 2 keeps the elapsed grace (follow-ups need no fresh 72h wait), and a dust\n        // repayment can no longer zero the clock to grief the lender's remedy.\n        (, uint256 newLtv) = _ltvAtPrice(loan, _liveDebt(loan), normalizedPrice);\n        if (newLtv < loan.marginCallThreshold) {\n            auction.marginCallAt = 0;\n            emit MarginCallCleared(matchId);\n        }\n    }\n\n    // --- risk, Zone 3 & maturity default: full liquidation ----------------\n\n    /// @inheritdoc ILoanManager\n    function triggerLiquidation(bytes32 matchId) external nonReentrant {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _activeLoan($, matchId);\n        Auction storage auction = $.auctions[matchId];\n        if (auction.liquidationAt != 0) revert LoanManager_AlreadyTriggered();\n\n        uint256 debt = _liveDebt(loan);\n        bool pastMaturity = block.timestamp >= loan.startTimestamp + loan.duration + $.risk.maturityGracePeriod;\n        (,, uint256 ltv) = _valueAndLtv(loan, debt);\n        if (ltv < loan.liquidationThreshold && !pastMaturity) revert LoanManager_NotLiquidatable();\n\n        // Open the auction: the reverse-Dutch bonus clock runs from here. Accrual is left untouched,\n        // so every settlement path — repay, clear, or seizure — bills the full elapsed window; `debt`\n        // is emitted only as an observer snapshot.\n        auction.liquidationAt = uint64(block.timestamp);\n        emit LiquidationTriggered(matchId, block.timestamp, debt, loan.maxLiquidationBonus);\n    }\n\n    /// @inheritdoc ILoanManager\n    function clearLiquidation(bytes32 matchId) external nonReentrant {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _existingLoan($, matchId);\n        Auction storage auction = $.auctions[matchId];\n        if (auction.liquidationAt == 0) revert LoanManager_NotTriggered();\n        // A maturity default is liquidatable regardless of health, so it cannot be cleared. A pure\n        // Zone-3 trigger clears once the price recovers back below the liquidation threshold.\n        bool pastMaturity = block.timestamp >= loan.startTimestamp + loan.duration + $.risk.maturityGracePeriod;\n        if (pastMaturity) revert LoanManager_MaturityDefault();\n        (,, uint256 ltv) = _valueAndLtv(loan, _liveDebt(loan));\n        if (ltv >= loan.liquidationThreshold) revert LoanManager_StillLiquidatable();\n\n        // Close the auction. Accrual was never paused (`lastAccrualTimestamp` was never moved), so the\n        // whole window the auction was open stays billed — clearing forgives nothing.\n        auction.liquidationAt = 0;\n        emit LiquidationCleared(matchId);\n    }\n\n    /// @inheritdoc ILoanManager\n    function liquidate(bytes32 matchId, uint256 maxRepay, uint256 minSeized)\n        external\n        nonReentrant\n        returns (uint256 repaid, uint256 collateralSeized)\n    {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _activeLoan($, matchId);\n        Auction storage auction = $.auctions[matchId];\n        if (auction.liquidationAt == 0) revert LoanManager_NotTriggered();\n\n        // Settle against the live debt: the trigger never paused accrual, so a seizure bills the full\n        // window exactly as {repay} would — self-liquidation is never cheaper than repaying.\n        uint256 debt = _liveDebt(loan);\n        (uint256 collValue, uint256 normalizedPrice, uint256 ltv) = _valueAndLtv(loan, debt);\n\n        // A Zone-3 trigger whose position has recovered below LT is stale: the borrower must not be\n        // seized on it (clear it via the permissionless {clearLiquidation}). A maturity default stays\n        // liquidatable regardless of health.\n        bool pastMaturity = block.timestamp >= loan.startTimestamp + loan.duration + $.risk.maturityGracePeriod;\n        if (!pastMaturity && ltv < loan.liquidationThreshold) revert LoanManager_NotLiquidatable();\n\n        // Price the bonus off the auction clock — except for a trigger that predates the maturity\n        // default and whose Zone-3 distress has since recovered without being cleared: its clock would\n        // arrive fully elapsed and turn the default into an instant max-bonus seizure. Re-base it to\n        // the default deadline so the seizure prices exactly like a freshly triggered maturity-default\n        // auction. A position still at/above its liquidation threshold keeps its genuine running clock.\n        uint256 auctionStart = auction.liquidationAt;\n        if (pastMaturity && ltv < loan.liquidationThreshold) {\n            uint256 defaultAt = loan.startTimestamp + loan.duration + $.risk.maturityGracePeriod;\n            if (auctionStart < defaultAt) auctionStart = defaultAt;\n        }\n        uint256 bonus = _bonus($, loan, auctionStart, ltv);\n\n        uint256 available = loan.collateralAmount;\n        uint256 desiredSeize = LtvMath.valueToCollateral(AuctionMath.grossUpValue(debt, bonus), normalizedPrice);\n        if (desiredSeize <= available) {\n            // Solvent: repay the full live debt, seize its grossed-up value, return the rest.\n            repaid = debt;\n            collateralSeized = desiredSeize;\n        } else {\n            // Underwater: the collateral cannot cover debt + bonus. Seize all of it and repay only the\n            // amount it backs (collValue / (1 + bonus)); the remaining principal is written down.\n            collateralSeized = available;\n            repaid = Math.mulDiv(collValue, Constants.BPS, Constants.BPS + bonus, Math.Rounding.Floor);\n            if (repaid > debt) repaid = debt; // guard rounding\n        }\n        if (repaid > maxRepay) revert LoanManager_SlippageExceeded(repaid, maxRepay);\n        if (collateralSeized < minSeized) revert LoanManager_SeizeBelowMinimum(collateralSeized, minSeized);\n\n        // Apply the repayment interest-first against the live legs, then write down any principal the\n        // repayment did not cover and close the loan.\n        _settleLiquidation($, loan, matchId, debt, repaid);\n\n        // Interactions: seize, then release the remainder to the borrower and clear the deposit. A\n        // zero seize (dust debt, or a stripped position) is skipped — seizeCollateral rejects zero\n        // amounts, and reverting would leave an otherwise-liquidatable loan uncloseable.\n        ICollateralManager cm = ICollateralManager($.collateralManager);\n        if (collateralSeized != 0) cm.seizeCollateral(matchId, msg.sender, collateralSeized);\n        cm.release(matchId);\n\n        emit LoanLiquidated(matchId, msg.sender, false, repaid, collateralSeized, bonus);\n        emit LoanClosed(matchId);\n    }\n\n    // --- collateral sync (CollateralManager-driven) -----------------------\n\n    /// @inheritdoc ILoanManager\n    function increaseCollateral(bytes32 matchId, uint256 amount) external onlyCollateralManager {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = _existingLoan($, matchId);\n        uint256 newAmount = loan.collateralAmount + amount;\n        loan.collateralAmount = newAmount;\n        emit CollateralIncreased(matchId, amount, newAmount);\n\n        // A top-up is a deleveraging action just like a repayment: clear whatever remediation state\n        // the added collateral cured, so the borrower's recovery is recorded the moment it happens.\n        _tryClearRemediation($, loan, matchId);\n    }\n\n    // --- views -------------------------------------------------------------\n\n    /// @inheritdoc ILoanManager\n    function unrealizedValue(bytes32 matchId) external view returns (uint256) {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = $.loans[matchId];\n        uint256 outstanding = loan.outstandingPrincipal;\n        if (outstanding == 0) return 0; // unknown or fully-repaid loan: nothing owed\n        // The lender's share of accrued interest (net of the protocol take), marked to market — live\n        // even during an auction. Rounds down so the NAV is never overstated; principal repayment\n        // moves value from `outstanding` into the note's cash, keeping NAV continuous across repays.\n        uint256 accrued = InterestMath.accrued(outstanding, loan.rate, block.timestamp - loan.lastAccrualTimestamp);\n        uint256 lenderAccrued =\n            Math.mulDiv(accrued, Constants.BPS - loan.interestTakeRateBps, Constants.BPS, Math.Rounding.Floor);\n        return outstanding + lenderAccrued;\n    }\n\n    /// @inheritdoc ILoanManager\n    function debtOf(bytes32 matchId) external view returns (uint256) {\n        Loan storage loan = _getStorage().loans[matchId];\n        if (loan.outstandingPrincipal == 0) return 0; // unknown or fully-repaid loan\n        return _liveDebt(loan);\n    }\n\n    /// @inheritdoc ILoanManager\n    function healthOf(bytes32 matchId)\n        external\n        view\n        returns (uint256 debt, uint256 collateralValue, uint256 ltvBps, uint8 zone)\n    {\n        LoanManagerStorage storage $ = _getStorage();\n        Loan storage loan = $.loans[matchId];\n        if (loan.outstandingPrincipal == 0) return (0, 0, 0, 0); // unknown or fully-repaid loan\n        debt = _liveDebt(loan);\n        (collateralValue,, ltvBps) = _valueAndLtv(loan, debt);\n        // Zone = trigger eligibility, matching {triggerLiquidation} / {triggerMarginCall} exactly:\n        // 2 once LTV reaches the liquidation threshold OR the maturity default deadline has passed,\n        // 1 inside the margin-call band [MCT, LT), 0 otherwise.\n        bool pastDefault = block.timestamp >= loan.startTimestamp + loan.duration + $.risk.maturityGracePeriod;\n        if (ltvBps >= loan.liquidationThreshold || pastDefault) zone = 2;\n        else if (ltvBps >= loan.marginCallThreshold) zone = 1;\n    }\n\n    /// @inheritdoc ILoanManager\n    function auctionOf(bytes32 matchId) external view returns (Auction memory) {\n        return _getStorage().auctions[matchId];\n    }\n\n    /// @inheritdoc ILoanManager\n    function riskParams() external view returns (RiskParams memory) {\n        return _getStorage().risk;\n    }\n\n    /// @inheritdoc ILoanManager\n    function loanOf(bytes32 matchId) external view returns (Loan memory) {\n        return _getStorage().loans[matchId];\n    }\n\n    /// @notice The AmishHub wired to this manager.\n    function hub() external view returns (address) {\n        return _getStorage().hub;\n    }\n\n    /// @notice The FeeRegistry read at execution.\n    function feeRegistry() external view returns (address) {\n        return _getStorage().feeRegistry;\n    }\n\n    /// @notice The APN template cloned per loan.\n    function apnImplementation() external view returns (address) {\n        return _getStorage().apnImplementation;\n    }\n\n    /// @notice The CollateralManager this manager releases collateral from.\n    function collateralManager() external view returns (address) {\n        return _getStorage().collateralManager;\n    }\n\n    // --- internals ----------------------------------------------------------\n\n    function _createApn(\n        LoanManagerStorage storage $,\n        bytes32 matchId,\n        ExecutedTerms calldata terms,\n        string calldata apnName,\n        string calldata apnSymbol,\n        uint8 principalDecimals\n    ) private returns (address apn) {\n        apn = $.apnImplementation.cloneDeterministic(matchId);\n        APNImplementation(apn)\n            .initialize(\n                matchId,\n                terms.principalToken,\n                terms.lender,\n                terms.principalAmount,\n                terms.apnTransferable,\n                principalDecimals,\n                apnName,\n                apnSymbol\n            );\n    }\n\n    function _recordLoan(\n        LoanManagerStorage storage $,\n        bytes32 matchId,\n        ExecutedTerms calldata terms,\n        address apn,\n        uint16 interestTakeRateBps,\n        uint8 principalDecimals\n    ) private {\n        $.loans[matchId] = Loan({\n            borrower: terms.borrower,\n            apn: apn,\n            collateralToken: terms.collateralToken,\n            collateralAmount: terms.collateralAmount,\n            collateralChainId: terms.collateralChainId,\n            collateralDecimals: terms.collateralDecimals,\n            oracle: terms.oracle,\n            oracleType: terms.oracleType,\n            maxStaleness: terms.maxStaleness,\n            ltv: terms.ltv,\n            marginCallThreshold: terms.marginCallThreshold,\n            liquidationThreshold: terms.liquidationThreshold,\n            maxLiquidationBonus: terms.maxLiquidationBonus,\n            principalToken: terms.principalToken,\n            principalDecimals: principalDecimals,\n            principalChainId: terms.principalChainId,\n            outstandingPrincipal: terms.principalAmount,\n            rate: terms.rate,\n            rateType: terms.rateType,\n            interestTakeRateBps: interestTakeRateBps,\n            startTimestamp: block.timestamp,\n            duration: terms.duration,\n            lastAccrualTimestamp: block.timestamp\n        });\n    }\n\n    /// @dev Moves principal directly from the lender — the origination fee to the treasury and the\n    ///      remainder to the borrower — so this contract never custodies principal. The lender must\n    ///      have approved this contract for the full principal. Unlike collateral, principal is not\n    ///      balance-delta-checked: a non-standard (e.g. fee-on-transfer) principal token only affects\n    ///      the borrower who named it in their intent, never the lender's claim or protocol solvency.\n    function _distributePrincipal(ExecutedTerms calldata terms, address treasury, uint256 originationFee) private {\n        IERC20 principal = IERC20(terms.principalToken);\n        if (originationFee != 0) principal.safeTransferFrom(terms.lender, treasury, originationFee);\n        principal.safeTransferFrom(terms.lender, terms.borrower, terms.principalAmount - originationFee);\n    }\n\n    /// @dev Interest-first repayment waterfall shared by {repay} and {liquidatePartial}: interest\n    ///      accrued on the current principal is paid first (split treasury/lender), the remainder\n    ///      reduces principal, and the accrual clock advances by only the paid fraction of elapsed time\n    ///      when interest is partially paid (a full reset would forgive unpaid interest). Amounts above\n    ///      the total owed are capped. Effects precede the token pulls; callers hold `nonReentrant`.\n    function _applyWaterfall(LoanManagerStorage storage $, Loan storage loan, uint256 amount)\n        private\n        returns (uint256 interestPortion, uint256 protocolFee, uint256 principalPortion, uint256 outstanding)\n    {\n        uint256 elapsed = block.timestamp - loan.lastAccrualTimestamp;\n        uint256 accrued = InterestMath.accrued(loan.outstandingPrincipal, loan.rate, elapsed);\n        uint256 totalOwed = loan.outstandingPrincipal + accrued;\n        if (amount > totalOwed) amount = totalOwed;\n\n        interestPortion = amount < accrued ? amount : accrued;\n        protocolFee = Math.mulDiv(interestPortion, loan.interestTakeRateBps, Constants.BPS, Math.Rounding.Floor);\n        uint256 lenderInterest = interestPortion - protocolFee; // lender takes the rounding dust\n        principalPortion = amount - interestPortion;\n\n        outstanding = loan.outstandingPrincipal - principalPortion;\n        loan.outstandingPrincipal = outstanding;\n        if (interestPortion == accrued) {\n            loan.lastAccrualTimestamp = block.timestamp; // all accrued interest cleared: reset fully\n        } else {\n            // Partial-interest payment: advance the clock by just the paid fraction so unpaid interest\n            // stays owed. `accrued > interestPortion` here, so no divide-by-zero; flooring is lender-safe.\n            loan.lastAccrualTimestamp += Math.mulDiv(elapsed, interestPortion, accrued, Math.Rounding.Floor);\n        }\n\n        _payLegs($, loan, protocolFee, lenderInterest + principalPortion);\n    }\n\n    /// @dev Settle a full liquidation against the live debt legs and close the loan. `repaid` is\n    ///      applied interest-first; any principal it does not cover is written down (the loss reaches\n    ///      the lender through a lower APN NAV once `outstandingPrincipal` is zeroed). Clears the\n    ///      auction. Effects precede the token pulls; the caller holds `nonReentrant`.\n    function _settleLiquidation(\n        LoanManagerStorage storage $,\n        Loan storage loan,\n        bytes32 matchId,\n        uint256 debt,\n        uint256 repaid\n    ) private {\n        uint256 principalOwed = loan.outstandingPrincipal;\n        uint256 interestOwed = debt - principalOwed; // interest accrued live through the auction\n        uint256 interestPortion = repaid < interestOwed ? repaid : interestOwed;\n        uint256 protocolFee = Math.mulDiv(interestPortion, loan.interestTakeRateBps, Constants.BPS, Math.Rounding.Floor);\n        uint256 lenderInterest = interestPortion - protocolFee;\n        uint256 principalPortion = repaid - interestPortion;\n        uint256 shortfall = principalOwed - principalPortion;\n\n        // Effects: close the loan and drop the freeze before any interaction. A full liquidation removes\n        // all collateral (seized to the liquidator + released to the borrower), so zero the denormalized\n        // amount too rather than leaving a stale figure on the closed loan.\n        loan.outstandingPrincipal = 0;\n        loan.collateralAmount = 0;\n        loan.lastAccrualTimestamp = block.timestamp;\n        delete $.auctions[matchId];\n\n        _payLegs($, loan, protocolFee, lenderInterest + principalPortion);\n        if (shortfall != 0) emit LoanWrittenDown(matchId, shortfall);\n    }\n\n    /// @dev Pull a repayment from the caller: the protocol fee to the treasury and the lender's legs\n    ///      (interest + returned principal) into the APN, which custodies them as the liquid part of\n    ///      its NAV until holders redeem.\n    function _payLegs(LoanManagerStorage storage $, Loan storage loan, uint256 protocolFee, uint256 apnLeg) private {\n        IERC20 principal = IERC20(loan.principalToken);\n        if (protocolFee != 0) {\n            principal.safeTransferFrom(msg.sender, IFeeRegistry($.feeRegistry).treasury(), protocolFee);\n        }\n        if (apnLeg != 0) principal.safeTransferFrom(msg.sender, loan.apn, apnLeg);\n    }\n\n    /// @dev Load a loan that was ever created, closed or not.\n    function _existingLoan(LoanManagerStorage storage $, bytes32 matchId) private view returns (Loan storage loan) {\n        loan = $.loans[matchId];\n        if (loan.borrower == address(0)) revert LoanManager_NoSuchLoan(matchId);\n    }\n\n    /// @dev Load a loan that exists and still has outstanding principal — the precondition of every\n    ///      servicing and risk action.\n    function _activeLoan(LoanManagerStorage storage $, bytes32 matchId) private view returns (Loan storage loan) {\n        loan = _existingLoan($, matchId);\n        if (loan.outstandingPrincipal == 0) revert LoanManager_LoanClosed(matchId);\n    }\n\n    /// @dev Close a fully-repaid loan: drop any remediation state and release the remaining\n    ///      collateral to the borrower. The caller has already settled the loan's legs.\n    function _closeLoan(LoanManagerStorage storage $, bytes32 matchId) private {\n        delete $.auctions[matchId];\n        ICollateralManager($.collateralManager).release(matchId);\n        emit LoanClosed(matchId);\n    }\n\n    /// @dev Live debt: outstanding principal plus interest accrued to this block.\n    function _liveDebt(Loan storage loan) private view returns (uint256) {\n        return loan.outstandingPrincipal\n            + InterestMath.accrued(loan.outstandingPrincipal, loan.rate, block.timestamp - loan.lastAccrualTimestamp);\n    }\n\n    /// @dev Read the oracle (reverting on a dead or stale feed) and value the position in one call:\n    ///      collateral value in principal base units, the normalized price (reused by liquidation\n    ///      callers to size the seize without a second read), and the LTV of `debt`.\n    function _valueAndLtv(Loan storage loan, uint256 debt)\n        private\n        view\n        returns (uint256 collValue, uint256 normalizedPrice, uint256 ltv)\n    {\n        (uint256 price, uint8 priceDecimals) =\n            OracleLib.readPrice(loan.oracle, loan.collateralToken, loan.principalToken, loan.maxStaleness);\n        normalizedPrice = LtvMath.normalizePrice(price, priceDecimals, loan.collateralDecimals, loan.principalDecimals);\n        (collValue, ltv) = _ltvAtPrice(loan, debt, normalizedPrice);\n    }\n\n    /// @dev The LTV formula and its zero-guard (zero collateral value reads as maximally leveraged)\n    ///      at an already-normalized price — the single home of both; health checks must not\n    ///      reimplement them. Token decimals are denormalized into the loan, so no external\n    ///      decimals() call is made here.\n    function _ltvAtPrice(Loan storage loan, uint256 debt, uint256 normalizedPrice)\n        private\n        view\n        returns (uint256 collValue, uint256 ltv)\n    {\n        collValue = LtvMath.collateralValue(loan.collateralAmount, normalizedPrice);\n        ltv = collValue == 0 ? type(uint256).max : LtvMath.ltvBps(debt, collValue);\n    }\n\n    /// @dev Best-effort clearing of remediation state after a deleveraging action (a repayment or a\n    ///      collateral top-up): a margin call clears once the position is back below MCT, a\n    ///      pre-maturity liquidation trigger once back below LT — the same conditions\n    ///      {clearMarginCall} / {clearLiquidation} enforce, applied automatically so a cured borrower\n    ///      is not left holding a stale, fully-elapsed grace/bonus clock. A maturity default is never\n    ///      cleared. Skipped silently when no fresh price is available, so a dead feed never blocks\n    ///      servicing; the permissionless clear functions remain the fallback.\n    function _tryClearRemediation(LoanManagerStorage storage $, Loan storage loan, bytes32 matchId) private {\n        Auction storage auction = $.auctions[matchId];\n        if (auction.marginCallAt == 0 && auction.liquidationAt == 0) return;\n\n        (bool ok, uint256 price, uint8 priceDecimals) =\n            OracleLib.tryReadPrice(loan.oracle, loan.collateralToken, loan.principalToken, loan.maxStaleness);\n        if (!ok) return;\n        uint256 normalizedPrice =\n            LtvMath.normalizePrice(price, priceDecimals, loan.collateralDecimals, loan.principalDecimals);\n        (, uint256 ltv) = _ltvAtPrice(loan, _liveDebt(loan), normalizedPrice);\n\n        if (auction.liquidationAt != 0) {\n            bool pastMaturity = block.timestamp >= loan.startTimestamp + loan.duration + $.risk.maturityGracePeriod;\n            if (!pastMaturity && ltv < loan.liquidationThreshold) {\n                auction.liquidationAt = 0;\n                emit LiquidationCleared(matchId);\n            }\n        }\n        if (auction.marginCallAt != 0 && ltv < loan.marginCallThreshold) {\n            auction.marginCallAt = 0;\n            emit MarginCallCleared(matchId);\n        }\n    }\n\n    /// @dev The auction bonus (bps) for a loan at the given LTV, `auctionStart`, and current time,\n    ///      using the zone-appropriate distress metric (Zone 3 / Zone 2 / healthy-maturity = 0).\n    function _bonus(LoanManagerStorage storage $, Loan storage loan, uint256 auctionStart, uint256 ltv)\n        private\n        view\n        returns (uint256)\n    {\n        uint256 distress;\n        if (ltv >= loan.liquidationThreshold) {\n            distress = AuctionMath.distressZone3(ltv, loan.liquidationThreshold, $.risk.hfFloor);\n        } else if (ltv >= loan.marginCallThreshold) {\n            distress = AuctionMath.distressZone2(ltv, loan.marginCallThreshold, loan.liquidationThreshold);\n        }\n        uint256 timePct = AuctionMath.timePct(block.timestamp - auctionStart, $.risk.auctionDuration);\n        return AuctionMath.bonusBps($.risk.bMin, loan.maxLiquidationBonus, AuctionMath.progress(timePct, distress));\n    }\n\n    function _authorizeUpgrade(address) internal override onlyRole(Roles.UPGRADER_ROLE) {}\n\n    function _getStorage() private pure returns (LoanManagerStorage storage $) {\n        assembly {\n            $.slot := STORAGE_LOCATION\n        }\n    }\n}\n"},"amish-contracts/src/interfaces/IAPN.sol":{"keccak256":"0xa6f69deed1e32f7dbdb25747512e395e6587e1d0d7a15f19c60a212e55732bd3","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title IAPN\n/// @notice Redemption surface of an Amish Position Note. An APN is an ERC-4626-style share of a\n///         single loan: its NAV is the loan's outstanding principal plus the lender's mark-to-market\n///         accrued interest (read live from the LoanManager) plus the principal-token cash already\n///         repaid into the note. Redeeming burns shares at `NAV / totalSupply` and pays the\n///         proportional assets, capped by the cash on hand.\ninterface IAPN {\n    /// @notice The note's net asset value in principal-token base units: illiquid loan claim\n    ///         (outstanding principal + lender accrued interest) plus liquid repaid cash.\n    function totalAssets() external view returns (uint256);\n\n    /// @notice Assets `shares` are currently worth at the mark-to-market share price (uncapped by\n    ///         cash; the actual redeemable amount is bounded by {maxRedeem}).\n    function convertToAssets(uint256 shares) external view returns (uint256);\n\n    /// @notice Shares that `assets` are worth at the current share price — the inverse of\n    ///         {convertToAssets}. Applied to the cash on hand, it is the share count {maxRedeem} caps to.\n    function convertToShares(uint256 assets) external view returns (uint256);\n\n    /// @notice The largest number of shares `owner` can redeem right now — the lesser of their\n    ///         balance and the shares whose value the cash on hand can cover.\n    function maxRedeem(address owner) external view returns (uint256);\n\n    /// @notice Burn `shares` and receive `shares · NAV / totalSupply` of the principal token. Reverts\n    ///         if the payout exceeds the cash on hand (redeem fewer, or wait for more repayments).\n    /// @return assets Principal token paid to the caller.\n    function redeem(uint256 shares) external returns (uint256 assets);\n\n    /// @notice Redeem the caller's full currently-redeemable amount ({maxRedeem}) in one call.\n    /// @return assets Principal token paid to the caller.\n    function redeemMax() external returns (uint256 assets);\n}\n"},"amish-contracts/src/interfaces/IAmishOracle.sol":{"keccak256":"0x48aea1456791d3f8a6dda9b09d43dc6f2b948ea006d845b4f8d9163af02fc906","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title IAmishOracle\n/// @notice Oracle-agnostic price interface. Adapters wrap concrete sources\n///         (Chainlink, Pyth, TWAP, …) behind this interface; anyone can deploy new adapters.\n/// @dev The adapter must live on the principal chain — the health factor is computed on-chain at\n///      liquidation and margin-call time, so the price must be readable directly. Treat this\n///      signature as a stable external interface.\ninterface IAmishOracle {\n    /// @notice Fixed number of decimals the adapter's price is scaled by (Chainlink-style, e.g. 8).\n    ///         Constant per adapter; consumers rebase with this plus the two tokens' own decimals.\n    function decimals() external view returns (uint8);\n\n    /// @notice Price of one *whole* `collateralToken` denominated in *whole* `principalToken`, scaled\n    ///         by `10 ** decimals()`. Independent of the ERC-20s' own decimals (those are applied by\n    ///         the consumer). E.g. WBTC at 100,000 USDC with 8 price-decimals returns 100_000e8.\n    /// @param collateralToken The collateral asset.\n    /// @param principalToken The loan asset the price is quoted in.\n    /// @return price Whole-collateral price in whole-principal units, at `10 ** decimals()` scale.\n    /// @return updatedAt Unix timestamp of the underlying feed's last update (staleness check).\n    function getPrice(address collateralToken, address principalToken)\n        external\n        view\n        returns (uint256 price, uint256 updatedAt);\n}\n"},"amish-contracts/src/interfaces/ICollateralManager.sol":{"keccak256":"0x1621bab5188a9cb0ae644ff980adb69023e6c0e74d1356d84dd59f4ec0d3a5d7","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title ICollateralManager\n/// @notice Interface for the singleton that custodies borrower collateral, keyed by loan.\ninterface ICollateralManager {\n    /// @notice A borrower's locked collateral for one loan.\n    struct CollateralDeposit {\n        address borrower;\n        address token;\n        uint256 amount;\n    }\n\n    /// @notice Pull and custody `amount` of `token` (declared on `chainId`) from `borrower` for\n    ///         loan `matchId`.\n    /// @dev Restricted to the orchestrator. `chainId` must be this chain (collateral is custodied on\n    ///      the chain where this manager is deployed). Reverts if a deposit already exists for `matchId`.\n    function lock(bytes32 matchId, address borrower, address token, uint256 chainId, uint256 amount) external;\n\n    /// @notice Return all collateral for `matchId` to its borrower and clear the deposit. Restricted\n    ///         to the LoanManager, which calls it only once the loan's principal is fully repaid.\n    function release(bytes32 matchId) external;\n\n    /// @notice Transfer `amount` of `matchId`'s collateral to `recipient` and reduce the deposit by\n    ///         that much, without clearing it. Restricted to the LoanManager, which calls it during a\n    ///         liquidation to hand the liquidator their seized collateral (bonus included); the\n    ///         LoanManager keeps its own denormalized amount in sync in the same transaction. Reverts if\n    ///         `amount` exceeds the deposit. For a full liquidation the LoanManager then calls\n    ///         {release} to return the remaining collateral to the borrower.\n    function seizeCollateral(bytes32 matchId, address recipient, uint256 amount) external;\n\n    /// @notice Add `amount` more collateral to an existing deposit, pulled from the caller, and sync\n    ///         the LoanManager's denormalized amount. Lowers the position's effective LTV; usable by\n    ///         anyone (a top-up only benefits the borrower, who receives it back on release).\n    function addCollateral(bytes32 matchId, uint256 amount) external;\n\n    /// @notice The collateral deposit recorded for `matchId` (zeroed if none).\n    function depositOf(bytes32 matchId) external view returns (CollateralDeposit memory);\n}\n"},"amish-contracts/src/interfaces/IFeeRegistry.sol":{"keccak256":"0x11f9d7ca28b06bed448c54f57cb6c81f8ecf7763e68a0d169899654857c4e3f9","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title IFeeRegistry\n/// @notice Read interface for the per-token fee parameters consumed at loan execution.\n///         LoanManager snapshots `interestTakeRateBps` into each loan; AmishHub/LoanManager\n///         read `originationFeeBps` and `treasury` at creation.\ninterface IFeeRegistry {\n    /// @notice Effective fee parameters for `token`. Tokens without an explicit config fall back\n    ///         to the protocol-wide default fees.\n    /// @return originationFeeBps One-time fee on principal, charged to the borrower (bps).\n    /// @return interestTakeRateBps Protocol's cut of interest, taken before the lender (bps).\n    function feesFor(address token) external view returns (uint16 originationFeeBps, uint16 interestTakeRateBps);\n\n    /// @notice Address that receives origination fees and the protocol's interest cut.\n    function treasury() external view returns (address);\n}\n"},"amish-contracts/src/interfaces/ILoanManager.sol":{"keccak256":"0x449d02170d571143856030e71e48c26175ac596a6ef2a35d766caead98b04e37","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {ExecutedTerms} from \"../types/DataTypes.sol\";\n\n/// @title ILoanManager\n/// @notice Interface for the singleton that manages loans on the principal chain.\ninterface ILoanManager {\n    /// @notice A loan's full on-chain state. Collateral parameters are denormalized so the loan can\n    ///         be valued and liquidated without reading the CollateralManager.\n    struct Loan {\n        address borrower;\n        address apn;\n        // Collateral (denormalized)\n        address collateralToken;\n        uint256 collateralAmount;\n        uint256 collateralChainId;\n        uint8 collateralDecimals; // collateral token decimals, denormalized (may be a remote token)\n        address oracle;\n        bytes32 oracleType;\n        uint32 maxStaleness;\n        uint16 ltv;\n        uint16 marginCallThreshold;\n        uint16 liquidationThreshold;\n        uint16 maxLiquidationBonus;\n        // Principal & interest\n        address principalToken;\n        uint8 principalDecimals; // principal token decimals, denormalized at execution (packs with principalToken)\n        uint256 principalChainId;\n        uint256 outstandingPrincipal;\n        uint16 rate;\n        bytes32 rateType;\n        uint16 interestTakeRateBps; // snapshotted from FeeRegistry at creation\n        uint256 startTimestamp;\n        uint256 duration;\n        uint256 lastAccrualTimestamp;\n    }\n\n    /// @notice Per-loan liquidation-auction state. All-zero when the loan is healthy and untriggered.\n    struct Auction {\n        uint64 marginCallAt; // when the margin call was triggered (Zone 2 grace start); 0 = none\n        uint64 liquidationAt; // when full liquidation was triggered (auction start); 0 = none\n    }\n\n    /// @notice Global, admin-tunable liquidation parameters. Every field is range-bounded in code so\n    ///         tuning changes only the auction's shape, never whether a healthy loan can be seized\n    ///         (that is fixed per-loan by the signed intent's MCT/LT/maxLiquidationBonus).\n    struct RiskParams {\n        uint32 auctionDuration; // seconds for the auction's time factor to reach 100%\n        uint32 marginCallDeadline; // Zone 2 grace before partial liquidation opens, seconds\n        uint32 maturityGracePeriod; // grace after maturity before default liquidation opens, seconds\n        uint16 bMin; // starting bonus, bps\n        uint16 hfFloor; // HF at which Zone 3 distress reaches 1.0, bps ratio\n        uint16 restoreBuffer; // partial liquidation restores to MCT - restoreBuffer, bps\n    }\n\n    /// @notice Create a loan from derived terms: move principal (minus the origination fee), record\n    ///         the loan, and mint the lender an APN. Restricted to the orchestrator.\n    /// @param apnName Display name for the loan's APN token (executor-supplied, cosmetic).\n    /// @param apnSymbol Display symbol for the loan's APN token (executor-supplied, cosmetic).\n    /// @return apn The APN token minted for this loan.\n    function execute(bytes32 matchId, ExecutedTerms calldata terms, string calldata apnName, string calldata apnSymbol)\n        external\n        returns (address apn);\n\n    /// @notice Repay up to the loan's current debt, applying the interest-first waterfall: interest is\n    ///         paid first and split between the treasury and the lender (recorded to the APN), the\n    ///         remainder reduces principal. Permissionless (funds pulled from the caller); an amount\n    ///         above the total owed is capped. Releases the collateral once principal reaches zero.\n    ///         Works during a live full-liquidation auction too, letting the borrower de-lever or fully\n    ///         close mid-auction. Interest is charged live for the whole elapsed window in every case, so\n    ///         repaying confers no interest advantage over a healthy loan and a seizure confers none over\n    ///         repaying. A partial payment that restores health clears whatever it cured — a margin call\n    ///         once back below the margin-call threshold, a pre-maturity liquidation trigger once back\n    ///         below the liquidation threshold (best-effort: skipped if the oracle is stale, never\n    ///         blocking the repayment); otherwise the loan stays liquidatable with the auction's bonus\n    ///         clock intact (a maturity default always stays liquidatable).\n    /// @return interestPortion Interest covered by this payment (protocol take + lender interest).\n    /// @return principalPortion Principal repaid by this payment.\n    function repay(bytes32 matchId, uint256 amount) external returns (uint256 interestPortion, uint256 principalPortion);\n\n    /// @notice Increase the loan's denormalized collateral amount by `amount`. Restricted to the\n    ///         CollateralManager, which calls it from {ICollateralManager-addCollateral} after it has\n    ///         custodied the additional collateral, keeping the two records in sync. Like a repayment,\n    ///         a top-up that restores health clears any margin call or pre-maturity liquidation trigger\n    ///         it cured (best-effort: skipped if the oracle is stale, never blocking the top-up).\n    function increaseCollateral(bytes32 matchId, uint256 amount) external;\n\n    /// @notice The not-yet-cash part of a loan's APN net asset value: value the note holders are owed\n    ///         but that has not been repaid into the note yet — outstanding principal plus the lender's\n    ///         mark-to-market accrued-but-unpaid interest (net of the protocol take), in principal base\n    ///         units. The APN prices redemptions as `unrealizedValue + cash on hand`. Goes to zero once\n    ///         principal is fully repaid (all value is then cash) or for an unknown loan.\n    function unrealizedValue(bytes32 matchId) external view returns (uint256);\n\n    /// @notice Open a Zone-2 margin call on a loan whose current LTV has crossed into\n    ///         `[marginCallThreshold, liquidationThreshold)`, starting the grace period. Permissionless.\n    ///         Reverts if the loan is outside that band or already margin-called or in a liquidation auction.\n    function triggerMarginCall(bytes32 matchId) external;\n\n    /// @notice Clear a margin call whose loan has recovered below `marginCallThreshold`, so a later\n    ///         re-crossing starts a fresh grace period. Permissionless.\n    function clearMarginCall(bytes32 matchId) external;\n\n    /// @notice Open a full-liquidation auction, starting the reverse-Dutch bonus clock. Interest keeps\n    ///         accruing live (the auction never pauses it). Valid when current LTV has crossed the\n    ///         liquidation threshold (Zone 3) or the loan is past maturity plus the grace period\n    ///         (maturity default). Permissionless.\n    function triggerLiquidation(bytes32 matchId) external;\n\n    /// @notice Clear a full-liquidation trigger whose loan has recovered below its liquidation threshold\n    ///         and is not past maturity, closing the auction. Interest was never paused, so the window it\n    ///         was open stays billed. Permissionless.\n    function clearLiquidation(bytes32 matchId) external;\n\n    /// @notice Zone-2 partial liquidation after the margin-call grace period: repay up to the amount\n    ///         that restores the position to `MCT - restoreBuffer`, seizing collateral worth the\n    ///         repayment plus the time/distress-scaled bonus. The loan persists — except on the knife\n    ///         edge where the restoring repayment settles the entire debt, which closes the loan and\n    ///         releases any remaining collateral. Permissionless; funds pulled from the caller.\n    ///         `repayAmount` is capped to the restoring maximum and the debt.\n    /// @param minSeized Slippage guard on the receive side, expressed as a RATE quote: the collateral\n    ///        the caller expects for a full `repayAmount` fill. When the engine caps the fill (a\n    ///        smaller live restoring maximum after a competing partial, or the debt), the floor\n    ///        scales pro-rata with the actual `repaid`, so a fairly-priced smaller fill executes and\n    ///        only a worsened exchange rate (price/bonus moved against the caller) reverts. Pass 0\n    ///        to accept any rate.\n    /// @return repaid Principal-token amount actually repaid.\n    /// @return collateralSeized Collateral base units transferred to the caller.\n    function liquidatePartial(bytes32 matchId, uint256 repayAmount, uint256 minSeized)\n        external\n        returns (uint256 repaid, uint256 collateralSeized);\n\n    /// @notice Full liquidation of a triggered loan: repay the live debt — or, if the collateral cannot\n    ///         cover debt plus bonus, as much as the collateral backs, writing down the shortfall — seize\n    ///         the corresponding collateral (bonus included), return any excess to the borrower, and close\n    ///         the loan. Permissionless; funds pulled from the caller. A trigger that predates the\n    ///         maturity default and whose distress has since recovered prices its bonus from the default\n    ///         deadline rather than its stale clock.\n    /// @param maxRepay Slippage guard on the pay side: the largest repayment the caller will make;\n    ///        reverts if the required repayment exceeds it.\n    /// @param minSeized Slippage guard on the receive side: the smallest collateral amount the caller\n    ///        will accept; reverts if the seize comes in below it. Together the two bound the\n    ///        caller's worst-case exchange rate against oracle/bonus movement between submission and\n    ///        inclusion. Pass 0 to accept any seize (required to close a dust debt whose seize\n    ///        rounds to zero).\n    /// @return repaid Principal-token amount actually repaid.\n    /// @return collateralSeized Collateral base units transferred to the caller.\n    function liquidate(bytes32 matchId, uint256 maxRepay, uint256 minSeized)\n        external\n        returns (uint256 repaid, uint256 collateralSeized);\n\n    /// @notice The loan's live gross debt — outstanding principal plus interest accrued to this\n    ///         second (the exact amount a full repayment would settle right now). Zero for an\n    ///         unknown or fully-repaid loan. Pure state read: no oracle involved.\n    function debtOf(bytes32 matchId) external view returns (uint256);\n\n    /// @notice One-read health snapshot for off-chain monitors: live debt, the collateral's value\n    ///         in principal base units at the live oracle price, the current LTV in bps, and the\n    ///         zone. `zone` is trigger eligibility, matching {triggerLiquidation} /\n    ///         {triggerMarginCall} exactly: 2 = liquidatable (LTV ≥ liquidation threshold or past\n    ///         the maturity-default deadline), 1 = margin-call band [MCT, LT), 0 = healthy.\n    ///         All-zero for an unknown or fully-repaid loan. Reverts on a stale or invalid oracle\n    ///         price, like every other health-dependent path — treat a revert as \"no fresh\n    ///         classification available\", never as healthy.\n    function healthOf(bytes32 matchId)\n        external\n        view\n        returns (uint256 debt, uint256 collateralValue, uint256 ltvBps, uint8 zone);\n\n    /// @notice The liquidation-auction state for `matchId` (all-zero if healthy/untriggered).\n    function auctionOf(bytes32 matchId) external view returns (Auction memory);\n\n    /// @notice The global liquidation risk parameters.\n    function riskParams() external view returns (RiskParams memory);\n\n    /// @notice The loan recorded for `matchId` (zeroed if none).\n    function loanOf(bytes32 matchId) external view returns (Loan memory);\n}\n"},"amish-contracts/src/libraries/AuctionMath.sol":{"keccak256":"0x6e7266c657feed7693b3c4f6b2b125ce135d900063fa33f9d0f8e4188fdd9f56","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {Math} from \"@openzeppelin-contracts-5.6.1/utils/math/Math.sol\";\n\nimport {Constants} from \"./Constants.sol\";\n\n/// @title AuctionMath\n/// @notice Pure math for the unified liquidation auction: the reverse-Dutch bonus curve, the two\n///         zone distress metrics, and the partial-liquidation repayment cap. All ratios are basis\n///         points (`Constants.BPS = 10_000 = 100%`); this library is price- and token-agnostic, so\n///         the collateral/value conversions live in {LtvMath}. Amounts (`debt`, `collValue`,\n///         `repay`) are principal base units.\n/// @dev The bonus grows with two independent factors — time since the auction opened and the\n///      position's distress — combined as the probability complement `1 - (1 - t)(1 - d)` so either\n///      alone can drive it to the cap and both together accelerate it. Rounding is chosen to favor\n///      the borrower (a lower bonus, less collateral seized) where a direction must be picked.\nlibrary AuctionMath {\n    /// @notice Elapsed-time fraction of the auction, in bps, capped at 100%.\n    ///         `min(BPS, elapsed * BPS / auctionDuration)`. `auctionDuration` must be non-zero\n    ///         (guaranteed by the protocol-parameter bound).\n    function timePct(uint256 elapsed, uint256 auctionDuration) internal pure returns (uint256) {\n        uint256 t = Math.mulDiv(elapsed, Constants.BPS, auctionDuration);\n        return t > Constants.BPS ? Constants.BPS : t;\n    }\n\n    /// @notice Auction progress in bps from a time fraction and a distress fraction (both bps):\n    ///         `progress = BPS - (BPS - timePct)(BPS - distressPct) / BPS`. Inputs are clamped to\n    ///         [0, BPS]. At (0.5, 0.5) this is 0.75, not 0.5 — both factors compound.\n    function progress(uint256 timePctBps, uint256 distressPctBps) internal pure returns (uint256) {\n        if (timePctBps > Constants.BPS) timePctBps = Constants.BPS;\n        if (distressPctBps > Constants.BPS) distressPctBps = Constants.BPS;\n        // Round the complement up so progress rounds down — a lower bonus, favoring the borrower,\n        // consistent with the rest of this library.\n        uint256 complement =\n            Math.mulDiv(Constants.BPS - timePctBps, Constants.BPS - distressPctBps, Constants.BPS, Math.Rounding.Ceil);\n        return Constants.BPS - complement;\n    }\n\n    /// @notice Zone-2 (margin-call) distress in bps: `(currentLTV - MCT) / (LT - MCT)`, clamped to\n    ///         [0, BPS]. Zero at the MCT boundary, 1 at the LT boundary. Requires `lt > mct`\n    ///         (the per-loan `LTV < MCT < LT` invariant guarantees it).\n    function distressZone2(uint256 currentLtv, uint16 mct, uint16 lt) internal pure returns (uint256) {\n        if (currentLtv <= mct) return 0;\n        uint256 d = Math.mulDiv(currentLtv - mct, Constants.BPS, uint256(lt) - mct);\n        return d > Constants.BPS ? Constants.BPS : d;\n    }\n\n    /// @notice Zone-3 (liquidation) distress in bps: `(1 - HF) / (1 - HF_floor)` with\n    ///         `HF = LT / currentLTV`, clamped to [0, BPS]. Zero as HF crosses 1.0\n    ///         (`currentLTV = LT`), 1 at `HF_floor`. `hfFloor` is a bps ratio in (0, BPS).\n    function distressZone3(uint256 currentLtv, uint16 lt, uint256 hfFloor) internal pure returns (uint256) {\n        // HF as a bps ratio; if the position is not actually past LT, there is no Zone-3 distress.\n        uint256 hf = Math.mulDiv(lt, Constants.BPS, currentLtv);\n        if (hf >= Constants.BPS) return 0;\n        uint256 d = Math.mulDiv(Constants.BPS - hf, Constants.BPS, Constants.BPS - hfFloor);\n        return d > Constants.BPS ? Constants.BPS : d;\n    }\n\n    /// @notice The liquidation bonus in bps for a given progress: `effBmin + (bMax - effBmin) * progress`,\n    ///         where `effBmin = min(bMin, bMax)` so a loan never pays more than its borrower-negotiated\n    ///         cap (`bMax = maxLiquidationBonus`) even if the global `bMin` is raised above it. Rounds\n    ///         down (borrower-favorable).\n    function bonusBps(uint256 bMin, uint16 bMax, uint256 progressBps) internal pure returns (uint256) {\n        uint256 effBmin = bMin < bMax ? bMin : bMax;\n        return effBmin + Math.mulDiv(uint256(bMax) - effBmin, progressBps, Constants.BPS);\n    }\n\n    /// @notice The principal-token value the liquidator claims for repaying `repay`: `repay * (1 + bonus)`.\n    ///         Rounds down so the seized collateral is never rounded up against the borrower. The caller\n    ///         converts this value to collateral base units via {LtvMath-valueToCollateral}.\n    function grossUpValue(uint256 repay, uint256 bonus) internal pure returns (uint256) {\n        return Math.mulDiv(repay, Constants.BPS + bonus, Constants.BPS, Math.Rounding.Floor);\n    }\n\n    /// @notice Largest repayment (principal base units) that restores a Zone-2 position to\n    ///         `targetLtvBps` while paying the liquidator `bonus`:\n    ///\n    ///           maxRepay = (debt - targetLtv * collValue) / (1 - targetLtv * (1 + bonus))\n    ///\n    ///         Returns 0 if the position is already at/below the target (nothing to do). If the\n    ///         denominator is non-positive the target is mathematically unreachable at this bonus\n    ///         (only with an atypically high target LTV); it returns `debt` and the caller caps the\n    ///         repay to the debt and available collateral. Rounds down.\n    /// @param debt Current debt (outstanding principal + accrued interest).\n    /// @param collValue Collateral value in principal base units at the current price.\n    /// @param targetLtvBps Target LTV to restore to (`MCT - restoreBuffer`), bps.\n    /// @param bonus Auction bonus, bps.\n    function partialMaxRepay(uint256 debt, uint256 collValue, uint16 targetLtvBps, uint256 bonus)\n        internal\n        pure\n        returns (uint256)\n    {\n        uint256 targetValue = Math.mulDiv(targetLtvBps, collValue, Constants.BPS); // targetLtv * collValue\n        if (debt <= targetValue) return 0; // already at or below target — no liquidation needed\n\n        uint256 bb = Constants.BPS * Constants.BPS; // BPS^2\n        uint256 sub = uint256(targetLtvBps) * (Constants.BPS + bonus); // targetLtv * (1 + bonus), BPS^2-scaled\n        if (sub >= bb) return debt; // denominator <= 0: target unreachable, let the caller cap\n\n        return Math.mulDiv(debt - targetValue, bb, bb - sub);\n    }\n}\n"},"amish-contracts/src/libraries/Constants.sol":{"keccak256":"0x02991e785dd961a7862945ff0087653a8a4a315ec68c7b2726b34779ca57a6e2","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title Constants\n/// @notice Protocol-wide constants and the `bytes32` tags used inside signed intents.\n/// @dev All rates/thresholds are basis points: `BPS = 10_000` is 100%. Interest math uses\n///      simple (non-compounding) accrual over `SECONDS_PER_YEAR`.\nlibrary Constants {\n    /// @notice Basis-points denominator. 10_000 bps = 100%.\n    uint256 internal constant BPS = 10_000;\n\n    /// @notice Seconds in a year used for interest accrual (365 days = 31_536_000).\n    uint256 internal constant SECONDS_PER_YEAR = 365 days;\n\n    /// @notice `intentType` tag for a borrow intent.\n    bytes32 internal constant INTENT_TYPE_BORROW = keccak256(\"BORROW\");\n\n    /// @notice `intentType` tag for a lend intent.\n    bytes32 internal constant INTENT_TYPE_LEND = keccak256(\"LEND\");\n\n    /// @notice `rateType` tag for a fixed-rate intent.\n    bytes32 internal constant RATE_TYPE_FIXED = keccak256(\"FIXED\");\n\n    /// @notice `rateType` tag for a variable-rate intent.\n    bytes32 internal constant RATE_TYPE_VARIABLE = keccak256(\"VARIABLE\");\n}\n"},"amish-contracts/src/libraries/InterestMath.sol":{"keccak256":"0x564a61bf3ae7f388b6187757ac61be98af52cfa1530d6d1ea63263acc2afc6c7","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {Math} from \"@openzeppelin-contracts-5.6.1/utils/math/Math.sol\";\n\nimport {Constants} from \"./Constants.sol\";\n\n/// @title InterestMath\n/// @notice Simple (non-compounding) interest accrual. Interest is computed on-the-fly from the loan's\n///         stored `outstandingPrincipal`, `rate`, and `lastAccrualTimestamp` — there is no stored\n///         `accruedInterest`. The debt at any second is `outstandingPrincipal + accrued(...)`.\n/// @dev Rounds up: a borderline position reads as marginally more indebted, which is conservative for\n///      the lender both when servicing (interest is paid before principal) and when the same figure\n///      feeds the health-factor check at margin-call / liquidation time.\nlibrary InterestMath {\n    /// @notice Interest accrued on `outstandingPrincipal` at `rate` (annual, bps) over `elapsed`\n    ///         seconds, in principal base units.\n    ///         `accrued = outstandingPrincipal * rate * elapsed / (BPS * SECONDS_PER_YEAR)`.\n    /// @dev `rate` (uint16 bps) and `elapsed` are small enough that `rate * elapsed` cannot overflow;\n    ///      `Math.mulDiv` carries the `outstandingPrincipal * (rate * elapsed)` product at full width.\n    function accrued(uint256 outstandingPrincipal, uint16 rate, uint256 elapsed) internal pure returns (uint256) {\n        return Math.mulDiv(\n            outstandingPrincipal,\n            uint256(rate) * elapsed,\n            Constants.BPS * Constants.SECONDS_PER_YEAR,\n            Math.Rounding.Ceil\n        );\n    }\n}\n"},"amish-contracts/src/libraries/LtvMath.sol":{"keccak256":"0xa94df8bd1ef9ba8d7ef57a11e453f75b8f7ce703d30b7efc0985672e415b6518","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {Math} from \"@openzeppelin-contracts-5.6.1/utils/math/Math.sol\";\n\nimport {Constants} from \"./Constants.sol\";\n\n/// @title LtvMath\n/// @notice Pure loan-to-value math. External oracle prices follow the `IAmishOracle` convention —\n///         value of one *whole* collateral token in *whole* principal tokens, scaled by\n///         `10 ** priceDecimals` (fixed per adapter, Chainlink-style). {normalizePrice} converts that\n///         into the internal price used by the rest of the library: principal base units per collateral\n///         base unit, PRECISION-scaled — folding the price/collateral/principal decimals in one place so the\n///         valuation functions stay decimal-free. All amounts are token base units; LTV is basis\n///         points. Rounding is chosen to stay conservative for the lender.\nlibrary LtvMath {\n    /// @dev The internal normalized price carries 18 decimals of fixed-point precision. Internal to\n    ///      this library only — not part of the oracle interface.\n    uint256 internal constant PRECISION = 1e18;\n\n    /// @dev Largest token/oracle decimal count the valuation math accepts. Real ERC-20s and price feeds\n    ///      are <= 18; 30 leaves head-room while keeping every power-of-ten below the uint256 overflow\n    ///      cliff — `10^(30+18)` (principal * PRECISION) and `10^(30+30)` (price * collateral) both fit\n    ///      with wide margin — so the decimal terms in {normalizePrice} can never overflow.\n    uint8 internal constant MAX_DECIMALS = 30;\n\n    /// @notice A token or oracle reported more decimals than {MAX_DECIMALS}; unsupported.\n    error LtvMath_DecimalsOutOfRange();\n\n    /// @notice Reject a match whose token/oracle decimals fall outside the supported range. Checked\n    ///         once at loan creation: a token's decimals and its oracle's decimals are fixed for the\n    ///         life of a match, and both are denormalized into the loan, so the hot-path valuation\n    ///         (which re-runs {normalizePrice} on every interaction) needs no repeat check.\n    function validateDecimals(uint8 priceDecimals, uint8 collateralDecimals, uint8 principalDecimals) internal pure {\n        if (priceDecimals > MAX_DECIMALS || collateralDecimals > MAX_DECIMALS || principalDecimals > MAX_DECIMALS) {\n            revert LtvMath_DecimalsOutOfRange();\n        }\n    }\n\n    /// @notice Convert an adapter price into the internal normalized price (principal base units per\n    ///         collateral base unit, PRECISION-scaled), applying the price and both tokens' decimals.\n    ///         Rounds down. `priceDecimals`/`collateralDecimals`/`principalDecimals` are token/adapter\n    ///         constants small enough that `10 ** d` cannot overflow.\n    function normalizePrice(uint256 price, uint8 priceDecimals, uint8 collateralDecimals, uint8 principalDecimals)\n        internal\n        pure\n        returns (uint256)\n    {\n        // Rebase the whole-token price into principal base units per collateral base unit, then scale\n        // by PRECISION so the fractional ratio survives as an integer:\n        //   price / 10^priceDec  (whole principal per whole collateral)\n        //     * 10^principalDec / 10^collateralDec  (whole -> base units on each side)\n        //     * PRECISION\n        return\n            Math.mulDiv(\n                price, (10 ** principalDecimals) * PRECISION, (10 ** priceDecimals) * (10 ** collateralDecimals)\n            );\n    }\n\n    /// @notice Value of `collateralAmount` (base units) in principal base units, given a normalized\n    ///         price. Rounds down, so a borderline position is never valued higher than the feed\n    ///         supports.\n    function collateralValue(uint256 collateralAmount, uint256 normalizedPrice) internal pure returns (uint256) {\n        return Math.mulDiv(collateralAmount, normalizedPrice, PRECISION);\n    }\n\n    /// @notice Collateral amount (base units) worth `value` principal base units at `normalizedPrice`,\n    ///         the inverse of {collateralValue}. Rounds down, so the amount seized to cover a given\n    ///         value is never rounded up against the borrower. `normalizedPrice` must be non-zero.\n    function valueToCollateral(uint256 value, uint256 normalizedPrice) internal pure returns (uint256) {\n        return Math.mulDiv(value, PRECISION, normalizedPrice, Math.Rounding.Floor);\n    }\n\n    /// @notice Loan-to-value in bps for `debt` against `collValue` (both in principal base units).\n    ///         Rounds up, so a borderline position reads as slightly more leveraged. `collValue` must\n    ///         be non-zero (the caller rejects a zero price upstream).\n    function ltvBps(uint256 debt, uint256 collValue) internal pure returns (uint256) {\n        return Math.mulDiv(debt, Constants.BPS, collValue, Math.Rounding.Ceil);\n    }\n\n    /// @notice Smallest collateral amount (base units) that opens a `debt` position at or below\n    ///         `targetLtvBps` at the given normalized price. The exact inverse of {collateralValue},\n    ///         rounded up so the locked collateral never leaves the position above the target.\n    ///         `targetLtvBps` and `normalizedPrice` must be non-zero.\n    function collateralForLtv(uint256 debt, uint16 targetLtvBps, uint256 normalizedPrice)\n        internal\n        pure\n        returns (uint256)\n    {\n        uint256 neededValue = Math.mulDiv(debt, Constants.BPS, targetLtvBps, Math.Rounding.Ceil);\n        return Math.mulDiv(neededValue, PRECISION, normalizedPrice, Math.Rounding.Ceil);\n    }\n}\n"},"amish-contracts/src/libraries/OracleLib.sol":{"keccak256":"0x9a3234cae235b88c621b96786829ce27a177be7241790fa6e97a86dc162c2177","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\nimport {IAmishOracle} from \"../interfaces/IAmishOracle.sol\";\n\n/// @title OracleLib\n/// @notice Shared reader for `IAmishOracle` adapters: fetches the collateral price, rejects a zero\n///         price and a feed older than `maxStaleness`, and returns the adapter's fixed price decimals\n///         alongside it. Used at loan creation (opening-health check) and again on the principal chain\n///         when health is recomputed for margin call / liquidation, so the read lives in one place.\nlibrary OracleLib {\n    error OracleLib_InvalidPrice();\n    error OracleLib_StalePrice();\n\n    /// @notice Read and validate the price of `collateralToken` in `principalToken` from `oracle`.\n    /// @param maxStaleness Maximum age (seconds) of the feed's last update relative to `block.timestamp`.\n    /// @return price Whole-collateral price in whole-principal units at `10 ** priceDecimals` scale.\n    /// @return priceDecimals The adapter's fixed price decimals.\n    function readPrice(address oracle, address collateralToken, address principalToken, uint32 maxStaleness)\n        internal\n        view\n        returns (uint256 price, uint8 priceDecimals)\n    {\n        uint256 updatedAt;\n        (price, updatedAt) = IAmishOracle(oracle).getPrice(collateralToken, principalToken);\n        if (price == 0) revert OracleLib_InvalidPrice();\n        if (block.timestamp > updatedAt + maxStaleness) revert OracleLib_StalePrice();\n        priceDecimals = IAmishOracle(oracle).decimals();\n    }\n\n    /// @notice Best-effort variant of {readPrice}: reports failure instead of reverting when the\n    ///         adapter reverts, the price is zero, or the feed is stale. For callers that only\n    ///         opportunistically refresh state off the price (e.g. clearing a cured margin call\n    ///         during a repayment) and must never let a dead feed block their primary action.\n    /// @return ok False if no valid, fresh price could be read; `price`/`priceDecimals` are zero then.\n    function tryReadPrice(address oracle, address collateralToken, address principalToken, uint32 maxStaleness)\n        internal\n        view\n        returns (bool ok, uint256 price, uint8 priceDecimals)\n    {\n        try IAmishOracle(oracle).getPrice(collateralToken, principalToken) returns (uint256 p, uint256 updatedAt) {\n            if (p == 0 || block.timestamp > updatedAt + maxStaleness) return (false, 0, 0);\n            price = p;\n        } catch {\n            return (false, 0, 0);\n        }\n        try IAmishOracle(oracle).decimals() returns (uint8 d) {\n            return (true, price, d);\n        } catch {\n            return (false, 0, 0);\n        }\n    }\n}\n"},"amish-contracts/src/libraries/Roles.sol":{"keccak256":"0x36096857f4a53adbcdc42b7cff63c8a3e67c07d412938039b38fd1e9fe1818f9","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title Roles\n/// @notice Central definitions of the AccessControl role identifiers used across Amish\n///         contracts. Keeping them in one place avoids typos and gives auditors a single\n///         surface for the privilege model. `DEFAULT_ADMIN_ROLE` (0x00, from OZ AccessControl)\n///         is the admin of every role below and is what grants/revokes them.\n/// @dev Roles are per-contract in AccessControl: granting a role on one contract does not grant\n///      it on another. Additional roles (e.g. executor, pauser) are added here as the contracts\n///      that need them are built.\nlibrary Roles {\n    /// @notice May configure per-token fees and the treasury on FeeRegistry.\n    bytes32 internal constant FEE_MANAGER_ROLE = keccak256(\"FEE_MANAGER_ROLE\");\n\n    /// @notice May tune the global liquidation risk parameters on LoanManager (bonus curve, auction\n    ///         duration, grace periods, restore buffer). Every value is range-bounded in code, so this\n    ///         role can adjust the auction's shape but cannot make an otherwise-healthy loan seizable.\n    bytes32 internal constant RISK_MANAGER_ROLE = keccak256(\"RISK_MANAGER_ROLE\");\n\n    /// @notice May authorize UUPS implementation upgrades on any upgradeable Amish singleton.\n    ///         Held by a Timelock in production.\n    bytes32 internal constant UPGRADER_ROLE = keccak256(\"UPGRADER_ROLE\");\n\n    /// @notice May submit matched intents to AmishHub for execution. Team-operated and rotatable;\n    ///         a policy gate for best-execution, not a safety mechanism (the Hub verifies everything).\n    bytes32 internal constant EXECUTOR_ROLE = keccak256(\"EXECUTOR_ROLE\");\n\n    /// @notice May list new price routes on ChainlinkOracle and propose/execute/cancel timelocked\n    ///         updates to existing ones. Listing a new pair is immediate (nothing depends on it yet);\n    ///         changing a live pair's route is delayed by the contract's built-in timelock, so this\n    ///         role can never reprice existing loans without notice.\n    bytes32 internal constant ORACLE_MANAGER_ROLE = keccak256(\"ORACLE_MANAGER_ROLE\");\n}\n"},"amish-contracts/src/types/DataTypes.sol":{"keccak256":"0x04065c54a39346ea76b9231250d9ad9e2c5c3a1e270df9ce87f890e17221f6a2","license":"MIT","content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.30;\n\n/// @title DataTypes\n/// @notice Core data structures for Amish intents. Pure data — no logic lives here.\n/// @dev The signed message (`LendingIntent`) is intentionally flat: the collateral and rules\n///      arrays are committed as `bytes32` hashes so the EIP-712 struct stays cheap to hash, while\n///      their full contents are passed alongside at execution and re-hashed on-chain to verify\n///      they match the signature. Chain-id fields are carried so the signed format never has to\n///      change if collateral and principal settle on different chains.\n\n/// @notice Per-collateral risk & pricing terms. One market = one (collateral, principal,\n///         oracle, rateType) tuple, so each collateral entry prices its own risk.\n/// @dev `intentType`/`rateType` equivalents are represented as `bytes32` tags elsewhere;\n///      here `rateType` is the tag the creator signed over. Invariant per entry:\n///      `ltv < marginCallThreshold < liquidationThreshold` (all in bps).\nstruct CollateralEntry {\n    address token; // ERC-20 collateral token\n    uint256 chainId; // chain where the collateral lives\n    uint256 amount; // collateral amount, token base units\n    address oracleAddress; // IAmishOracle adapter on the principal chain\n    bytes32 oracleType; // oracle source tag (e.g. keccak256(\"CHAINLINK\"))\n    uint32 maxStaleness; // max acceptable oracle update age, seconds\n    uint16 ltv; // loan-to-value, bps\n    uint16 marginCallThreshold; // MCT, bps — must be > ltv and < liquidationThreshold\n    uint16 liquidationThreshold; // LT, bps\n    uint16 maxLiquidationBonus; // reverse-Dutch-auction cap, bps\n    uint16 rate; // annual interest rate, bps (BORROW: max pay / LEND: min accept)\n    bytes32 rateType; // interest-rate mode tag (FIXED or VARIABLE)\n    address variableRateIndex; // rate index for VARIABLE mode; zero for FIXED\n}\n\n/// @notice A compliance rule attached to an intent. The module address is the type id;\n///         `params` is ABI-encoded per-intent config. Empty rules = permissionless.\nstruct Rule {\n    address module; // IRuleModule contract\n    bytes params; // ABI-encoded config for this module\n}\n\n/// @notice The flat, EIP-712-signed intent. `collateralHash`/`rulesHash` commit the\n///         off-chain arrays; the signer binds them without paying nested-hash gas.\n/// @dev `intentType` is a tag: keccak256(\"BORROW\") or keccak256(\"LEND\").\n///      `principalAmount` is the full size; partial fills are tracked off this via\n///      fill-accounting keyed by the intent hash.\n///      `minFillAmount` is the smallest acceptable single fill (dust guard); a fill that\n///      closes the intent out is always allowed regardless.\nstruct LendingIntent {\n    bytes32 intentType; // keccak256(\"BORROW\") | keccak256(\"LEND\")\n    address creator; // intent signer\n    uint256 nonce; // distinguishes otherwise-identical intents / cancellation target\n    uint256 deadline; // expiry, unix seconds — no fills after this\n    address principalToken; // loan asset\n    uint256 principalChainId; // chain where the principal is issued (settlement chain)\n    uint256 principalAmount; // full principal, token base units\n    uint256 minFillAmount; // minimum acceptable single fill (0 = no floor)\n    bytes32 collateralHash; // commitment to CollateralEntry[] (see IntentHash)\n    uint256 duration; // loan duration, seconds — must match exactly between sides\n    bool partialFill; // false = all-or-nothing (fill must equal principalAmount)\n    bytes32 rulesHash; // commitment to Rule[] (see IntentHash)\n    bool apnTransferable; // false = APN soulbound to original lender\n    bool strict; // collateral model (borrower-authoritative): see below\n}\n\n// `strict` selects how a borrower's collateral backs a (possibly partial) fill, and which of the\n// two leverage representations in the intent is authoritative:\n//   - strict = true: the signed `amount`/`principalAmount` are authoritative. Collateral is locked\n//     pro-rata to the fill; the resulting LTV floats with the collateral price, and a match that\n//     would open at or beyond the margin-call threshold is rejected. Never locks more than the\n//     signed proportional share.\n//   - strict = false: the signed `ltv` is authoritative and `amount`/`principalAmount` are caps.\n//     Collateral is sized to open the loan at the target `ltv` given the live price (drawn from the\n//     borrower's available collateral, up to `amount`); the position is healthy by construction.\n//     A falling price makes each fill consume more collateral, so the pool can be exhausted before\n//     the full principal is filled — the unfillable remainder simply never matches.\n// The field lives on every intent but is only consulted for the borrower (the collateral provider);\n// a lender's value is ignored on-chain.\n\n/// @notice The finalized loan terms derived on-chain from a matched borrow/lend pair. Every field\n///         is computed from the two signed intents and the matched fill amount, then consumed by\n///         the managers to lock collateral, move principal, and record the loan.\nstruct ExecutedTerms {\n    address borrower;\n    address lender;\n    // Collateral (denormalized so the loan can be valued without a cross-contract read)\n    address collateralToken;\n    uint256 collateralChainId;\n    uint256 collateralAmount; // pro-rata share of the borrower's collateral for this fill\n    uint8 collateralDecimals; // collateral token decimals, denormalized (may be a remote token)\n    address oracle;\n    bytes32 oracleType;\n    uint32 maxStaleness;\n    uint16 ltv;\n    uint16 marginCallThreshold;\n    uint16 liquidationThreshold;\n    uint16 maxLiquidationBonus;\n    uint16 rate;\n    bytes32 rateType;\n    // Principal\n    address principalToken;\n    uint256 principalChainId;\n    uint256 principalAmount; // the matched fill amount\n    // Loan\n    uint256 duration;\n    bool apnTransferable;\n}\n"}},"version":1}