{"abi":[{"type":"constructor","inputs":[{"name":"usdai_","type":"address","internalType":"address"},{"name":"loanRouterV2_","type":"address","internalType":"address"},{"name":"adminFeeRecipient_","type":"address","internalType":"address"},{"name":"genesisTimestamp_","type":"uint64","internalType":"uint64"},{"name":"baseYieldAdminFeeRate_","type":"uint256","internalType":"uint256"},{"name":"loanRouterAdminFeeRate_","type":"uint256","internalType":"uint256"},{"name":"bridgeAdapter_","type":"address","internalType":"address"}],"stateMutability":"nonpayable"},{"name":"AccessControlBadConfirmation","type":"error","inputs":[]},{"name":"AccessControlUnauthorizedAccount","type":"error","inputs":[{"name":"account","type":"address","internalType":"address"},{"name":"neededRole","type":"bytes32","internalType":"bytes32"}]},{"name":"AddressEmptyCode","type":"error","inputs":[{"name":"target","type":"address","internalType":"address"}]},{"name":"BlacklistedAddress","type":"error","inputs":[{"name":"value","type":"address","internalType":"address"}]},{"name":"DisabledImplementation","type":"error","inputs":[]},{"name":"ECDSAInvalidSignature","type":"error","inputs":[]},{"name":"ECDSAInvalidSignatureLength","type":"error","inputs":[{"name":"length","type":"uint256","internalType":"uint256"}]},{"name":"ECDSAInvalidSignatureS","type":"error","inputs":[{"name":"s","type":"bytes32","internalType":"bytes32"}]},{"name":"ERC20InsufficientAllowance","type":"error","inputs":[{"name":"spender","type":"address","internalType":"address"},{"name":"allowance","type":"uint256","internalType":"uint256"},{"name":"needed","type":"uint256","internalType":"uint256"}]},{"name":"ERC20InsufficientBalance","type":"error","inputs":[{"name":"sender","type":"address","internalType":"address"},{"name":"balance","type":"uint256","internalType":"uint256"},{"name":"needed","type":"uint256","internalType":"uint256"}]},{"name":"ERC20InvalidApprover","type":"error","inputs":[{"name":"approver","type":"address","internalType":"address"}]},{"name":"ERC20InvalidReceiver","type":"error","inputs":[{"name":"receiver","type":"address","internalType":"address"}]},{"name":"ERC20InvalidSender","type":"error","inputs":[{"name":"sender","type":"address","internalType":"address"}]},{"name":"ERC20InvalidSpender","type":"error","inputs":[{"name":"spender","type":"address","internalType":"address"}]},{"name":"ERC2612ExpiredSignature","type":"error","inputs":[{"name":"deadline","type":"uint256","internalType":"uint256"}]},{"name":"ERC2612InvalidSigner","type":"error","inputs":[{"name":"signer","type":"address","internalType":"address"},{"name":"owner","type":"address","internalType":"address"}]},{"name":"EnforcedPause","type":"error","inputs":[]},{"name":"ExpectedPause","type":"error","inputs":[]},{"name":"FailedCall","type":"error","inputs":[]},{"name":"InsufficientBalance","type":"error","inputs":[]},{"name":"InvalidAccountNonce","type":"error","inputs":[{"name":"account","type":"address","internalType":"address"},{"name":"currentNonce","type":"uint256","internalType":"uint256"}]},{"name":"InvalidAddress","type":"error","inputs":[]},{"name":"InvalidAmount","type":"error","inputs":[]},{"name":"InvalidCaller","type":"error","inputs":[]},{"name":"InvalidInitialization","type":"error","inputs":[]},{"name":"InvalidRedemptionState","type":"error","inputs":[]},{"name":"InvalidTimelockCancellation","type":"error","inputs":[]},{"name":"NotInitializing","type":"error","inputs":[]},{"name":"ReentrancyGuardReentrantCall","type":"error","inputs":[]},{"name":"SafeERC20FailedOperation","type":"error","inputs":[{"name":"token","type":"address","internalType":"address"}]},{"name":"Approval","type":"event","inputs":[{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"spender","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"BaseYieldDeposited","type":"event","inputs":[{"name":"depositedAmount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"adminFee","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"Deposit","type":"event","inputs":[{"name":"sender","type":"address","indexed":true,"internalType":"address"},{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"assets","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"shares","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"EIP712DomainChanged","type":"event","inputs":[],"anonymous":false},{"name":"Initialized","type":"event","inputs":[{"name":"version","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"name":"LoanDepositTimelockCancelled","type":"event","inputs":[{"name":"loanTermsHash","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"usdaiAmount","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"LoanDepositTimelockDeposited","type":"event","inputs":[{"name":"loanTermsHash","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"usdaiAmount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"expiration","type":"uint64","indexed":false,"internalType":"uint64"}],"anonymous":false},{"name":"LoanEscrowTimelockCancelled","type":"event","inputs":[{"name":"loanTermsHash","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"usdaiAmount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"interestAmount","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"LoanEscrowTimelockDeposited","type":"event","inputs":[{"name":"loanTermsHash","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"usdaiAmount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"interestRate","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"LoanEscrowTimelockWithdrawn","type":"event","inputs":[{"name":"loanTermsHash","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"interestAmount","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"OperatorSet","type":"event","inputs":[{"name":"controller","type":"address","indexed":true,"internalType":"address"},{"name":"operator","type":"address","indexed":true,"internalType":"address"},{"name":"approved","type":"bool","indexed":false,"internalType":"bool"}],"anonymous":false},{"name":"Paused","type":"event","inputs":[{"name":"account","type":"address","indexed":false,"internalType":"address"}],"anonymous":false},{"name":"RedeemRequest","type":"event","inputs":[{"name":"controller","type":"address","indexed":true,"internalType":"address"},{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"requestId","type":"uint256","indexed":true,"internalType":"uint256"},{"name":"sender","type":"address","indexed":false,"internalType":"address"},{"name":"shares","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"RedemptionProcessed","type":"event","inputs":[{"name":"redemptionId","type":"uint256","indexed":true,"internalType":"uint256"},{"name":"controller","type":"address","indexed":true,"internalType":"address"},{"name":"fulfilledShares","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"pendingShares","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"RedemptionsServiced","type":"event","inputs":[{"name":"shares","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"amount","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"allRedemptionsServiced","type":"bool","indexed":false,"internalType":"bool"}],"anonymous":false},{"name":"ReferredDeposit","type":"event","inputs":[{"name":"sender","type":"address","indexed":true,"internalType":"address"},{"name":"receiver","type":"address","indexed":true,"internalType":"address"},{"name":"assets","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"shares","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"referral","type":"uint16","indexed":false,"internalType":"uint16"}],"anonymous":false},{"name":"RoleAdminChanged","type":"event","inputs":[{"name":"role","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"previousAdminRole","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"newAdminRole","type":"bytes32","indexed":true,"internalType":"bytes32"}],"anonymous":false},{"name":"RoleGranted","type":"event","inputs":[{"name":"role","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"account","type":"address","indexed":true,"internalType":"address"},{"name":"sender","type":"address","indexed":true,"internalType":"address"}],"anonymous":false},{"name":"RoleRevoked","type":"event","inputs":[{"name":"role","type":"bytes32","indexed":true,"internalType":"bytes32"},{"name":"account","type":"address","indexed":true,"internalType":"address"},{"name":"sender","type":"address","indexed":true,"internalType":"address"}],"anonymous":false},{"name":"Transfer","type":"event","inputs":[{"name":"from","type":"address","indexed":true,"internalType":"address"},{"name":"to","type":"address","indexed":true,"internalType":"address"},{"name":"value","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"Unpaused","type":"event","inputs":[{"name":"account","type":"address","indexed":false,"internalType":"address"}],"anonymous":false},{"name":"Withdraw","type":"event","inputs":[{"name":"sender","type":"address","indexed":true,"internalType":"address"},{"name":"receiver","type":"address","indexed":true,"internalType":"address"},{"name":"owner","type":"address","indexed":true,"internalType":"address"},{"name":"assets","type":"uint256","indexed":false,"internalType":"uint256"},{"name":"shares","type":"uint256","indexed":false,"internalType":"uint256"}],"anonymous":false},{"name":"DEFAULT_ADMIN_ROLE","type":"function","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"name":"DOMAIN_SEPARATOR","type":"function","inputs":[],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"name":"IMPLEMENTATION_VERSION","type":"function","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"name":"accrualRate","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"adminFeeRecipient","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"allowance","type":"function","inputs":[{"name":"owner","type":"address","internalType":"address"},{"name":"spender","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"approve","type":"function","inputs":[{"name":"spender","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"name":"asset","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"balanceOf","type":"function","inputs":[{"name":"account","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"balances","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"},{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"bridgedSupply","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"burn","type":"function","inputs":[{"name":"from","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"cancelLoanDepositTimelock","type":"function","inputs":[{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"cancelLoanEscrowTimelock","type":"function","inputs":[{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"claimableBaseYield","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"claimableRedeemRequest","type":"function","inputs":[{"name":"redemptionId","type":"uint256","internalType":"uint256"},{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"convertToAssets","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"convertToShares","type":"function","inputs":[{"name":"assets","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"decimals","type":"function","inputs":[],"outputs":[{"name":"","type":"uint8","internalType":"uint8"}],"stateMutability":"view"},{"name":"deposit","type":"function","inputs":[{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"},{"name":"minShares","type":"uint256","internalType":"uint256"},{"name":"referral","type":"uint16","internalType":"uint16"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"deposit","type":"function","inputs":[{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"deposit","type":"function","inputs":[{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"},{"name":"minShares","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"depositLoanDepositTimelock","type":"function","inputs":[{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"usdaiAmount","type":"uint256","internalType":"uint256"},{"name":"expiration","type":"uint64","internalType":"uint64"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"depositLoanEscrowTimelock","type":"function","inputs":[{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"usdaiAmount","type":"uint256","internalType":"uint256"},{"name":"interestRate","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"depositSharePrice","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"depositTimelockBalance","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"eip712Domain","type":"function","inputs":[],"outputs":[{"name":"fields","type":"bytes1","internalType":"bytes1"},{"name":"name","type":"string","internalType":"string"},{"name":"version","type":"string","internalType":"string"},{"name":"chainId","type":"uint256","internalType":"uint256"},{"name":"verifyingContract","type":"address","internalType":"address"},{"name":"salt","type":"bytes32","internalType":"bytes32"},{"name":"extensions","type":"uint256[]","internalType":"uint256[]"}],"stateMutability":"view"},{"name":"getRoleAdmin","type":"function","inputs":[{"name":"role","type":"bytes32","internalType":"bytes32"}],"outputs":[{"name":"","type":"bytes32","internalType":"bytes32"}],"stateMutability":"view"},{"name":"grantRole","type":"function","inputs":[{"name":"role","type":"bytes32","internalType":"bytes32"},{"name":"account","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"harvestBaseYield","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"},{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"hasRole","type":"function","inputs":[{"name":"role","type":"bytes32","internalType":"bytes32"},{"name":"account","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"name":"initialize","type":"function","inputs":[{"name":"admin","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"isOperator","type":"function","inputs":[{"name":"controller","type":"address","internalType":"address"},{"name":"operator","type":"address","internalType":"address"}],"outputs":[{"name":"status","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"name":"loanRouterBalances","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"},{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"maxDeposit","type":"function","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"pure"},{"name":"maxMint","type":"function","inputs":[{"name":"","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"pure"},{"name":"maxRedeem","type":"function","inputs":[{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"maxWithdraw","type":"function","inputs":[{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"mint","type":"function","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"mint","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"},{"name":"maxAmount","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"mint","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"}],"outputs":[{"name":"assets","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"multicall","type":"function","inputs":[{"name":"data","type":"bytes[]","internalType":"bytes[]"}],"outputs":[{"name":"results","type":"bytes[]","internalType":"bytes[]"}],"stateMutability":"nonpayable"},{"name":"name","type":"function","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"name":"nav","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"nonces","type":"function","inputs":[{"name":"owner","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"onDepositWithdrawn","type":"function","inputs":[{"name":"","type":"address","internalType":"address"},{"name":"","type":"bytes32","internalType":"bytes32"},{"name":"","type":"address","internalType":"address"},{"name":"","type":"uint256","internalType":"uint256"},{"name":"","type":"uint256","internalType":"uint256"},{"name":"refundDepositAmount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onERC721Received","type":"function","inputs":[{"name":"","type":"address","internalType":"address"},{"name":"","type":"address","internalType":"address"},{"name":"","type":"uint256","internalType":"uint256"},{"name":"","type":"bytes","internalType":"bytes"}],"outputs":[{"name":"","type":"bytes4","internalType":"bytes4"}],"stateMutability":"pure"},{"name":"onEscrowWithdrawn","type":"function","inputs":[{"name":"","type":"address","internalType":"address"},{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"","type":"address","internalType":"address"},{"name":"","type":"uint256","internalType":"uint256"},{"name":"interestAmount","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onLoanCollateralLiquidated","type":"function","inputs":[{"name":"loanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"trancheIndex","type":"uint8","internalType":"uint8"},{"name":"principal","type":"uint256","internalType":"uint256"},{"name":"interest","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onLoanFeePaid","type":"function","inputs":[{"name":"loanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"feeSpecIndex","type":"uint8","internalType":"uint8"},{"name":"fee","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onLoanLiquidated","type":"function","inputs":[{"name":"loanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"trancheIndex","type":"uint8","internalType":"uint8"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onLoanOriginated","type":"function","inputs":[{"name":"loanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"trancheIndex","type":"uint8","internalType":"uint8"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onLoanRefinanced","type":"function","inputs":[{"name":"oldLoanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"newLoanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"oldLoanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"newLoanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"trancheIndex","type":"uint8","internalType":"uint8"},{"name":"cashOut","type":"uint256","internalType":"uint256"},{"name":"cashIn","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"onLoanRepayment","type":"function","inputs":[{"name":"loanTerms","type":"tuple","components":[{"name":"expiration","type":"uint64","internalType":"uint64"},{"name":"borrower","type":"address","internalType":"address"},{"name":"currencyToken","type":"address","internalType":"address"},{"name":"collateralToken","type":"address","internalType":"address"},{"name":"repaymentSpec","type":"tuple","components":[{"name":"totalDurationDays","type":"uint16","internalType":"uint16"},{"name":"day","type":"uint8","internalType":"uint8"},{"name":"timezoneOffsetSeconds","type":"int32","internalType":"int32"}],"internalType":"struct ILoanRouterV2.RepaymentSpec"},{"name":"interestRateSpec","type":"tuple","components":[{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.InterestRateSpec"},{"name":"collateralTokenIds","type":"uint256[]","internalType":"uint256[]"},{"name":"trancheSpecs","type":"tuple[]","components":[{"name":"lender","type":"address","internalType":"address"},{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"rate","type":"uint256","internalType":"uint256"}],"internalType":"struct ILoanRouterV2.TrancheSpec[]"},{"name":"feeSpecs","type":"tuple[]","components":[{"name":"kind","type":"uint8","internalType":"enum ILoanRouterV2.FeeKind"},{"name":"recipient","type":"address","internalType":"address"},{"name":"model","type":"address","internalType":"address"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.FeeSpec[]"},{"name":"approvalAddresses","type":"address[]","internalType":"address[]"},{"name":"options","type":"bytes","internalType":"bytes"}],"internalType":"struct ILoanRouterV2.LoanTermsV2"},{"name":"loanTermsHash","type":"bytes32","internalType":"bytes32"},{"name":"trancheIndex","type":"uint8","internalType":"uint8"},{"name":"loanBalance","type":"uint256","internalType":"uint256"},{"name":"principal","type":"uint256","internalType":"uint256"},{"name":"interest","type":"uint256","internalType":"uint256"},{"name":"prepayment","type":"uint256","internalType":"uint256"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"pause","type":"function","inputs":[],"outputs":[],"stateMutability":"nonpayable"},{"name":"paused","type":"function","inputs":[],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"name":"pendingRedeemRequest","type":"function","inputs":[{"name":"redemptionId","type":"uint256","internalType":"uint256"},{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"permit","type":"function","inputs":[{"name":"owner","type":"address","internalType":"address"},{"name":"spender","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"},{"name":"deadline","type":"uint256","internalType":"uint256"},{"name":"v","type":"uint8","internalType":"uint8"},{"name":"r","type":"bytes32","internalType":"bytes32"},{"name":"s","type":"bytes32","internalType":"bytes32"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"previewDeposit","type":"function","inputs":[{"name":"assets","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"previewMint","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"previewRedeem","type":"function","inputs":[{"name":"","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"pure"},{"name":"previewWithdraw","type":"function","inputs":[{"name":"","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"pure"},{"name":"redeem","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"},{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"redemption","type":"function","inputs":[{"name":"redemptionId","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"tuple","components":[{"name":"prev","type":"uint256","internalType":"uint256"},{"name":"next","type":"uint256","internalType":"uint256"},{"name":"pendingShares","type":"uint256","internalType":"uint256"},{"name":"redeemableShares","type":"uint256","internalType":"uint256"},{"name":"withdrawableAmount","type":"uint256","internalType":"uint256"},{"name":"controller","type":"address","internalType":"address"},{"name":"redemptionTimestamp","type":"uint64","internalType":"uint64"}],"internalType":"struct IStakedUSDai.Redemption"},{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"redemptionIds","type":"function","inputs":[{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256[]","internalType":"uint256[]"}],"stateMutability":"view"},{"name":"redemptionQueueInfo","type":"function","inputs":[],"outputs":[{"name":"index","type":"uint256","internalType":"uint256"},{"name":"head","type":"uint256","internalType":"uint256"},{"name":"tail","type":"uint256","internalType":"uint256"},{"name":"pending","type":"uint256","internalType":"uint256"},{"name":"balance","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"redemptionSharePrice","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"redemptionTimestamp","type":"function","inputs":[],"outputs":[{"name":"","type":"uint64","internalType":"uint64"}],"stateMutability":"view"},{"name":"renounceRole","type":"function","inputs":[{"name":"role","type":"bytes32","internalType":"bytes32"},{"name":"callerConfirmation","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"requestRedeem","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"},{"name":"controller","type":"address","internalType":"address"},{"name":"owner","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"revokeRole","type":"function","inputs":[{"name":"role","type":"bytes32","internalType":"bytes32"},{"name":"account","type":"address","internalType":"address"}],"outputs":[],"stateMutability":"nonpayable"},{"name":"serviceRedemptions","type":"function","inputs":[{"name":"shares","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"},{"name":"setOperator","type":"function","inputs":[{"name":"operator","type":"address","internalType":"address"},{"name":"approved","type":"bool","internalType":"bool"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"name":"share","type":"function","inputs":[],"outputs":[{"name":"","type":"address","internalType":"address"}],"stateMutability":"view"},{"name":"supportsInterface","type":"function","inputs":[{"name":"interfaceId","type":"bytes4","internalType":"bytes4"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"view"},{"name":"symbol","type":"function","inputs":[],"outputs":[{"name":"","type":"string","internalType":"string"}],"stateMutability":"view"},{"name":"totalAssets","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"totalShares","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"totalSupply","type":"function","inputs":[],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"view"},{"name":"transfer","type":"function","inputs":[{"name":"to","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"name":"transferFrom","type":"function","inputs":[{"name":"from","type":"address","internalType":"address"},{"name":"to","type":"address","internalType":"address"},{"name":"value","type":"uint256","internalType":"uint256"}],"outputs":[{"name":"","type":"bool","internalType":"bool"}],"stateMutability":"nonpayable"},{"name":"unpause","type":"function","inputs":[],"outputs":[],"stateMutability":"nonpayable"},{"name":"withdraw","type":"function","inputs":[{"name":"amount","type":"uint256","internalType":"uint256"},{"name":"receiver","type":"address","internalType":"address"},{"name":"controller","type":"address","internalType":"address"}],"outputs":[{"name":"","type":"uint256","internalType":"uint256"}],"stateMutability":"nonpayable"}],"sources":{"src/StakedUSDai.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/interfaces/IERC4626.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol\";\n\nimport \"@usdai-loan-router-contracts/interfaces/ILoanRouterV2Hooks.sol\";\n\nimport \"./StakedUSDaiStorage.sol\";\nimport \"./RedemptionLogic.sol\";\n\nimport \"./positionManagers/BasePositionManager.sol\";\nimport \"./positionManagers/LoanRouterPositionManager.sol\";\n\nimport \"./interfaces/IStakedUSDai.sol\";\nimport \"./interfaces/IERC7540.sol\";\nimport \"./interfaces/IERC7575.sol\";\nimport \"./interfaces/IMintableBurnable.sol\";\n\n/**\n * @title Staked USDai ERC20\n * @author USD.AI Foundation\n */\ncontract StakedUSDai is\n    ERC165Upgradeable,\n    ERC20Upgradeable,\n    ERC20PermitUpgradeable,\n    MulticallUpgradeable,\n    PausableUpgradeable,\n    StakedUSDaiStorage,\n    BasePositionManager,\n    LoanRouterPositionManager,\n    IStakedUSDai,\n    IMintableBurnable,\n    IERC4626,\n    IERC7540Redeem,\n    IERC7540Operator\n{\n    using SafeERC20 for IERC20;\n    using EnumerableSet for EnumerableSet.UintSet;\n\n    /*------------------------------------------------------------------------*/\n    /* Constants */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Implementation version\n     */\n    string public constant IMPLEMENTATION_VERSION = \"1.14\";\n\n    /**\n     * @notice Fixed point scale\n     */\n    uint256 private constant FIXED_POINT_SCALE = 1e18;\n\n    /**\n     * @notice Amount of shares to lock for initial deposit\n     */\n    uint128 private constant LOCKED_SHARES = 1e6;\n\n    /*------------------------------------------------------------------------*/\n    /* Constructor */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice sUSDai Constructor\n     * @param usdai_ USDai token\n     * @param loanRouterV2_ V2 loan router\n     * @param adminFeeRecipient_ Admin fee recipient\n     * @param genesisTimestamp_ Genesis timestamp\n     * @param baseYieldAdminFeeRate_ Base yield admin fee rate\n     * @param loanRouterAdminFeeRate_ Loan router admin fee rate\n     * @param bridgeAdapter_ Bridge adapter contract\n     */\n    constructor(\n        address usdai_,\n        address loanRouterV2_,\n        address adminFeeRecipient_,\n        uint64 genesisTimestamp_,\n        uint256 baseYieldAdminFeeRate_,\n        uint256 loanRouterAdminFeeRate_,\n        address bridgeAdapter_\n    )\n        StakedUSDaiStorage(usdai_, adminFeeRecipient_, genesisTimestamp_, bridgeAdapter_)\n        BasePositionManager(baseYieldAdminFeeRate_)\n        LoanRouterPositionManager(loanRouterV2_, loanRouterAdminFeeRate_)\n    {\n        _disableInitializers();\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Initialization  */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Initialize the contract\n     * @param admin Default admin address\n     */\n    function initialize(\n        address admin\n    ) external initializer {\n        __ERC165_init();\n        __ERC20_init(\"Staked USDai\", \"sUSDai\");\n        __ERC20Permit_init(\"Staked USDai\");\n        __Multicall_init();\n        __Pausable_init();\n        __AccessControl_init();\n        __ReentrancyGuard_init();\n\n        /* Grant roles */\n        _grantRole(DEFAULT_ADMIN_ROLE, admin);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Modifiers  */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Non-zero value modifier\n     * @param value Value to check\n     */\n    modifier nonZeroUint(\n        uint256 value\n    ) {\n        if (value == 0) revert InvalidAmount();\n        _;\n    }\n\n    /**\n     * @notice Non-zero address modifier\n     * @param value Value to check\n     */\n    modifier nonZeroAddress(\n        address value\n    ) {\n        if (value == address(0)) revert InvalidAddress();\n        _;\n    }\n\n    /**\n     * @notice Only bridge adapter modifier\n     */\n    modifier onlyBridgeAdapter() {\n        if (msg.sender != _bridgeAdapter) revert InvalidAddress();\n        _;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Getters  */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function redemptionQueueInfo()\n        external\n        view\n        returns (uint256 index, uint256 head, uint256 tail, uint256 pending, uint256 balance)\n    {\n        return (\n            _getRedemptionStateStorage().index,\n            _getRedemptionStateStorage().head,\n            _getRedemptionStateStorage().tail,\n            _getRedemptionStateStorage().pending,\n            _getRedemptionStateStorage().balance\n        );\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function redemptionTimestamp() external view returns (uint64) {\n        return RedemptionLogic._nextRedemptionTimestamp(_genesisTimestamp);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function redemption(\n        uint256 redemptionId\n    ) external view returns (Redemption memory, uint256) {\n        return RedemptionLogic._redemption(_getRedemptionStateStorage(), redemptionId);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function redemptionIds(\n        address controller\n    ) external view nonZeroAddress(controller) returns (uint256[] memory) {\n        return _getRedemptionStateStorage().redemptionIds[controller].values();\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function nav() external view returns (uint256) {\n        return _assets(ValuationType.OPTIMISTIC);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function depositSharePrice() public view returns (uint256) {\n        return _sharePrice(ValuationType.OPTIMISTIC);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function redemptionSharePrice() public view returns (uint256) {\n        return _sharePrice(ValuationType.CONSERVATIVE);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function totalShares() public view returns (uint256) {\n        return totalSupply() + bridgedSupply() + _getRedemptionStateStorage().pending;\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function bridgedSupply() public view returns (uint256) {\n        return _getBridgedSupplyStorage().bridgedSupply;\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function balances() external view returns (uint256, uint256) {\n        return (_getDepositsStorage().balance, _getRedemptionStateStorage().balance);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function adminFeeRecipient() external view returns (address) {\n        return _adminFeeRecipient;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Internal helpers  */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc PositionManager\n     */\n    function _assets(\n        ValuationType valuationType\n    ) internal view override(BasePositionManager, LoanRouterPositionManager) returns (uint256) {\n        return BasePositionManager._assets(valuationType) + LoanRouterPositionManager._assets(valuationType)\n            + _depositBalance();\n    }\n\n    /**\n     * @notice USDai deposit balance in this contract less serviced redemption\n     * @return USDai deposit balance less serviced redemption\n     */\n    function _depositBalance() internal view returns (uint256) {\n        return _getDepositsStorage().balance - _getRedemptionStateStorage().balance;\n    }\n\n    /**\n     * @notice Compute share price\n     * @param valuationType Valuation type\n     * @return Share price\n     */\n    function _sharePrice(\n        ValuationType valuationType\n    ) internal view returns (uint256) {\n        return totalShares() == 0 ? FIXED_POINT_SCALE : (_assets(valuationType) * FIXED_POINT_SCALE) / totalShares();\n    }\n\n    /**\n     * @notice Mint shares and deposit amount\n     * @param amount Amount deposited\n     * @param shares Shares minted\n     * @param receiver Receiver address\n     * @param referral Referral code\n     */\n    function _mintAndDeposit(uint256 amount, uint256 shares, address receiver, uint16 referral) internal {\n        /* If initial deposit, mint locked shares */\n        if (totalSupply() < LOCKED_SHARES) _mint(address(0xdead), LOCKED_SHARES);\n\n        /* Mint shares */\n        _mint(receiver, shares);\n\n        /* Update deposits balance */\n        _getDepositsStorage().balance += amount;\n\n        /* Deposit assets */\n        IERC20(asset()).safeTransferFrom(msg.sender, address(this), amount);\n\n        /* Emit Deposit */\n        emit Deposit(msg.sender, receiver, amount, shares);\n\n        /* Emit Referred Deposit if a referral code was provided */\n        if (referral != 0x0000) emit ReferredDeposit(msg.sender, receiver, amount, shares, referral);\n    }\n\n    /**\n     * @notice Deposit assets with slippage\n     * @param amount Amount to deposit\n     * @param receiver Receiver address\n     * @param minShares Minimum shares\n     * @param referral Referral code\n     * @return Shares minted\n     */\n    function _deposit(\n        uint256 amount,\n        address receiver,\n        uint256 minShares,\n        uint16 referral\n    ) internal whenNotPaused nonReentrant nonZeroUint(amount) nonZeroAddress(receiver) returns (uint256) {\n        /* Compute shares */\n        uint256 shares = convertToShares(amount);\n\n        /* If shares is 0 or less than min shares, revert */\n        if (shares == 0 || shares < minShares) revert InvalidAmount();\n\n        /* Mint shares and deposit amount */\n        _mintAndDeposit(amount, shares, receiver, referral);\n\n        return shares;\n    }\n\n    /**\n     * @notice Mint shares with slippage\n     * @param shares Shares to mint\n     * @param receiver Receiver address\n     * @param maxAmount Maximum amount\n     * @param referral Referral code\n     * @return assets Assets deposited\n     */\n    function _mint(\n        uint256 shares,\n        address receiver,\n        uint256 maxAmount,\n        uint16 referral\n    ) internal whenNotPaused nonReentrant nonZeroUint(shares) nonZeroAddress(receiver) returns (uint256 assets) {\n        /* Compute amount */\n        uint256 amount = convertToAssets(shares);\n\n        /* If amount is 0 or more than max amount, revert */\n        if (amount == 0 || amount > maxAmount) revert InvalidAmount();\n\n        /* Mint shares and deposit amount */\n        _mintAndDeposit(amount, shares, receiver, referral);\n\n        return amount;\n    }\n\n    /**\n     * @notice Validate address is not blacklisted\n     * @param account Address to check\n     */\n    function _validateNotBlacklisted(\n        address account\n    ) internal view {\n        if (_usdai.isBlacklisted(account)) revert BlacklistedAddress(account);\n    }\n\n    /**\n     * @notice Validate caller is account or operator for account\n     * @param account Address to check\n     */\n    function _validateOperator(\n        address account\n    ) internal view {\n        if (account != msg.sender && !_getIsOperatorStorage().isOperator[account][msg.sender]) revert InvalidCaller();\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC20Upgradeable overrides */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc ERC20Upgradeable\n     */\n    function _update(address from, address to, uint256 value) internal override {\n        _validateNotBlacklisted(msg.sender);\n        _validateNotBlacklisted(from);\n        _validateNotBlacklisted(to);\n\n        super._update(from, to, value);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC4626  */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function asset() public view returns (address) {\n        return address(_usdai);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function totalAssets() external view returns (uint256) {\n        return _assets(ValuationType.OPTIMISTIC);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function previewWithdraw(\n        uint256\n    ) external pure returns (uint256) {\n        revert DisabledImplementation();\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function previewRedeem(\n        uint256\n    ) external pure returns (uint256) {\n        revert DisabledImplementation();\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function maxWithdraw(\n        address controller\n    ) external view returns (uint256) {\n        (uint256 amount,) = RedemptionLogic._redemptionAvailable(_getRedemptionStateStorage(), controller);\n\n        /* Return amount */\n        return amount;\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function maxRedeem(\n        address controller\n    ) external view returns (uint256) {\n        (, uint256 shares) = RedemptionLogic._redemptionAvailable(_getRedemptionStateStorage(), controller);\n\n        /* Return shares */\n        return shares;\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function maxDeposit(\n        address\n    ) external pure returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function maxMint(\n        address\n    ) external pure returns (uint256) {\n        return type(uint256).max;\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function convertToShares(\n        uint256 assets\n    ) public view returns (uint256) {\n        /* Check if initial deposit */\n        bool initialDeposit = totalSupply() < LOCKED_SHARES;\n\n        /* Compute shares. If initial deposit, remove locked shares */\n        return ((assets * FIXED_POINT_SCALE) / depositSharePrice()) - (initialDeposit ? LOCKED_SHARES : 0);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function convertToAssets(\n        uint256 shares\n    ) public view returns (uint256) {\n        /* Check if initial deposit */\n        bool initialDeposit = totalSupply() < LOCKED_SHARES;\n\n        /* Compute assets. If initial deposit, price locked shares */\n        return ((((initialDeposit ? LOCKED_SHARES : 0) + shares) * depositSharePrice()) + FIXED_POINT_SCALE - 1)\n            / FIXED_POINT_SCALE;\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function previewDeposit(\n        uint256 assets\n    ) external view returns (uint256) {\n        return convertToShares(assets);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function previewMint(\n        uint256 shares\n    ) external view returns (uint256) {\n        return convertToAssets(shares);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function deposit(uint256 amount, address receiver) external returns (uint256) {\n        return _deposit(amount, receiver, 0, 0x0000);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function mint(uint256 shares, address receiver) external returns (uint256 assets) {\n        return _mint(shares, receiver, type(uint256).max, 0x0000);\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function withdraw(\n        uint256 amount,\n        address receiver,\n        address controller\n    )\n        external\n        whenNotPaused\n        nonReentrant\n        nonZeroUint(amount)\n        nonZeroAddress(receiver)\n        nonZeroAddress(controller)\n        returns (uint256)\n    {\n        /* Validate controller is not blacklisted */\n        _validateNotBlacklisted(controller);\n\n        /* Validate caller */\n        _validateOperator(controller);\n\n        /* Withdraw amount */\n        uint256 shares = RedemptionLogic._withdraw(_getRedemptionStateStorage(), amount, controller);\n\n        /* Update deposits balance */\n        _getDepositsStorage().balance -= amount;\n\n        /* Transfer assets */\n        IERC20(asset()).safeTransfer(receiver, amount);\n\n        /* Emit Withdraw */\n        emit Withdraw(msg.sender, receiver, controller, amount, shares);\n\n        return shares;\n    }\n\n    /**\n     * @inheritdoc IERC4626\n     */\n    function redeem(\n        uint256 shares,\n        address receiver,\n        address controller\n    )\n        external\n        whenNotPaused\n        nonReentrant\n        nonZeroUint(shares)\n        nonZeroAddress(receiver)\n        nonZeroAddress(controller)\n        returns (uint256)\n    {\n        /* Validate controller is not blacklisted */\n        _validateNotBlacklisted(controller);\n\n        /* Validate caller */\n        _validateOperator(controller);\n\n        /* Redeem shares */\n        uint256 amount = RedemptionLogic._redeem(_getRedemptionStateStorage(), shares, controller);\n\n        /* Update deposits balance */\n        _getDepositsStorage().balance -= amount;\n\n        /* Transfer assets */\n        if (amount > 0) IERC20(asset()).safeTransfer(receiver, amount);\n\n        /* Emit Withdraw */\n        emit Withdraw(msg.sender, receiver, controller, amount, shares);\n\n        return amount;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC4626 Overload */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function deposit(uint256 amount, address receiver, uint256 minShares) external returns (uint256) {\n        return _deposit(amount, receiver, minShares, 0x0000);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function deposit(uint256 amount, address receiver, uint256 minShares, uint16 referral) external returns (uint256) {\n        return _deposit(amount, receiver, minShares, referral);\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function mint(uint256 shares, address receiver, uint256 maxAmount) external returns (uint256) {\n        return _mint(shares, receiver, maxAmount, 0x0000);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC7540Operator */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IERC7540Operator\n     */\n    function isOperator(address controller, address operator) external view returns (bool status) {\n        return _getIsOperatorStorage().isOperator[controller][operator];\n    }\n\n    /**\n     * @inheritdoc IERC7540Operator\n     */\n    function setOperator(\n        address operator,\n        bool approved\n    ) external whenNotPaused nonReentrant nonZeroAddress(operator) returns (bool) {\n        /* Validate address is not blacklisted */\n        _validateNotBlacklisted(msg.sender);\n\n        /* Validate caller */\n        if (msg.sender == operator) revert InvalidAddress();\n\n        /* Set operator */\n        _getIsOperatorStorage().isOperator[msg.sender][operator] = approved;\n\n        /* Emit OperatorSet */\n        emit OperatorSet(msg.sender, operator, approved);\n\n        return true;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC7540Redeem */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IERC7540Redeem\n     */\n    function pendingRedeemRequest(uint256 redemptionId, address controller) external view returns (uint256) {\n        /* Get redemption */\n        Redemption storage redemption_ = _getRedemptionStateStorage().redemptions[redemptionId];\n\n        /* If controller is not the same, return 0 */\n        if (redemption_.controller != controller) return 0;\n\n        return redemption_.pendingShares;\n    }\n\n    /**\n     * @inheritdoc IERC7540Redeem\n     */\n    function claimableRedeemRequest(uint256 redemptionId, address controller) external view returns (uint256) {\n        /* Get redemption */\n        Redemption storage redemption_ = _getRedemptionStateStorage().redemptions[redemptionId];\n\n        /* If controller is not the same, return 0 */\n        if (redemption_.controller != controller) return 0;\n\n        return redemption_.redeemableShares;\n    }\n\n    /**\n     * @inheritdoc IERC7540Redeem\n     */\n    function requestRedeem(\n        uint256 shares,\n        address controller,\n        address owner\n    )\n        external\n        whenNotPaused\n        nonReentrant\n        nonZeroUint(shares)\n        nonZeroAddress(controller)\n        nonZeroAddress(owner)\n        returns (uint256)\n    {\n        /* Validate address is not blacklisted */\n        _validateNotBlacklisted(controller);\n\n        /* Validate caller */\n        _validateOperator(owner);\n\n        /* Validate balance */\n        if (balanceOf(owner) < shares) revert InsufficientBalance();\n\n        /* Burn sUSDai shares */\n        _burn(owner, shares);\n\n        /* Request redeem */\n        uint256 redemptionId =\n            RedemptionLogic._requestRedeem(_getRedemptionStateStorage(), _genesisTimestamp, shares, controller);\n\n        /* Emit redeem request */\n        emit RedeemRequest(controller, owner, redemptionId, msg.sender, shares);\n\n        return redemptionId;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC7575 */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get share address\n     * @return Share address\n     */\n    function share() external view returns (address) {\n        return address(this);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Pause admin API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function pause() external onlyRole(PAUSE_ADMIN_ROLE) {\n        _pause();\n    }\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function unpause() external onlyRole(PAUSE_ADMIN_ROLE) {\n        _unpause();\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Manager API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IStakedUSDai\n     */\n    function serviceRedemptions(\n        uint256 shares\n    ) external onlyRole(STRATEGY_ADMIN_ROLE) nonZeroUint(shares) returns (uint256) {\n        /* Process redemptions */\n        (uint256 amountProcessed, bool allRedemptionsServiced) =\n            RedemptionLogic._processRedemptions(_getRedemptionStateStorage(), shares, redemptionSharePrice());\n\n        /* Validate amount is available to be serviced */\n        if (amountProcessed > _depositBalance()) revert InsufficientBalance();\n\n        /* Update redemption balance */\n        _getRedemptionStateStorage().balance += amountProcessed;\n\n        /* Emit RedemptionsServiced */\n        emit RedemptionsServiced(shares, amountProcessed, allRedemptionsServiced);\n\n        return amountProcessed;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Minter API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IMintableBurnable\n     */\n    function mint(address to, uint256 amount) external whenNotPaused onlyBridgeAdapter {\n        /* Mint supply */\n        _mint(to, amount);\n\n        /* Update bridged supply */\n        _getBridgedSupplyStorage().bridgedSupply -= amount;\n    }\n\n    /**\n     * @inheritdoc IMintableBurnable\n     */\n    function burn(address from, uint256 amount) external whenNotPaused onlyBridgeAdapter {\n        /* Burn supply */\n        _burn(from, amount);\n\n        /* Update bridged supply */\n        _getBridgedSupplyStorage().bridgedSupply += amount;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC165 */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IERC165\n     */\n    function supportsInterface(\n        bytes4 interfaceId\n    ) public view virtual override(AccessControlUpgradeable, ERC165Upgradeable) returns (bool) {\n        return interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC4626).interfaceId\n            || interfaceId == type(IERC7540Redeem).interfaceId || interfaceId == type(IERC7540Operator).interfaceId\n            || interfaceId == type(IStakedUSDai).interfaceId || interfaceId == type(IMintableBurnable).interfaceId\n            || interfaceId == type(IERC7575).interfaceId || interfaceId == type(ILoanRouterV2Hooks).interfaceId\n            || interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IEscrowTimelockHooks).interfaceId\n            || interfaceId == type(IDepositTimelockHooks).interfaceId || super.supportsInterface(interfaceId);\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.20;\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"},"lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4626.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\nimport {IERC20Metadata} from \"../token/ERC20/extensions/IERC20Metadata.sol\";\n\n/**\n * @dev Interface of the ERC-4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n */\ninterface IERC4626 is IERC20, IERC20Metadata {\n    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n    event Withdraw(\n        address indexed sender,\n        address indexed receiver,\n        address indexed owner,\n        uint256 assets,\n        uint256 shares\n    );\n\n    /**\n     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n     *\n     * - MUST be an ERC-20 token contract.\n     * - MUST NOT revert.\n     */\n    function asset() external view returns (address assetTokenAddress);\n\n    /**\n     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n     *\n     * - SHOULD include any compounding that occurs from yield.\n     * - MUST be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT revert.\n     */\n    function totalAssets() external view returns (uint256 totalManagedAssets);\n\n    /**\n     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n     * through a deposit call.\n     *\n     * - MUST return a limited value if receiver is subject to some deposit limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n     * - MUST NOT revert.\n     */\n    function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n     *   in the same transaction.\n     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   deposit execution, and are accounted for during deposit.\n     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n     * - MUST return a limited value if receiver is subject to some mint limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n     * - MUST NOT revert.\n     */\n    function maxMint(address receiver) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n     *   same transaction.\n     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n     *   would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by minting.\n     */\n    function previewMint(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n     *   execution, and are accounted for during mint.\n     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n     * Vault, through a withdraw call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n     *   called\n     *   in the same transaction.\n     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n    /**\n     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   withdraw execution, and are accounted for during withdraw.\n     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n     * through a redeem call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n     *   same transaction.\n     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n     *   redemption would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n     */\n    function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n    /**\n     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   redeem execution, and are accounted for during redeem.\n     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.2.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        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));\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        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));\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        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));\n\n        if (!_callOptionalReturnBool(token, approvalCall)) {\n            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));\n            _callOptionalReturn(token, approvalCall);\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 rely 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 rely 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     * Opposedly, 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 high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.\n     */\n    function _callOptionalReturn(IERC20 token, bytes memory data) private {\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            // bubble errors\n            if iszero(success) {\n                let ptr := mload(0x40)\n                returndatacopy(ptr, 0, returndatasize())\n                revert(ptr, returndatasize())\n            }\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n\n        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {\n            revert SafeERC20FailedOperation(address(token));\n        }\n    }\n\n    /**\n     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n     * on the return value: the return value is optional (but if data is returned, it must not be false).\n     * @param token The token targeted by the call.\n     * @param data The call data (encoded using abi.encode or one of its variants).\n     *\n     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.\n     */\n    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {\n        bool success;\n        uint256 returnSize;\n        uint256 returnValue;\n        assembly (\"memory-safe\") {\n            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)\n            returnSize := returndatasize()\n            returnValue := mload(0)\n        }\n        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```solidity\n * contract Example {\n *     // Add the library methods\n *     using EnumerableSet for EnumerableSet.AddressSet;\n *\n *     // Declare a set state variable\n *     EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n    // To implement this library for multiple types with as little code\n    // repetition as possible, we write it in terms of a generic Set type with\n    // bytes32 values.\n    // The Set implementation uses private functions, and user-facing\n    // implementations (such as AddressSet) are just wrappers around the\n    // underlying Set.\n    // This means that we can only create new EnumerableSets for types that fit\n    // in bytes32.\n\n    struct Set {\n        // Storage of set values\n        bytes32[] _values;\n        // Position is the index of the value in the `values` array plus 1.\n        // Position 0 is used to mean a value is not in the set.\n        mapping(bytes32 value => uint256) _positions;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function _add(Set storage set, bytes32 value) private returns (bool) {\n        if (!_contains(set, value)) {\n            set._values.push(value);\n            // The value is stored at length-1, but we add 1 to all indexes\n            // and use 0 as a sentinel value\n            set._positions[value] = set._values.length;\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function _remove(Set storage set, bytes32 value) private returns (bool) {\n        // We cache the value's position to prevent multiple reads from the same storage slot\n        uint256 position = set._positions[value];\n\n        if (position != 0) {\n            // Equivalent to contains(set, value)\n            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n            // the array, and then remove the last element (sometimes called as 'swap and pop').\n            // This modifies the order of the array, as noted in {at}.\n\n            uint256 valueIndex = position - 1;\n            uint256 lastIndex = set._values.length - 1;\n\n            if (valueIndex != lastIndex) {\n                bytes32 lastValue = set._values[lastIndex];\n\n                // Move the lastValue to the index where the value to delete is\n                set._values[valueIndex] = lastValue;\n                // Update the tracked position of the lastValue (that was just moved)\n                set._positions[lastValue] = position;\n            }\n\n            // Delete the slot where the moved value was stored\n            set._values.pop();\n\n            // Delete the tracked position for the deleted slot\n            delete set._positions[value];\n\n            return true;\n        } else {\n            return false;\n        }\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function _contains(Set storage set, bytes32 value) private view returns (bool) {\n        return set._positions[value] != 0;\n    }\n\n    /**\n     * @dev Returns the number of values on the set. O(1).\n     */\n    function _length(Set storage set) private view returns (uint256) {\n        return set._values.length;\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function _at(Set storage set, uint256 index) private view returns (bytes32) {\n        return set._values[index];\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function _values(Set storage set) private view returns (bytes32[] memory) {\n        return set._values;\n    }\n\n    // Bytes32Set\n\n    struct Bytes32Set {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _add(set._inner, value);\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n        return _remove(set._inner, value);\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n        return _contains(set._inner, value);\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(Bytes32Set storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n        return _at(set._inner, index);\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // AddressSet\n\n    struct AddressSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(AddressSet storage set, address value) internal returns (bool) {\n        return _add(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(AddressSet storage set, address value) internal returns (bool) {\n        return _remove(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(AddressSet storage set, address value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(uint256(uint160(value))));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(AddressSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(AddressSet storage set, uint256 index) internal view returns (address) {\n        return address(uint160(uint256(_at(set._inner, index))));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(AddressSet storage set) internal view returns (address[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        address[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n\n    // UintSet\n\n    struct UintSet {\n        Set _inner;\n    }\n\n    /**\n     * @dev Add a value to a set. O(1).\n     *\n     * Returns true if the value was added to the set, that is if it was not\n     * already present.\n     */\n    function add(UintSet storage set, uint256 value) internal returns (bool) {\n        return _add(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Removes a value from a set. O(1).\n     *\n     * Returns true if the value was removed from the set, that is if it was\n     * present.\n     */\n    function remove(UintSet storage set, uint256 value) internal returns (bool) {\n        return _remove(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns true if the value is in the set. O(1).\n     */\n    function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n        return _contains(set._inner, bytes32(value));\n    }\n\n    /**\n     * @dev Returns the number of values in the set. O(1).\n     */\n    function length(UintSet storage set) internal view returns (uint256) {\n        return _length(set._inner);\n    }\n\n    /**\n     * @dev Returns the value stored at position `index` in the set. O(1).\n     *\n     * Note that there are no guarantees on the ordering of values inside the\n     * array, and it may change when more values are added or removed.\n     *\n     * Requirements:\n     *\n     * - `index` must be strictly less than {length}.\n     */\n    function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n        return uint256(_at(set._inner, index));\n    }\n\n    /**\n     * @dev Return the entire set in an array\n     *\n     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n     * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n     */\n    function values(UintSet storage set) internal view returns (uint256[] memory) {\n        bytes32[] memory store = _values(set._inner);\n        uint256[] memory result;\n\n        assembly (\"memory-safe\") {\n            result := store\n        }\n\n        return result;\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @title ERC-721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC-721 asset contracts.\n */\ninterface IERC721Receiver {\n    /**\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n     * by `operator` from `from`, this function is called.\n     *\n     * It must return its Solidity selector to confirm the token transfer.\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be\n     * reverted.\n     *\n     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n     */\n    function onERC721Received(\n        address operator,\n        address from,\n        uint256 tokenId,\n        bytes calldata data\n    ) external returns (bytes4);\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ReentrancyGuardUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)\n\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,\n * consider using {ReentrancyGuardTransient} instead.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n    // Booleans are more expensive than uint256 or any type that takes up a full\n    // word because each write operation emits an extra SLOAD to first read the\n    // slot's contents, replace the bits taken up by the boolean, and then write\n    // back. This is the compiler's defense against contract upgrades and\n    // pointer aliasing, and it cannot be disabled.\n\n    // The values being non-zero value makes deployment a bit more expensive,\n    // but in exchange the refund on every call to nonReentrant will be lower in\n    // amount. Since refunds are capped to a percentage of the total\n    // transaction's gas, it is best to keep them low in cases like this one, to\n    // increase the likelihood of the full refund coming into effect.\n    uint256 private constant NOT_ENTERED = 1;\n    uint256 private constant ENTERED = 2;\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard\n    struct ReentrancyGuardStorage {\n        uint256 _status;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.ReentrancyGuard\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;\n\n    function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {\n        assembly {\n            $.slot := ReentrancyGuardStorageLocation\n        }\n    }\n\n    /**\n     * @dev Unauthorized reentrant call.\n     */\n    error ReentrancyGuardReentrantCall();\n\n    function __ReentrancyGuard_init() internal onlyInitializing {\n        __ReentrancyGuard_init_unchained();\n    }\n\n    function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        $._status = NOT_ENTERED;\n    }\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    function _nonReentrantBefore() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // On the first call to nonReentrant, _status will be NOT_ENTERED\n        if ($._status == ENTERED) {\n            revert ReentrancyGuardReentrantCall();\n        }\n\n        // Any calls to nonReentrant after this point will fail\n        $._status = ENTERED;\n    }\n\n    function _nonReentrantAfter() private {\n        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        // By storing the original value once again, a refund is triggered (see\n        // https://eips.ethereum.org/EIPS/eip-2200)\n        $._status = NOT_ENTERED;\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        ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();\n        return $._status == ENTERED;\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/MulticallUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Multicall.sol)\n\npragma solidity ^0.8.20;\n\nimport {Address} from \"@openzeppelin/contracts/utils/Address.sol\";\nimport {ContextUpgradeable} from \"./ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides a function to batch together multiple calls in a single external call.\n *\n * Consider any assumption about calldata validation performed by the sender may be violated if it's not especially\n * careful about sending transactions invoking {multicall}. For example, a relay address that filters function\n * selectors won't filter calls nested within a {multicall} operation.\n *\n * NOTE: Since 5.0.1 and 4.9.4, this contract identifies non-canonical contexts (i.e. `msg.sender` is not {_msgSender}).\n * If a non-canonical context is identified, the following self `delegatecall` appends the last bytes of `msg.data`\n * to the subcall. This makes it safe to use with {ERC2771Context}. Contexts that don't affect the resolution of\n * {_msgSender} are not propagated to subcalls.\n */\nabstract contract MulticallUpgradeable is Initializable, ContextUpgradeable {\n    function __Multicall_init() internal onlyInitializing {\n    }\n\n    function __Multicall_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Receives and executes a batch of function calls on this contract.\n     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n     */\n    function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {\n        bytes memory context = msg.sender == _msgSender()\n            ? new bytes(0)\n            : msg.data[msg.data.length - _contextSuffixLength():];\n\n        results = new bytes[](data.length);\n        for (uint256 i = 0; i < data.length; i++) {\n            results[i] = Address.functionDelegateCall(address(this), bytes.concat(data[i], context));\n        }\n        return results;\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\nimport {Initializable} from \"../../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    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.2.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 \"../../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     * All two of these values are immutable: they can only be set once during\n     * 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    /**\n     * @dev See {IERC20-totalSupply}.\n     */\n    function totalSupply() public view virtual returns (uint256) {\n        ERC20Storage storage $ = _getERC20Storage();\n        return $._totalSupply;\n    }\n\n    /**\n     * @dev See {IERC20-balanceOf}.\n     */\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    /**\n     * @dev See {IERC20-allowance}.\n     */\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 set 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"},"lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20PermitUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/ERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20Permit} from \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol\";\nimport {ERC20Upgradeable} from \"../ERC20Upgradeable.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\nimport {EIP712Upgradeable} from \"../../../utils/cryptography/EIP712Upgradeable.sol\";\nimport {NoncesUpgradeable} from \"../../../utils/NoncesUpgradeable.sol\";\nimport {Initializable} from \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\nabstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable {\n    bytes32 private constant PERMIT_TYPEHASH =\n        keccak256(\"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\");\n\n    /**\n     * @dev Permit deadline has expired.\n     */\n    error ERC2612ExpiredSignature(uint256 deadline);\n\n    /**\n     * @dev Mismatched signature.\n     */\n    error ERC2612InvalidSigner(address signer, address owner);\n\n    /**\n     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `\"1\"`.\n     *\n     * It's a good idea to use the same `name` that is defined as the ERC-20 token name.\n     */\n    function __ERC20Permit_init(string memory name) internal onlyInitializing {\n        __EIP712_init_unchained(name, \"1\");\n    }\n\n    function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) public virtual {\n        if (block.timestamp > deadline) {\n            revert ERC2612ExpiredSignature(deadline);\n        }\n\n        bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));\n\n        bytes32 hash = _hashTypedDataV4(structHash);\n\n        address signer = ECDSA.recover(hash, v, r, s);\n        if (signer != owner) {\n            revert ERC2612InvalidSigner(signer, owner);\n        }\n\n        _approve(owner, spender, value);\n    }\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) {\n        return super.nonces(owner);\n    }\n\n    /**\n     * @inheritdoc IERC20Permit\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view virtual returns (bytes32) {\n        return _domainSeparatorV4();\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/PausableUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ContextUpgradeable} from \"../utils/ContextUpgradeable.sol\";\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n    /// @custom:storage-location erc7201:openzeppelin.storage.Pausable\n    struct PausableStorage {\n        bool _paused;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Pausable\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;\n\n    function _getPausableStorage() private pure returns (PausableStorage storage $) {\n        assembly {\n            $.slot := PausableStorageLocation\n        }\n    }\n\n    /**\n     * @dev Emitted when the pause is triggered by `account`.\n     */\n    event Paused(address account);\n\n    /**\n     * @dev Emitted when the pause is lifted by `account`.\n     */\n    event Unpaused(address account);\n\n    /**\n     * @dev The operation failed because the contract is paused.\n     */\n    error EnforcedPause();\n\n    /**\n     * @dev The operation failed because the contract is not paused.\n     */\n    error ExpectedPause();\n\n    /**\n     * @dev Initializes the contract in unpaused state.\n     */\n    function __Pausable_init() internal onlyInitializing {\n        __Pausable_init_unchained();\n    }\n\n    function __Pausable_init_unchained() internal onlyInitializing {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is not paused.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    modifier whenNotPaused() {\n        _requireNotPaused();\n        _;\n    }\n\n    /**\n     * @dev Modifier to make a function callable only when the contract is paused.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    modifier whenPaused() {\n        _requirePaused();\n        _;\n    }\n\n    /**\n     * @dev Returns true if the contract is paused, and false otherwise.\n     */\n    function paused() public view virtual returns (bool) {\n        PausableStorage storage $ = _getPausableStorage();\n        return $._paused;\n    }\n\n    /**\n     * @dev Throws if the contract is paused.\n     */\n    function _requireNotPaused() internal view virtual {\n        if (paused()) {\n            revert EnforcedPause();\n        }\n    }\n\n    /**\n     * @dev Throws if the contract is not paused.\n     */\n    function _requirePaused() internal view virtual {\n        if (!paused()) {\n            revert ExpectedPause();\n        }\n    }\n\n    /**\n     * @dev Triggers stopped state.\n     *\n     * Requirements:\n     *\n     * - The contract must not be paused.\n     */\n    function _pause() internal virtual whenNotPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = true;\n        emit Paused(_msgSender());\n    }\n\n    /**\n     * @dev Returns to normal state.\n     *\n     * Requirements:\n     *\n     * - The contract must be paused.\n     */\n    function _unpause() internal virtual whenPaused {\n        PausableStorage storage $ = _getPausableStorage();\n        $._paused = false;\n        emit Unpaused(_msgSender());\n    }\n}\n"},"lib/usdai-loan-router-contracts/src/interfaces/ILoanRouterV2Hooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {ILoanRouterV2} from \"./ILoanRouterV2.sol\";\n\n/**\n * @title Loan Router V2 Callback Hooks\n * @author USD.AI Foundation\n */\ninterface ILoanRouterV2Hooks {\n    /**\n     * @notice Called when loan is originated\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     */\n    function onLoanOriginated(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex\n    ) external;\n\n    /**\n     * @notice Called when lender is repaid\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     * @param loanBalance Loan balance\n     * @param principal Principal repaid\n     * @param interest Interest paid\n     * @param prepay Prepayment\n     */\n    function onLoanRepayment(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        uint256 loanBalance,\n        uint256 principal,\n        uint256 interest,\n        uint256 prepay\n    ) external;\n\n    /**\n     * @notice Called when loan fee is paid\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param feeSpecIndex Fee specification index\n     * @param fee Fee paid\n     */\n    function onLoanFeePaid(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 feeSpecIndex,\n        uint256 fee\n    ) external;\n\n    /**\n     * @notice Called when loan is liquidated\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     */\n    function onLoanLiquidated(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex\n    ) external;\n\n    /**\n     * @notice Called when loan collateral is liquidated\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     * @param principal Principal repaid\n     * @param interest Interest paid\n     */\n    function onLoanCollateralLiquidated(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        uint256 principal,\n        uint256 interest\n    ) external;\n\n    /**\n     * @notice Called when loan is refinanced\n     * @param oldLoanTerms Old loan terms\n     * @param newLoanTerms New loan terms\n     * @param oldLoanTermsHash Old loan terms hash\n     * @param newLoanTermsHash New loan terms hash\n     * @param trancheIndex Old tranche index\n     * @param cashOut Cash out amount\n     * @param cashIn Cash in amount\n     */\n    function onLoanRefinanced(\n        ILoanRouterV2.LoanTermsV2 calldata oldLoanTerms,\n        ILoanRouterV2.LoanTermsV2 calldata newLoanTerms,\n        bytes32 oldLoanTermsHash,\n        bytes32 newLoanTermsHash,\n        uint8 trancheIndex,\n        uint256 cashOut,\n        uint256 cashIn\n    ) external;\n}\n"},"src/StakedUSDaiStorage.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nimport \"./interfaces/IStakedUSDai.sol\";\nimport \"./interfaces/IUSDai.sol\";\n\n/**\n * @title Staked USDai Storage\n * @author USD.AI Foundation\n */\nabstract contract StakedUSDaiStorage {\n    /*------------------------------------------------------------------------*/\n    /* Roles */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Pause role\n     */\n    bytes32 internal constant PAUSE_ADMIN_ROLE = keccak256(\"PAUSE_ADMIN_ROLE\");\n\n    /**\n     * @notice Strategy admin role\n     */\n    bytes32 internal constant STRATEGY_ADMIN_ROLE = keccak256(\"STRATEGY_ADMIN_ROLE\");\n\n    /*------------------------------------------------------------------------*/\n    /* Constants */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Is operator storage location\n     * @dev keccak256(abi.encode(uint256(keccak256(\"stakedUSDai.isOperator\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant IS_OPERATOR_STORAGE_LOCATION =\n        0x407fc66dcc0b10c2a8ec69f9095c4cd702e9ed0fb1a7e0f6b6f65bd03e776100;\n\n    /**\n     * @notice Redemption state storage location\n     * @dev keccak256(abi.encode(uint256(keccak256(\"stakedUSDai.redemptionState_\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant REDEMPTION_STATE_STORAGE_LOCATION =\n        0xc6ad599b80e437d86c31abd9e2cd5c6ce030f11e9dbae11bc05446f7af4d4900;\n\n    /**\n     * @notice Bridged supply storage location\n     * @dev keccak256(abi.encode(uint256(keccak256(\"stakedUSDai.bridgedSupply\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant BRIDGED_SUPPLY_STORAGE_LOCATION =\n        0x3625978433c3d3388ec2dddfdf4dd931786e9db5f2382a6ed08621dc9fb95f00;\n\n    /**\n     * @notice Deposits storage location\n     * @dev keccak256(abi.encode(uint256(keccak256(\"stakedUSDai.deposits\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant DEPOSITS_STORAGE_LOCATION =\n        0x2c5de62bb029e52f8f5651820547ac44294b098c752111b71e5fee4f80a66900;\n\n    /*------------------------------------------------------------------------*/\n    /* Structures */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @custom:storage-location erc7201:stakedUSDai.isOperator\n     */\n    struct IsOperator {\n        mapping(address => mapping(address => bool)) isOperator;\n    }\n\n    /**\n     * @custom:storage-location erc7201:stakedUSDai.redemptionState_\n     * @param index Current redemption index\n     * @param head Head of the redemption queue\n     * @param tail Tail of the redemption queue\n     * @param pending Pending redemption shares\n     * @param balance Redemption balance\n     * @param redemptions Mapping of redemption index to redemption\n     * @param redemptionIds Mapping of controller to redemption indices\n     */\n    struct RedemptionState {\n        uint256 index;\n        uint256 head;\n        uint256 tail;\n        uint256 pending;\n        uint256 balance;\n        mapping(uint256 => IStakedUSDai.Redemption) redemptions;\n        mapping(address => EnumerableSet.UintSet) redemptionIds;\n    }\n\n    /**\n     * @custom:storage-location erc7201:stakedUSDai.bridgedSupply\n     */\n    struct BridgedSupply {\n        uint256 bridgedSupply;\n    }\n\n    /**\n     * @custom:storage-location erc7201:stakedUSDai.deposits\n     */\n    struct Deposits {\n        uint256 balance;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Immutable */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice USDai\n     */\n    IUSDai internal immutable _usdai;\n\n    /**\n     * @notice Admin fee recipient\n     */\n    address internal immutable _adminFeeRecipient;\n\n    /**\n     * @notice Genesis timestamp\n     */\n    uint64 internal immutable _genesisTimestamp;\n\n    /**\n     * @notice Bridge adapter contract\n     */\n    address internal immutable _bridgeAdapter;\n\n    /*------------------------------------------------------------------------*/\n    /* Constructor */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Constructor\n     * @param usdai USDai\n     * @param adminFeeRecipient Admin fee recipient\n     * @param genesisTimestamp Genesis timestamp\n     * @param bridgeAdapter Bridge adapter contract\n     */\n    constructor(address usdai, address adminFeeRecipient, uint64 genesisTimestamp, address bridgeAdapter) {\n        _usdai = IUSDai(usdai);\n        _adminFeeRecipient = adminFeeRecipient;\n        _genesisTimestamp = genesisTimestamp;\n        _bridgeAdapter = bridgeAdapter;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Storage getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get reference to ERC-7201 is operator storage\n     *\n     * @return $ Reference to is operator storage\n     */\n    function _getIsOperatorStorage() internal pure returns (IsOperator storage $) {\n        assembly {\n            $.slot := IS_OPERATOR_STORAGE_LOCATION\n        }\n    }\n\n    /**\n     * @notice Get reference to ERC-7201 redemption state storage\n     *\n     * @return $ Reference to redemption state storage\n     */\n    function _getRedemptionStateStorage() internal pure returns (RedemptionState storage $) {\n        assembly {\n            $.slot := REDEMPTION_STATE_STORAGE_LOCATION\n        }\n    }\n\n    /**\n     * @notice Get reference to ERC-7201 bridged supply storage\n     *\n     * @return $ Reference to bridged supply storage\n     */\n    function _getBridgedSupplyStorage() internal pure returns (BridgedSupply storage $) {\n        assembly {\n            $.slot := BRIDGED_SUPPLY_STORAGE_LOCATION\n        }\n    }\n\n    /**\n     * @notice Get reference to ERC-7201 deposits storage\n     *\n     * @return $ Reference to deposits storage\n     */\n    function _getDepositsStorage() internal pure returns (Deposits storage $) {\n        assembly {\n            $.slot := DEPOSITS_STORAGE_LOCATION\n        }\n    }\n}\n"},"src/RedemptionLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nimport \"./StakedUSDaiStorage.sol\";\n\nimport \"./interfaces/IStakedUSDai.sol\";\n\n/**\n * @title Redemption Logic\n * @author USD.AI Foundation\n */\nlibrary RedemptionLogic {\n    using EnumerableSet for EnumerableSet.UintSet;\n\n    /*------------------------------------------------------------------------*/\n    /* Constants */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Fixed point scale\n     */\n    uint256 internal constant FIXED_POINT_SCALE = 1e18;\n\n    /**\n     * @notice Maximum redemption queue scan count\n     */\n    uint256 internal constant MAX_REDEMPTION_QUEUE_SCAN_COUNT = 150;\n\n    /**\n     * @notice Max active redemptions per controller\n     */\n    uint256 internal constant MAX_ACTIVE_REDEMPTIONS_COUNT = 50;\n\n    /**\n     * @notice Minimum redemption shares\n     */\n    uint256 internal constant MIN_REDEMPTION_SHARES = 1e18;\n\n    /**\n     * @notice Redemption window\n     */\n    uint64 internal constant REDEMPTION_WINDOW = 30 days;\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get redemption and shares ahead\n     * @param redemptionState_ Redemption state\n     * @param redemptionId Redemption ID\n     * @return Redemption, shares ahead\n     */\n    function _redemption(\n        StakedUSDaiStorage.RedemptionState storage redemptionState_,\n        uint256 redemptionId\n    ) external view returns (IStakedUSDai.Redemption memory, uint256) {\n        /* Look up redemption */\n        IStakedUSDai.Redemption memory redemption_ = redemptionState_.redemptions[redemptionId];\n\n        /* Get shares ahead */\n        uint256 sharesAhead;\n        uint256 count;\n        uint256 prevRedemptionId = redemption_.prev;\n        while (prevRedemptionId != 0 && count < MAX_REDEMPTION_QUEUE_SCAN_COUNT) {\n            /* Get redemption */\n            IStakedUSDai.Redemption memory prevRedemption = redemptionState_.redemptions[prevRedemptionId];\n\n            /* If previous redemption pending is 0, break */\n            if (prevRedemption.pendingShares == 0) break;\n\n            /* Add pending shares */\n            sharesAhead += prevRedemption.pendingShares;\n\n            /* Get previous redemption */\n            prevRedemptionId = prevRedemption.prev;\n\n            /* Increment count */\n            count++;\n        }\n\n        return (redemption_, sharesAhead);\n    }\n\n    /**\n     * @notice Get available redemption amount and shares\n     * @param redemptionState_ Redemption state\n     * @param controller Controller address\n     * @return Amount, shares\n     */\n    function _redemptionAvailable(\n        StakedUSDaiStorage.RedemptionState storage redemptionState_,\n        address controller\n    ) external view returns (uint256, uint256) {\n        uint256 amount;\n        uint256 shares;\n\n        /* Get redemption IDs */\n        uint256[] memory redemptionIds = redemptionState_.redemptionIds[controller].values();\n\n        /* Iterate through redemption IDs */\n        for (uint256 i; i < redemptionIds.length; i++) {\n            /* Look up redemption */\n            IStakedUSDai.Redemption memory redemption_ = redemptionState_.redemptions[redemptionIds[i]];\n\n            /* Add withdrawable amount and redeemable shares which are already serviced */\n            amount += redemption_.withdrawableAmount;\n            shares += redemption_.redeemableShares;\n        }\n\n        /* Return amount and shares */\n        return (amount, shares);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Helpers */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Compute next redemption timestamp\n     * @param genesisTimestamp Genesis timestamp\n     * @return Next redemption timestamp\n     */\n    function _nextRedemptionTimestamp(\n        uint64 genesisTimestamp\n    ) internal view returns (uint64) {\n        /* Compute count */\n        uint64 count = block.timestamp >= genesisTimestamp\n            ? uint64((block.timestamp - genesisTimestamp) / REDEMPTION_WINDOW + 1)\n            : 0;\n\n        /* Return next redemption timestamp */\n        return genesisTimestamp + count * REDEMPTION_WINDOW;\n    }\n\n    /**\n     * @notice Withdraw assets\n     * @param redemptionState_ Redemption state\n     * @param amount Amount to withdraw\n     * @param controller Controller address\n     * @return Shares redeemed\n     */\n    function _withdraw(\n        StakedUSDaiStorage.RedemptionState storage redemptionState_,\n        uint256 amount,\n        address controller\n    ) external returns (uint256) {\n        /* Initialize shares, remaining amount and redemption IDs */\n        uint256 shares;\n        uint256 remainingAmount = amount;\n        uint256[] memory redemptionIds = redemptionState_.redemptionIds[controller].values();\n\n        /* Iterate through redemption IDs */\n        for (uint256 i; i < redemptionIds.length && remainingAmount > 0; i++) {\n            /* Look up redemption */\n            IStakedUSDai.Redemption storage redemption_ = redemptionState_.redemptions[redemptionIds[i]];\n\n            /* Skip if redemption amount is 0 */\n            if (redemption_.withdrawableAmount == 0) continue;\n\n            /* Compute amount to withdraw */\n            uint256 amountToWithdraw = Math.min(remainingAmount, redemption_.withdrawableAmount);\n\n            /* Compute shares to redeem */\n            uint256 sharesToRedeem = amountToWithdraw == redemption_.withdrawableAmount\n                ? redemption_.redeemableShares\n                : Math.mulDiv(amountToWithdraw, redemption_.redeemableShares, redemption_.withdrawableAmount);\n\n            /* Update redemption state */\n            redemption_.withdrawableAmount -= amountToWithdraw;\n            redemption_.redeemableShares -= sharesToRedeem;\n\n            /* Update remaining amount and shares */\n            remainingAmount -= amountToWithdraw;\n            shares += sharesToRedeem;\n\n            /* If redemption is fully serviced and all shares have been redeemed, */\n            /* remove redemption ID */\n            if (redemption_.pendingShares == 0 && redemption_.redeemableShares == 0) {\n                redemptionState_.redemptionIds[controller].remove(redemptionIds[i]);\n            }\n        }\n\n        /* Validate withdrawal completed */\n        if (remainingAmount != 0) revert IStakedUSDai.InvalidRedemptionState();\n\n        /* Update redemption balance */\n        redemptionState_.balance -= amount;\n\n        return shares;\n    }\n\n    /**\n     * @notice Redeem shares\n     * @param redemptionState_ Redemption state\n     * @param shares Shares to redeem\n     * @param controller Controller address\n     * @return Amount redeemed\n     */\n    function _redeem(\n        StakedUSDaiStorage.RedemptionState storage redemptionState_,\n        uint256 shares,\n        address controller\n    ) external returns (uint256) {\n        /* Initialize amount, remaining shares and redemption IDs */\n        uint256 amount;\n        uint256 remainingShares = shares;\n        uint256[] memory redemptionIds = redemptionState_.redemptionIds[controller].values();\n\n        /* Iterate through redemption IDs */\n        for (uint256 i; i < redemptionIds.length && remainingShares > 0; i++) {\n            /* Look up redemption */\n            IStakedUSDai.Redemption storage redemption_ = redemptionState_.redemptions[redemptionIds[i]];\n\n            /* Skip if redemption amount is 0 */\n            if (redemption_.redeemableShares == 0) continue;\n\n            /* Compute shares to redeem */\n            uint256 sharesToRedeem = Math.min(remainingShares, redemption_.redeemableShares);\n\n            /* Compute amount to withdraw */\n            uint256 amountToWithdraw = sharesToRedeem == redemption_.redeemableShares\n                ? redemption_.withdrawableAmount\n                : Math.mulDiv(sharesToRedeem, redemption_.withdrawableAmount, redemption_.redeemableShares);\n\n            /* Update redemption state */\n            redemption_.withdrawableAmount -= amountToWithdraw;\n            redemption_.redeemableShares -= sharesToRedeem;\n\n            /* Update remaining shares and amount */\n            remainingShares -= sharesToRedeem;\n            amount += amountToWithdraw;\n\n            /* If redemption is fully serviced and all shares have been redeemed, */\n            /* remove redemption ID */\n            if (redemption_.pendingShares == 0 && redemption_.withdrawableAmount == 0) {\n                redemptionState_.redemptionIds[controller].remove(redemptionIds[i]);\n            }\n        }\n\n        /* Validate redemption completed */\n        if (remainingShares != 0) revert IStakedUSDai.InvalidRedemptionState();\n\n        /* Update redemption balance */\n        redemptionState_.balance -= amount;\n\n        return amount;\n    }\n\n    /**\n     * @notice Request redeem\n     * @param redemptionState_ Redemption state\n     * @param genesisTimestamp Genesis timestamp\n     * @param shares Shares to redeem\n     * @param controller Controller address\n     * @return Redemption ID\n     */\n    function _requestRedeem(\n        StakedUSDaiStorage.RedemptionState storage redemptionState_,\n        uint64 genesisTimestamp,\n        uint256 shares,\n        address controller\n    ) external returns (uint256) {\n        /* Validate active redemptions count is less than max allowed */\n        if (redemptionState_.redemptionIds[controller].length() == MAX_ACTIVE_REDEMPTIONS_COUNT) {\n            revert IStakedUSDai.InvalidRedemptionState();\n        }\n\n        /* Validate shares are greater than minimum redemption shares */\n        if (shares < MIN_REDEMPTION_SHARES) revert IStakedUSDai.InvalidAmount();\n\n        /* Compute redemption timestamp */\n        uint64 redemptionTimestamp = _nextRedemptionTimestamp(genesisTimestamp);\n\n        /* Assign redemption ID */\n        uint256 redemptionId = ++redemptionState_.index;\n\n        /* Get current tail */\n        uint256 tail = redemptionState_.tail;\n\n        /* Update current tail pointer to next redemption ID */\n        redemptionState_.redemptions[tail].next = redemptionId;\n\n        /* Update new tail state */\n        redemptionState_.redemptions[redemptionId] = IStakedUSDai.Redemption({\n            prev: tail,\n            next: 0,\n            pendingShares: shares,\n            redeemableShares: 0,\n            withdrawableAmount: 0,\n            controller: controller,\n            redemptionTimestamp: redemptionTimestamp\n        });\n        redemptionState_.tail = redemptionId;\n\n        /* Update pending shares */\n        redemptionState_.pending += shares;\n\n        /* If head is not set, set it to the new redemption ID */\n        if (redemptionState_.head == 0) {\n            redemptionState_.head = redemptionId;\n        }\n\n        /* Add redemption ID */\n        redemptionState_.redemptionIds[controller].add(redemptionId);\n\n        return redemptionId;\n    }\n\n    /**\n     * @notice Process pending redemptions\n     * @param redemptionState_ Redemption state\n     * @param shares Shares to process\n     * @param redemptionSharePrice_ Redemption share price\n     * @return Amount processed, true if all valid redemptions are serviced\n     */\n    function _processRedemptions(\n        StakedUSDaiStorage.RedemptionState storage redemptionState_,\n        uint256 shares,\n        uint256 redemptionSharePrice_\n    ) external returns (uint256, bool) {\n        /* Validate shares are available to be serviced */\n        if (redemptionState_.pending < shares) {\n            revert IStakedUSDai.InvalidRedemptionState();\n        }\n\n        /* Get head redemption ID */\n        uint256 head = redemptionState_.head;\n\n        /* If head is not set, revert */\n        if (head == 0) revert IStakedUSDai.InvalidRedemptionState();\n\n        /* Process redemptions */\n        uint256 remainingShares = shares;\n        uint256 amountProcessed;\n        while (remainingShares > 0 && head != 0) {\n            /* Get redemption */\n            IStakedUSDai.Redemption storage redemption_ = redemptionState_.redemptions[head];\n\n            /* Validate that redemption is past redemption timestamp */\n            if (redemption_.redemptionTimestamp >= block.timestamp) revert IStakedUSDai.InvalidRedemptionState();\n\n            /* Compute shares to fulfill */\n            uint256 fulfilledShares = Math.min(redemption_.pendingShares, remainingShares);\n\n            /* Compute amount to fulfill */\n            uint256 fulfilledAmount = Math.mulDiv(fulfilledShares, redemptionSharePrice_, FIXED_POINT_SCALE);\n\n            /* Update redemption pending, redeemable shares, and withdrawable amount */\n            redemption_.pendingShares -= fulfilledShares;\n            redemption_.redeemableShares += fulfilledShares;\n            redemption_.withdrawableAmount += fulfilledAmount;\n\n            /* Update remaining shares and amount processed */\n            remainingShares -= fulfilledShares;\n            amountProcessed += fulfilledAmount;\n\n            /* Emit RedemptionProcessed */\n            emit IStakedUSDai.RedemptionProcessed(\n                head, redemption_.controller, fulfilledShares, fulfilledAmount, redemption_.pendingShares\n            );\n\n            /* If redemption is completely fulfilled, update head */\n            if (redemption_.pendingShares == 0) head = redemption_.next;\n        }\n\n        /* If there are remaining shares, revert */\n        if (remainingShares != 0) revert IStakedUSDai.InvalidRedemptionState();\n\n        /* Update redemption state */\n        redemptionState_.head = head;\n        redemptionState_.pending -= shares;\n\n        /* If head is 0 or next redemption is not past redemption timestamp, it\n         * means all redemptions for the elapsed redemption windows are serviced */\n        return (amountProcessed, head == 0 || redemptionState_.redemptions[head].redemptionTimestamp >= block.timestamp);\n    }\n}\n"},"src/positionManagers/BasePositionManager.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\n\nimport \"../StakedUSDaiStorage.sol\";\nimport \"./PositionManager.sol\";\n\nimport \"../interfaces/IBasePositionManager.sol\";\n\n/**\n * @title Base Position Manager\n * @author USD.AI Foundation\n */\nabstract contract BasePositionManager is\n    AccessControlUpgradeable,\n    ReentrancyGuardUpgradeable,\n    PositionManager,\n    StakedUSDaiStorage,\n    IBasePositionManager\n{\n    /*------------------------------------------------------------------------*/\n    /* Immutable state */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Admin fee rate\n     */\n    uint256 internal immutable _baseYieldAdminFeeRate;\n\n    /*------------------------------------------------------------------------*/\n    /* Constructor */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Constructor\n     * @param baseYieldAdminFeeRate_ Base yield admin fee rate\n     */\n    constructor(\n        uint256 baseYieldAdminFeeRate_\n    ) {\n        _baseYieldAdminFeeRate = baseYieldAdminFeeRate_;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Internal helpers */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc PositionManager\n     */\n    function _assets(\n        ValuationType\n    ) internal view virtual override returns (uint256) {\n        /* Get base yield accrued */\n        uint256 baseYieldAccrued = _usdai.baseYieldAccrued();\n\n        /* Calculate admin fee */\n        uint256 adminFee = (baseYieldAccrued * _baseYieldAdminFeeRate) / BASIS_POINTS_SCALE;\n\n        /* Return total assets in terms of USDai */\n        return baseYieldAccrued - adminFee;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Getter */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IBasePositionManager\n     */\n    function claimableBaseYield() external view returns (uint256) {\n        return _usdai.baseYieldAccrued();\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Permissioned API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IBasePositionManager\n     */\n    function harvestBaseYield() external onlyRole(STRATEGY_ADMIN_ROLE) nonReentrant returns (uint256, uint256) {\n        /* Harvest base yield */\n        uint256 usdaiAmount = _usdai.harvest();\n\n        /* Calculate admin fee */\n        uint256 adminFee = (usdaiAmount * _baseYieldAdminFeeRate) / BASIS_POINTS_SCALE;\n\n        /* Update deposits balance with base yield minus admin fee */\n        _getDepositsStorage().balance += usdaiAmount - adminFee;\n\n        /* Transfer admin fee to admin fee recipient */\n        if (adminFee > 0) _usdai.transfer(_adminFeeRecipient, adminFee);\n\n        /* Emit BaseYieldDeposited */\n        emit BaseYieldDeposited(usdaiAmount - adminFee, adminFee);\n\n        return (usdaiAmount - adminFee, adminFee);\n    }\n}\n"},"src/positionManagers/LoanRouterPositionManager.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\n\nimport \"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol\";\n\nimport {PositionManager} from \"./PositionManager.sol\";\nimport {StakedUSDaiStorage} from \"../StakedUSDaiStorage.sol\";\n\nimport {ILoanRouterPositionManager} from \"../interfaces/ILoanRouterPositionManager.sol\";\n\nimport {IEscrowTimelock} from \"@usdai-loan-router-contracts/interfaces/IEscrowTimelock.sol\";\nimport {IEscrowTimelockHooks} from \"@usdai-loan-router-contracts/interfaces/IEscrowTimelockHooks.sol\";\nimport {IDepositTimelock} from \"@usdai-loan-router-contracts/interfaces/IDepositTimelock.sol\";\nimport {IDepositTimelockHooks} from \"@usdai-loan-router-contracts/interfaces/IDepositTimelockHooks.sol\";\nimport {ILoanRouterV2} from \"@usdai-loan-router-contracts/interfaces/ILoanRouterV2.sol\";\nimport {ILoanRouterV2Hooks} from \"@usdai-loan-router-contracts/interfaces/ILoanRouterV2Hooks.sol\";\n\nimport {LoanRouterPositionManagerLogic} from \"./LoanRouterPositionManagerLogic.sol\";\n\n/**\n * @title Loan Router Position Manager\n * @author USD.AI Foundation\n */\nabstract contract LoanRouterPositionManager is\n    AccessControlUpgradeable,\n    ReentrancyGuardUpgradeable,\n    PositionManager,\n    StakedUSDaiStorage,\n    ILoanRouterPositionManager,\n    IEscrowTimelockHooks,\n    IDepositTimelockHooks,\n    ILoanRouterV2Hooks\n{\n    /*------------------------------------------------------------------------*/\n    /* Constants */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit timelock storage location\n     * @dev keccak256(abi.encode(uint256(keccak256(\"stakedUSDai.depositTimelock\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant DEPOSIT_TIMELOCK_STORAGE_LOCATION =\n        0x7fab4664d57f16410d3bcb5fb74c23268a2f6f0b7b67ca2a4a44fc24e93b6300;\n\n    /**\n     * @notice Loans storage location\n     * @dev keccak256(abi.encode(uint256(keccak256(\"stakedUSDai.loans\")) - 1)) & ~bytes32(uint256(0xff));\n     */\n    bytes32 private constant LOANS_STORAGE_LOCATION = 0xeedf9bea8709bd441d5da250df505e80fc82bec74f9f1df28edf19fa1ed4bd00;\n\n    /*------------------------------------------------------------------------*/\n    /* Structures */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Repayment\n     * @param repayment Repayment amount\n     * @param adminFee Admin fee amount\n     */\n    struct Repayment {\n        uint256 repayment;\n        uint256 adminFee;\n    }\n\n    /**\n     * @notice Accrual state\n     * @param accrued Accrued interest\n     * @param rate Accrual rate\n     * @param timestamp Last accrual timestamp\n     */\n    struct Accrual {\n        uint256 accrued;\n        uint256 rate;\n        uint64 timestamp;\n    }\n\n    /**\n     * @notice Loan\n     * @param accrualRate Accrual rate\n     * @param pendingBalance Pending balance\n     * @param lastRepaymentTimestamp Last repayment timestamp\n     * @param liquidationTimestamp Liquidation timestamp\n     */\n    struct Loan {\n        uint256 accrualRate;\n        uint256 pendingBalance;\n        uint64 lastRepaymentTimestamp;\n        uint64 liquidationTimestamp;\n    }\n\n    /**\n     * @custom:storage-location erc7201:stakedUSDai.loans\n     * @param currencyTokens Currency tokens set (deprecated)\n     * @param repaymentBalances Repayment balances per currency token (deprecated)\n     * @param pendingBalances Pending loan balances per currency token\n     * @param interestAccruals Interest accruals per currency token\n     * @param loan Loan state by loan terms hash\n     */\n    struct Loans {\n        EnumerableSet.AddressSet currencyTokens;\n        mapping(address => Repayment) repaymentBalances;\n        mapping(address => uint256) pendingBalances;\n        mapping(address => Accrual) interestAccruals;\n        mapping(bytes32 => Loan) loan;\n    }\n\n    /**\n     * @custom:storage-location erc7201:stakedUSDai.depositTimelock\n     * @param balance Deposit timelock USDai balance\n     * @param amounts Deposit amount for each loan terms hash\n     */\n    struct DepositTimelock {\n        uint256 balance;\n        mapping(bytes32 => uint256) amounts;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Immutable state */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice V2 loan router\n     */\n    address internal immutable _loanRouterV2;\n\n    /**\n     * @notice Escrow timelock\n     */\n    address internal immutable _escrowTimelock;\n\n    /**\n     * @notice Deposit timelock\n     */\n    address internal immutable _depositTimelock;\n\n    /**\n     * @notice Admin fee rate\n     */\n    uint256 internal immutable _loanRouterAdminFeeRate;\n\n    /*------------------------------------------------------------------------*/\n    /* Constructor */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Constructor\n     * @param loanRouterV2_ V2 loan router\n     * @param loanRouterAdminFeeRate_ Loan router admin fee rate\n     */\n    constructor(address loanRouterV2_, uint256 loanRouterAdminFeeRate_) {\n        _loanRouterV2 = loanRouterV2_;\n\n        _escrowTimelock = ILoanRouterV2(loanRouterV2_).escrowTimelock();\n        _depositTimelock = ILoanRouterV2(loanRouterV2_).depositTimelock();\n        _loanRouterAdminFeeRate = loanRouterAdminFeeRate_;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function depositTimelockBalance() public view returns (uint256) {\n        /* Return USDai balance in deposit timelock */\n        return _getDepositTimelockStorage().balance;\n    }\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function loanRouterBalances() public view returns (uint256, uint256) {\n        return LoanRouterPositionManagerLogic.loanRouterBalances(_getLoansStorage(), address(_usdai));\n    }\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function accrualRate() external view returns (uint256) {\n        return _getLoansStorage().interestAccruals[address(_usdai)].rate;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Internal helpers */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get reference to deposit timelock storage\n     *\n     * @return $ Reference to deposit timelock storage\n     */\n    function _getDepositTimelockStorage() internal pure returns (DepositTimelock storage $) {\n        assembly {\n            $.slot := DEPOSIT_TIMELOCK_STORAGE_LOCATION\n        }\n    }\n\n    /**\n     * @notice Get reference to loans storage\n     *\n     * @return $ Reference to loans storage\n     */\n    function _getLoansStorage() internal pure returns (Loans storage $) {\n        assembly {\n            $.slot := LOANS_STORAGE_LOCATION\n        }\n    }\n\n    /**\n     * @inheritdoc PositionManager\n     */\n    function _assets(\n        PositionManager.ValuationType valuationType\n    ) internal view virtual override returns (uint256) {\n        (uint256 pendingLoanBalance, uint256 accruedLoanInterestBalance) = loanRouterBalances();\n\n        /* Get accrued escrow interest balance */\n        uint256 accruedEscrowInterestBalance = IEscrowTimelock(_escrowTimelock).accrued();\n\n        /* Return total assets in terms of USDai */\n        return depositTimelockBalance() + pendingLoanBalance\n            + (\n                (valuationType == PositionManager.ValuationType.OPTIMISTIC)\n                    ? (accruedLoanInterestBalance - (accruedLoanInterestBalance * _loanRouterAdminFeeRate / BASIS_POINTS_SCALE))\n                        + (\n                            accruedEscrowInterestBalance\n                                - (accruedEscrowInterestBalance * _loanRouterAdminFeeRate / BASIS_POINTS_SCALE)\n                        )\n                    : 0\n            );\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* ERC721 Receiver Hooks */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Handle receipt of an NFT\n     * @dev Required to receive ERC721 tokens (collateral from loans)\n     */\n    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {\n        return IERC721Receiver.onERC721Received.selector;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Escrow Timelock Hooks */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IEscrowTimelockHooks\n     */\n    function onEscrowWithdrawn(\n        address,\n        bytes32 loanTermsHash,\n        address,\n        uint256,\n        uint256 interestAmount\n    ) external nonReentrant {\n        /* Handle interest accrued */\n        LoanRouterPositionManagerLogic.escrowWithdrawn(\n            _getDepositsStorage(),\n            address(_usdai),\n            _escrowTimelock,\n            _loanRouterAdminFeeRate,\n            _adminFeeRecipient,\n            interestAmount\n        );\n\n        /* Emit LoanEscrowTimelockWithdrawn */\n        emit LoanEscrowTimelockWithdrawn(loanTermsHash, interestAmount);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Deposit Timelock Hooks */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc IDepositTimelockHooks\n     */\n    function onDepositWithdrawn(\n        address,\n        bytes32,\n        address,\n        uint256,\n        uint256,\n        uint256 refundDepositAmount\n    ) external nonReentrant {\n        /* Handle deposit timelock withdrawn */\n        LoanRouterPositionManagerLogic.depositWithdrawn(_getDepositsStorage(), _depositTimelock, refundDepositAmount);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Loan Router Hooks (V2) */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc ILoanRouterV2Hooks\n     */\n    function onLoanOriginated(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex\n    ) external nonReentrant {\n        LoanRouterPositionManagerLogic.loanOriginated(\n            _getDepositTimelockStorage(),\n            _getLoansStorage(),\n            loanTerms,\n            loanTermsHash,\n            trancheIndex,\n            address(_usdai),\n            _loanRouterV2\n        );\n    }\n\n    /**\n     * @inheritdoc ILoanRouterV2Hooks\n     */\n    function onLoanRepayment(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        uint256 loanBalance,\n        uint256 principal,\n        uint256 interest,\n        uint256 prepayment\n    ) external nonReentrant {\n        LoanRouterPositionManagerLogic.loanRepayment(\n            _getDepositsStorage(),\n            _getLoansStorage(),\n            loanTerms,\n            loanTermsHash,\n            trancheIndex,\n            loanBalance,\n            principal + prepayment,\n            interest,\n            _loanRouterV2,\n            _loanRouterAdminFeeRate,\n            _adminFeeRecipient\n        );\n    }\n\n    /**\n     * @inheritdoc ILoanRouterV2Hooks\n     */\n    function onLoanFeePaid(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 feeSpecIndex,\n        uint256 fee\n    ) external nonReentrant {\n        LoanRouterPositionManagerLogic.loanFeePaid(\n            _getDepositsStorage(), loanTerms, loanTermsHash, feeSpecIndex, fee, address(_usdai), _loanRouterV2\n        );\n    }\n\n    /**\n     * @inheritdoc ILoanRouterV2Hooks\n     */\n    function onLoanLiquidated(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex\n    ) external nonReentrant {\n        LoanRouterPositionManagerLogic.loanLiquidated(\n            _getLoansStorage(), loanTerms, loanTermsHash, trancheIndex, _loanRouterV2\n        );\n    }\n\n    /**\n     * @inheritdoc ILoanRouterV2Hooks\n     */\n    function onLoanCollateralLiquidated(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        uint256 principal,\n        uint256 interest\n    ) external nonReentrant {\n        LoanRouterPositionManagerLogic.loanCollateralLiquidated(\n            _getDepositsStorage(),\n            _getLoansStorage(),\n            loanTerms,\n            loanTermsHash,\n            trancheIndex,\n            principal,\n            interest,\n            _loanRouterV2,\n            _loanRouterAdminFeeRate,\n            _adminFeeRecipient\n        );\n    }\n\n    /**\n     * @inheritdoc ILoanRouterV2Hooks\n     */\n    function onLoanRefinanced(\n        ILoanRouterV2.LoanTermsV2 calldata oldLoanTerms,\n        ILoanRouterV2.LoanTermsV2 calldata newLoanTerms,\n        bytes32 oldLoanTermsHash,\n        bytes32 newLoanTermsHash,\n        uint8 trancheIndex,\n        uint256 cashOut,\n        uint256 cashIn\n    ) external nonReentrant {\n        LoanRouterPositionManagerLogic.loanRefinanced(\n            _getDepositTimelockStorage(),\n            _getLoansStorage(),\n            oldLoanTerms,\n            newLoanTerms,\n            oldLoanTermsHash,\n            newLoanTermsHash,\n            trancheIndex,\n            cashOut,\n            cashIn,\n            _loanRouterV2\n        );\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Permissioned API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function depositLoanEscrowTimelock(\n        bytes32 loanTermsHash,\n        uint256 usdaiAmount,\n        uint256 interestRate\n    ) external onlyRole(STRATEGY_ADMIN_ROLE) nonReentrant {\n        /* Handle deposit accounting and approval */\n        LoanRouterPositionManagerLogic.depositFunds(\n            _getDepositsStorage(),\n            _getRedemptionStateStorage(),\n            _getDepositTimelockStorage(),\n            address(_usdai),\n            usdaiAmount,\n            loanTermsHash,\n            _escrowTimelock\n        );\n\n        /* Deposit funds against the V2 router */\n        IEscrowTimelock(_escrowTimelock).deposit(\n            _loanRouterV2, loanTermsHash, address(_usdai), usdaiAmount, interestRate\n        );\n\n        /* Emit LoanEscrowTimelockDeposited */\n        emit LoanEscrowTimelockDeposited(loanTermsHash, usdaiAmount, interestRate);\n    }\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function depositLoanDepositTimelock(\n        bytes32 loanTermsHash,\n        uint256 usdaiAmount,\n        uint64 expiration\n    ) external onlyRole(STRATEGY_ADMIN_ROLE) nonReentrant {\n        /* Handle deposit accounting and approval */\n        LoanRouterPositionManagerLogic.depositFunds(\n            _getDepositsStorage(),\n            _getRedemptionStateStorage(),\n            _getDepositTimelockStorage(),\n            address(_usdai),\n            usdaiAmount,\n            loanTermsHash,\n            _depositTimelock\n        );\n\n        /* Deposit funds against the V2 router */\n        IDepositTimelock(_depositTimelock).deposit(\n            _loanRouterV2, loanTermsHash, address(_usdai), usdaiAmount, expiration\n        );\n\n        /* Emit LoanDepositTimelockDeposited */\n        emit LoanDepositTimelockDeposited(loanTermsHash, usdaiAmount, expiration);\n    }\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function cancelLoanEscrowTimelock(\n        bytes32 loanTermsHash\n    ) external onlyRole(STRATEGY_ADMIN_ROLE) nonReentrant {\n        uint256 usdaiAmount = LoanRouterPositionManagerLogic.withdrawFunds(\n            _getDepositsStorage(), _getDepositTimelockStorage(), loanTermsHash\n        );\n\n        /* Cancel deposit */\n        (uint256 depositAmount, uint256 interestAmount) =\n            IEscrowTimelock(_escrowTimelock).cancel(_loanRouterV2, loanTermsHash);\n        if (depositAmount != usdaiAmount) revert InvalidTimelockCancellation();\n\n        /* Handle interest accrued */\n        LoanRouterPositionManagerLogic.escrowCancelled(\n            _getDepositsStorage(), address(_usdai), _loanRouterAdminFeeRate, _adminFeeRecipient, interestAmount\n        );\n\n        /* Emit LoanEscrowTimelockCancelled */\n        emit LoanEscrowTimelockCancelled(loanTermsHash, usdaiAmount, interestAmount);\n    }\n\n    /**\n     * @inheritdoc ILoanRouterPositionManager\n     */\n    function cancelLoanDepositTimelock(\n        bytes32 loanTermsHash\n    ) external onlyRole(STRATEGY_ADMIN_ROLE) nonReentrant {\n        uint256 usdaiAmount = LoanRouterPositionManagerLogic.withdrawFunds(\n            _getDepositsStorage(), _getDepositTimelockStorage(), loanTermsHash\n        );\n\n        /* Cancel deposit */\n        if (IDepositTimelock(_depositTimelock).cancel(_loanRouterV2, loanTermsHash) != usdaiAmount) {\n            revert InvalidTimelockCancellation();\n        }\n\n        /* Emit LoanDepositTimelockCancelled */\n        emit LoanDepositTimelockCancelled(loanTermsHash, usdaiAmount);\n    }\n}\n"},"src/interfaces/IStakedUSDai.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport \"./IBasePositionManager.sol\";\n\n/**\n * @title Staked USDai Interface\n * @author USD.AI Foundation\n */\ninterface IStakedUSDai is IBasePositionManager {\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid address\n     */\n    error InvalidAddress();\n\n    /**\n     * @notice Invalid caller\n     */\n    error InvalidCaller();\n\n    /**\n     * @notice Invalid redemption state\n     */\n    error InvalidRedemptionState();\n\n    /**\n     * @notice Invalid amount\n     */\n    error InvalidAmount();\n\n    /**\n     * @notice Disabled implementation\n     */\n    error DisabledImplementation();\n\n    /**\n     * @notice Blacklisted address\n     * @param value Address\n     */\n    error BlacklistedAddress(address value);\n\n    /*------------------------------------------------------------------------*/\n    /* Structures */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Redemption\n     * @param prev Previous redemption index in queue\n     * @param next Next redemption index in queue\n     * @param pendingShares Pending shares\n     * @param redeemableShares Shares that can be redeemed\n     * @param withdrawableAmount Amount that can be withdrawn\n     * @param controller Controller address\n     * @param redemptionTimestamp Redemption timestamp\n     */\n    struct Redemption {\n        uint256 prev;\n        uint256 next;\n        uint256 pendingShares;\n        uint256 redeemableShares;\n        uint256 withdrawableAmount;\n        address controller;\n        uint64 redemptionTimestamp;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Redemption Processed\n     * @param redemptionId Redemption ID\n     * @param controller Controller\n     * @param fulfilledShares Fulfilled shares\n     * @param amount Fulfilled amount\n     * @param pendingShares Pending shares\n     */\n    event RedemptionProcessed(\n        uint256 indexed redemptionId,\n        address indexed controller,\n        uint256 fulfilledShares,\n        uint256 amount,\n        uint256 pendingShares\n    );\n\n    /**\n     * @notice Redemptions Serviced\n     * @param shares Shares processed\n     * @param amount Amount processed\n     * @param allRedemptionsServiced True if all redemptions are serviced\n     */\n    event RedemptionsServiced(uint256 shares, uint256 amount, bool allRedemptionsServiced);\n\n    /**\n     * @notice Referred Deposit\n     * @param sender Sender address\n     * @param receiver Receiver address\n     * @param assets Assets deposited\n     * @param shares Shares minted\n     * @param referral Referral code\n     */\n    event ReferredDeposit(\n        address indexed sender, address indexed receiver, uint256 assets, uint256 shares, uint16 referral\n    );\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get total shares\n     * @return Total shares\n     */\n    function totalShares() external view returns (uint256);\n\n    /**\n     * @notice Get redemption queue info\n     * @return index Redemption index\n     * @return head Redemption head\n     * @return tail Redemption tail\n     * @return pending Redemption shares pending\n     * @return balance Redemption balance\n     */\n    function redemptionQueueInfo()\n        external\n        view\n        returns (uint256 index, uint256 head, uint256 tail, uint256 pending, uint256 balance);\n\n    /**\n     * @notice Get redemption timestamp\n     * @return Redemption timestamp\n     */\n    function redemptionTimestamp() external view returns (uint64);\n\n    /**\n     * @notice Get redemption\n     * @param redemptionId Redemption ID\n     * @return Redemption\n     * @return Shares ahead\n     */\n    function redemption(\n        uint256 redemptionId\n    ) external view returns (Redemption memory, uint256);\n\n    /**\n     * @notice Get redemption IDs\n     * @param controller Controller\n     * @return Redemption IDs\n     */\n    function redemptionIds(\n        address controller\n    ) external view returns (uint256[] memory);\n\n    /**\n     * @notice Get net asset value\n     * @return Net asset value\n     */\n    function nav() external view returns (uint256);\n\n    /**\n     * @notice Get deposit and redemption balances\n     * @return Deposit balance\n     * @return Redemption balance\n     */\n    function balances() external view returns (uint256, uint256);\n\n    /**\n     * @notice Get admin fee recipient\n     * @return Admin fee recipient\n     */\n    function adminFeeRecipient() external view returns (address);\n\n    /**\n     * @notice Get deposit share price\n     * @return Deposit share price\n     */\n    function depositSharePrice() external view returns (uint256);\n\n    /**\n     * @notice Get redemption share price\n     * @return Redemption share price\n     */\n    function redemptionSharePrice() external view returns (uint256);\n\n    /**\n     * @notice Get bridged supply\n     * @return Bridged supply\n     */\n    function bridgedSupply() external view returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Overload of IERC4626 deposit\n     * @param amount Amount to deposit\n     * @param receiver Receiver address\n     * @param minShares Minimum shares\n     * @return Shares minted\n     */\n    function deposit(uint256 amount, address receiver, uint256 minShares) external returns (uint256);\n\n    /**\n     * @notice Overload of IERC4626 deposit\n     * @param amount Amount to deposit\n     * @param receiver Receiver address\n     * @param minShares Minimum shares\n     * @param referral Referral code\n     * @return Shares minted\n     */\n    function deposit(uint256 amount, address receiver, uint256 minShares, uint16 referral) external returns (uint256);\n\n    /**\n     * @notice Overload of IERC4626 mint\n     * @param shares Shares to mint\n     * @param receiver Receiver address\n     * @param maxAmount Maximum amount\n     * @return Amount minted\n     */\n    function mint(uint256 shares, address receiver, uint256 maxAmount) external returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Pause Admin API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Pause the contract\n     */\n    function pause() external;\n\n    /**\n     * @notice Unpause the contract\n     */\n    function unpause() external;\n\n    /*------------------------------------------------------------------------*/\n    /* Strategy Admin API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Service pending redemption requests\n     * @param shares Shares to process\n     * @return Amount processed\n     */\n    function serviceRedemptions(\n        uint256 shares\n    ) external returns (uint256);\n}\n"},"src/interfaces/IERC7540.sol":{"content":"// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IERC7540Operator {\n    /**\n     * @dev The event emitted when an operator is set.\n     *\n     * @param controller The address of the controller.\n     * @param operator The address of the operator.\n     * @param approved The approval status.\n     */\n    event OperatorSet(address indexed controller, address indexed operator, bool approved);\n\n    /**\n     * @dev Sets or removes an operator for the caller.\n     *\n     * @param operator The address of the operator.\n     * @param approved The approval status.\n     * @return Whether the call was executed successfully or not\n     */\n    function setOperator(address operator, bool approved) external returns (bool);\n\n    /**\n     * @dev Returns `true` if the `operator` is approved as an operator for an `controller`.\n     *\n     * @param controller The address of the controller.\n     * @param operator The address of the operator.\n     * @return status The approval status\n     */\n    function isOperator(address controller, address operator) external view returns (bool status);\n}\n\ninterface IERC7540Redeem {\n    event RedeemRequest(\n        address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 shares\n    );\n\n    /**\n     * @dev Assumes control of shares from sender into the Vault and submits a Request for asynchronous redeem.\n     *\n     * - MUST support a redeem Request flow where the control of shares is taken from sender directly\n     *   where msg.sender has ERC-20 approval over the shares of owner.\n     * - MUST revert if all of shares cannot be requested for redeem.\n     *\n     * @param shares the amount of shares to be redeemed to transfer from owner\n     * @param controller the controller of the request who will be able to operate the request\n     * @param owner the source of the shares to be redeemed\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault's share token.\n     */\n    function requestRedeem(uint256 shares, address controller, address owner) external returns (uint256 requestId);\n\n    /**\n     * @dev Returns the amount of requested shares in Pending state.\n     *\n     * - MUST NOT include any shares in Claimable state for redeem or withdraw.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input.\n     */\n    function pendingRedeemRequest(\n        uint256 requestId,\n        address controller\n    ) external view returns (uint256 pendingShares);\n\n    /**\n     * @dev Returns the amount of requested shares in Claimable state for the controller to redeem or withdraw.\n     *\n     * - MUST NOT include any shares in Pending state for redeem or withdraw.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT revert unless due to integer overflow caused by an unreasonably large input.\n     */\n    function claimableRedeemRequest(\n        uint256 requestId,\n        address controller\n    ) external view returns (uint256 claimableShares);\n}\n"},"src/interfaces/IERC7575.sol":{"content":"// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IERC7575 {\n    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n    event Withdraw(\n        address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares\n    );\n\n    /**\n     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n     *\n     * - MUST be an ERC-20 token contract.\n     * - MUST NOT revert.\n     */\n    function asset() external view returns (address assetTokenAddress);\n\n    /**\n     * @dev Returns the address of the share token\n     *\n     * - MUST be an ERC-20 token contract.\n     * - MUST NOT revert.\n     */\n    function share() external view returns (address shareTokenAddress);\n\n    /**\n     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToShares(\n        uint256 assets\n    ) external view returns (uint256 shares);\n\n    /**\n     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n     * scenario where all the conditions are met.\n     *\n     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT show any variations depending on the caller.\n     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n     * - MUST NOT revert.\n     *\n     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n     * from.\n     */\n    function convertToAssets(\n        uint256 shares\n    ) external view returns (uint256 assets);\n\n    /**\n     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n     *\n     * - SHOULD include any compounding that occurs from yield.\n     * - MUST be inclusive of any fees that are charged against assets in the Vault.\n     * - MUST NOT revert.\n     */\n    function totalAssets() external view returns (uint256 totalManagedAssets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n     * through a deposit call.\n     *\n     * - MUST return a limited value if receiver is subject to some deposit limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n     * - MUST NOT revert.\n     */\n    function maxDeposit(\n        address receiver\n    ) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n     *   in the same transaction.\n     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewDeposit(\n        uint256 assets\n    ) external view returns (uint256 shares);\n\n    /**\n     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   deposit execution, and are accounted for during deposit.\n     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n     * - MUST return a limited value if receiver is subject to some mint limit.\n     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n     * - MUST NOT revert.\n     */\n    function maxMint(\n        address receiver\n    ) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n     * current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n     *   same transaction.\n     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n     *   would be accepted, regardless if the user has enough tokens approved, etc.\n     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by minting.\n     */\n    function previewMint(\n        uint256 shares\n    ) external view returns (uint256 assets);\n\n    /**\n     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n     *\n     * - MUST emit the Deposit event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n     *   execution, and are accounted for during mint.\n     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n     *   approving enough underlying tokens to the Vault contract, etc).\n     *\n     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n     */\n    function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n    /**\n     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n     * Vault, through a withdraw call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxWithdraw(\n        address owner\n    ) external view returns (uint256 maxAssets);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n     *   called\n     *   in the same transaction.\n     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n     */\n    function previewWithdraw(\n        uint256 assets\n    ) external view returns (uint256 shares);\n\n    /**\n     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   withdraw execution, and are accounted for during withdraw.\n     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);\n\n    /**\n     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n     * through a redeem call.\n     *\n     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n     * - MUST NOT revert.\n     */\n    function maxRedeem(\n        address owner\n    ) external view returns (uint256 maxShares);\n\n    /**\n     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,\n     * given current on-chain conditions.\n     *\n     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n     *   same transaction.\n     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n     *   redemption would be accepted, regardless if the user has enough shares, etc.\n     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n     * - MUST NOT revert.\n     *\n     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n     */\n    function previewRedeem(\n        uint256 shares\n    ) external view returns (uint256 assets);\n\n    /**\n     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n     *\n     * - MUST emit the Withdraw event.\n     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n     *   redeem execution, and are accounted for during redeem.\n     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n     *   not having enough shares, etc).\n     *\n     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n     * Those methods should be performed separately.\n     */\n    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);\n}\n"},"src/interfaces/IMintableBurnable.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Mintable Burnable Interface\n * @author USD.AI Foundation\n */\ninterface IMintableBurnable {\n    /*------------------------------------------------------------------------*/\n    /* Minter API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Mint\n     * @param to Account\n     * @param amount Amount\n     */\n    function mint(address to, uint256 amount) external;\n\n    /**\n     * @notice Burn\n     * @param from Account\n     * @param amount Amount\n     */\n    function burn(address from, uint256 amount) external;\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.20;\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"},"lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)\n\npragma solidity ^0.8.20;\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"},"lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.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 reininitialization) 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 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        assembly {\n            $.slot := INITIALIZABLE_STORAGE\n        }\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/utils/Address.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)\n\npragma solidity ^0.8.20;\n\nimport {Errors} from \"./Errors.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\n        (bool success, bytes memory returndata) = recipient.call{value: amount}(\"\");\n        if (!success) {\n            _revert(returndata);\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, bytes memory returndata) = target.call{value: value}(data);\n        return verifyCallResultFromTarget(target, success, returndata);\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, bytes memory returndata) = target.staticcall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\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, bytes memory returndata) = target.delegatecall(data);\n        return verifyCallResultFromTarget(target, success, returndata);\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    function verifyCallResultFromTarget(\n        address target,\n        bool success,\n        bytes memory returndata\n    ) internal view returns (bytes memory) {\n        if (!success) {\n            _revert(returndata);\n        } else {\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 (returndata.length == 0 && target.code.length == 0) {\n                revert AddressEmptyCode(target);\n            }\n            return returndata;\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            _revert(returndata);\n        } else {\n            return returndata;\n        }\n    }\n\n    /**\n     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.\n     */\n    function _revert(bytes memory returndata) private pure {\n        // Look for revert reason and bubble it up if present\n        if (returndata.length > 0) {\n            // The easiest way to bubble the revert reason is using memory via assembly\n            assembly (\"memory-safe\") {\n                let returndata_size := mload(returndata)\n                revert(add(32, returndata), returndata_size)\n            }\n        } else {\n            revert Errors.FailedCall();\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol":{"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 \"../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"},"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.20;\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"},"lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)\npragma solidity ^0.8.20;\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-20.\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"},"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Permit.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Permit.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n *\n * ==== Security Considerations\n *\n * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature\n * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be\n * considered as an intention to spend the allowance in any specific way. The second is that because permits have\n * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should\n * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be\n * generally recommended is:\n *\n * ```solidity\n * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {\n *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}\n *     doThing(..., value);\n * }\n *\n * function doThing(..., uint256 value) public {\n *     token.safeTransferFrom(msg.sender, address(this), value);\n *     ...\n * }\n * ```\n *\n * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of\n * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also\n * {SafeERC20-safeTransferFrom}).\n *\n * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so\n * contracts should have entry points that don't rely on permit.\n */\ninterface IERC20Permit {\n    /**\n     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n     * given ``owner``'s signed approval.\n     *\n     * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n     * ordering also apply here.\n     *\n     * Emits an {Approval} event.\n     *\n     * Requirements:\n     *\n     * - `spender` cannot be the zero address.\n     * - `deadline` must be a timestamp in the future.\n     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n     * over the EIP712-formatted function arguments.\n     * - the signature must use ``owner``'s current nonce (see {nonces}).\n     *\n     * For more information on the signature format, see the\n     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n     * section].\n     *\n     * CAUTION: See Security Considerations above.\n     */\n    function permit(\n        address owner,\n        address spender,\n        uint256 value,\n        uint256 deadline,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) external;\n\n    /**\n     * @dev Returns the current nonce for `owner`. This value must be\n     * included whenever a signature is generated for {permit}.\n     *\n     * Every successful call to {permit} increases ``owner``'s nonce by one. This\n     * prevents a signature from being used multiple times.\n     */\n    function nonces(address owner) external view returns (uint256);\n\n    /**\n     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n     */\n    // solhint-disable-next-line func-name-mixedcase\n    function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n"},"lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS\n    }\n\n    /**\n     * @dev The signature derives the `address(0)`.\n     */\n    error ECDSAInvalidSignature();\n\n    /**\n     * @dev The signature has an invalid length.\n     */\n    error ECDSAInvalidSignatureLength(uint256 length);\n\n    /**\n     * @dev The signature has an S value that is in the upper half order.\n     */\n    error ECDSAInvalidSignatureS(bytes32 s);\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not\n     * return address(0) without also returning an error description. Errors are documented using an enum (error type)\n     * and a bytes32 providing additional information about the error.\n     *\n     * If no error is returned, then the address can be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes memory signature\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            assembly (\"memory-safe\") {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]\n     */\n    function tryRecover(\n        bytes32 hash,\n        bytes32 r,\n        bytes32 vs\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        unchecked {\n            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n            // We do not check for an overflow here since the shift operation results in 0 or 1.\n            uint8 v = uint8((uint256(vs) >> 255) + 27);\n            return tryRecover(hash, v, r, s);\n        }\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function tryRecover(\n        bytes32 hash,\n        uint8 v,\n        bytes32 r,\n        bytes32 s\n    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS, s);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature, bytes32(0));\n        }\n\n        return (signer, RecoverError.NoError, bytes32(0));\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);\n        _throwError(error, errorArg);\n        return recovered;\n    }\n\n    /**\n     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.\n     */\n    function _throwError(RecoverError error, bytes32 errorArg) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert ECDSAInvalidSignature();\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert ECDSAInvalidSignatureLength(uint256(errorArg));\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert ECDSAInvalidSignatureS(errorArg);\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/cryptography/EIP712Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol)\n\npragma solidity ^0.8.20;\n\nimport {MessageHashUtils} from \"@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol\";\nimport {IERC5267} from \"@openzeppelin/contracts/interfaces/IERC5267.sol\";\nimport {Initializable} from \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.\n *\n * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose\n * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract\n * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to\n * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.\n *\n * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding\n * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA\n * ({_hashTypedDataV4}).\n *\n * The implementation of the domain separator was designed to be as efficient as possible while still properly updating\n * the chain id to protect against replay attacks on an eventual fork of the chain.\n *\n * NOTE: This contract implements the version of the encoding known as \"v4\", as implemented by the JSON RPC method\n * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].\n *\n * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain\n * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the\n * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.\n */\nabstract contract EIP712Upgradeable is Initializable, IERC5267 {\n    bytes32 private constant TYPE_HASH =\n        keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.EIP712\n    struct EIP712Storage {\n        /// @custom:oz-renamed-from _HASHED_NAME\n        bytes32 _hashedName;\n        /// @custom:oz-renamed-from _HASHED_VERSION\n        bytes32 _hashedVersion;\n\n        string _name;\n        string _version;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.EIP712\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;\n\n    function _getEIP712Storage() private pure returns (EIP712Storage storage $) {\n        assembly {\n            $.slot := EIP712StorageLocation\n        }\n    }\n\n    /**\n     * @dev Initializes the domain separator and parameter caches.\n     *\n     * The meaning of `name` and `version` is specified in\n     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:\n     *\n     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.\n     * - `version`: the current major version of the signing domain.\n     *\n     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart\n     * contract upgrade].\n     */\n    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {\n        __EIP712_init_unchained(name, version);\n    }\n\n    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {\n        EIP712Storage storage $ = _getEIP712Storage();\n        $._name = name;\n        $._version = version;\n\n        // Reset prior values in storage if upgrading\n        $._hashedName = 0;\n        $._hashedVersion = 0;\n    }\n\n    /**\n     * @dev Returns the domain separator for the current chain.\n     */\n    function _domainSeparatorV4() internal view returns (bytes32) {\n        return _buildDomainSeparator();\n    }\n\n    function _buildDomainSeparator() private view returns (bytes32) {\n        return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));\n    }\n\n    /**\n     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this\n     * function returns the hash of the fully encoded EIP712 message for this domain.\n     *\n     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:\n     *\n     * ```solidity\n     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(\n     *     keccak256(\"Mail(address to,string contents)\"),\n     *     mailTo,\n     *     keccak256(bytes(mailContents))\n     * )));\n     * address signer = ECDSA.recover(digest, signature);\n     * ```\n     */\n    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {\n        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);\n    }\n\n    /**\n     * @dev See {IERC-5267}.\n     */\n    function eip712Domain()\n        public\n        view\n        virtual\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        )\n    {\n        EIP712Storage storage $ = _getEIP712Storage();\n        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized\n        // and the EIP712 domain is not reliable, as it will be missing name and version.\n        require($._hashedName == 0 && $._hashedVersion == 0, \"EIP712: Uninitialized\");\n\n        return (\n            hex\"0f\", // 01111\n            _EIP712Name(),\n            _EIP712Version(),\n            block.chainid,\n            address(this),\n            bytes32(0),\n            new uint256[](0)\n        );\n    }\n\n    /**\n     * @dev The name parameter for the EIP712 domain.\n     *\n     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n     * are a concern.\n     */\n    function _EIP712Name() internal view virtual returns (string memory) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        return $._name;\n    }\n\n    /**\n     * @dev The version parameter for the EIP712 domain.\n     *\n     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs\n     * are a concern.\n     */\n    function _EIP712Version() internal view virtual returns (string memory) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        return $._version;\n    }\n\n    /**\n     * @dev The hash of the name parameter for the EIP712 domain.\n     *\n     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.\n     */\n    function _EIP712NameHash() internal view returns (bytes32) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        string memory name = _EIP712Name();\n        if (bytes(name).length > 0) {\n            return keccak256(bytes(name));\n        } else {\n            // If the name is empty, the contract may have been upgraded without initializing the new storage.\n            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.\n            bytes32 hashedName = $._hashedName;\n            if (hashedName != 0) {\n                return hashedName;\n            } else {\n                return keccak256(\"\");\n            }\n        }\n    }\n\n    /**\n     * @dev The hash of the version parameter for the EIP712 domain.\n     *\n     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.\n     */\n    function _EIP712VersionHash() internal view returns (bytes32) {\n        EIP712Storage storage $ = _getEIP712Storage();\n        string memory version = _EIP712Version();\n        if (bytes(version).length > 0) {\n            return keccak256(bytes(version));\n        } else {\n            // If the version is empty, the contract may have been upgraded without initializing the new storage.\n            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.\n            bytes32 hashedVersion = $._hashedVersion;\n            if (hashedVersion != 0) {\n                return hashedVersion;\n            } else {\n                return keccak256(\"\");\n            }\n        }\n    }\n}\n"},"lib/openzeppelin-contracts-upgradeable/contracts/utils/NoncesUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol)\npragma solidity ^0.8.20;\nimport {Initializable} from \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides tracking nonces for addresses. Nonces will only increment.\n */\nabstract contract NoncesUpgradeable is Initializable {\n    /**\n     * @dev The nonce used for an `account` is not the expected current nonce.\n     */\n    error InvalidAccountNonce(address account, uint256 currentNonce);\n\n    /// @custom:storage-location erc7201:openzeppelin.storage.Nonces\n    struct NoncesStorage {\n        mapping(address account => uint256) _nonces;\n    }\n\n    // keccak256(abi.encode(uint256(keccak256(\"openzeppelin.storage.Nonces\")) - 1)) & ~bytes32(uint256(0xff))\n    bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00;\n\n    function _getNoncesStorage() private pure returns (NoncesStorage storage $) {\n        assembly {\n            $.slot := NoncesStorageLocation\n        }\n    }\n\n    function __Nonces_init() internal onlyInitializing {\n    }\n\n    function __Nonces_init_unchained() internal onlyInitializing {\n    }\n    /**\n     * @dev Returns the next unused nonce for an address.\n     */\n    function nonces(address owner) public view virtual returns (uint256) {\n        NoncesStorage storage $ = _getNoncesStorage();\n        return $._nonces[owner];\n    }\n\n    /**\n     * @dev Consumes a nonce.\n     *\n     * Returns the current value and increments nonce.\n     */\n    function _useNonce(address owner) internal virtual returns (uint256) {\n        NoncesStorage storage $ = _getNoncesStorage();\n        // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be\n        // decremented or reset. This guarantees that the nonce never overflows.\n        unchecked {\n            // It is important to do x++ and not ++x here.\n            return $._nonces[owner]++;\n        }\n    }\n\n    /**\n     * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`.\n     */\n    function _useCheckedNonce(address owner, uint256 nonce) internal virtual {\n        uint256 current = _useNonce(owner);\n        if (nonce != current) {\n            revert InvalidAccountNonce(owner, current);\n        }\n    }\n}\n"},"lib/usdai-loan-router-contracts/src/interfaces/ILoanRouterV2.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Loan Router V2 Interface\n * @author USD.AI Foundation\n */\ninterface ILoanRouterV2 {\n    /*------------------------------------------------------------------------*/\n    /* Structures */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit type\n     * @param DepositTimelock Deposit timelock\n     * @param EscrowTimelock Escrow timelock\n     */\n    enum DepositType {\n        DepositTimelock,\n        EscrowTimelock\n    }\n\n    /**\n     * @notice Lender deposit info\n     * @param depositType Deposit type\n     * @param data Deposit data passed to timelock\n     */\n    struct LenderDepositInfo {\n        DepositType depositType;\n        bytes data;\n    }\n\n    /**\n     * @notice Tranche specification\n     * @param lender Lender\n     * @param amount Amount\n     * @param rate Rate\n     */\n    struct TrancheSpec {\n        address lender;\n        uint256 amount;\n        uint256 rate;\n    }\n\n    /**\n     * @notice Fee specification\n     * @param kind Fee event kind\n     * @param recipient Fee recipient (zero address for default)\n     * @param model Fee model contract address\n     * @param options Encoded fee model options\n     */\n    struct FeeSpec {\n        FeeKind kind;\n        address recipient;\n        address model;\n        bytes options;\n    }\n\n    /**\n     * @notice Fee event kind\n     * @param Origination Fee charged when the loan originates\n     * @param Repayment Fee charged on each repayment\n     * @param Exit Fee charged when the loan is repaid in full\n     * @param Liquidation Fee charged when the loan is liquidated\n     * @param Refinance Fee charged when the loan is refinanced\n     */\n    enum FeeKind {\n        Origination,\n        Repayment,\n        Exit,\n        Liquidation,\n        Refinance\n    }\n\n    /**\n     * @notice Interest rate specification\n     * @param model Interest rate model contract address\n     * @param options Encoded interest rate model options\n     */\n    struct InterestRateSpec {\n        address model;\n        bytes options;\n    }\n\n    /**\n     * @notice Repayment specification\n     * @param totalDurationDays Total loan duration in days\n     * @param day Day of month repayments are due\n     * @param timezoneOffsetSeconds UTC offset in seconds\n     */\n    struct RepaymentSpec {\n        uint16 totalDurationDays;\n        uint8 day;\n        int32 timezoneOffsetSeconds;\n    }\n\n    /**\n     * @notice Loan terms specification\n     * @param expiration Loan offer expiration timestamp\n     * @param borrower Borrower address\n     * @param currencyToken Currency token\n     * @param collateralToken Collateral token\n     * @param repaymentSpec Repayment specification\n     * @param interestRateSpec Interest rate specification\n     * @param collateralTokenIds Collateral token IDs\n     * @param trancheSpecs Tranche specifications\n     * @param feeSpecs Fee specifications\n     * @param approvalAddresses Addresses required to approve the loan\n     * @param options Options data reserved for future extensions\n     */\n    struct LoanTermsV2 {\n        uint64 expiration;\n        address borrower;\n        address currencyToken;\n        address collateralToken;\n        RepaymentSpec repaymentSpec;\n        InterestRateSpec interestRateSpec;\n        uint256[] collateralTokenIds;\n        TrancheSpec[] trancheSpecs;\n        FeeSpec[] feeSpecs;\n        address[] approvalAddresses;\n        bytes options;\n    }\n\n    /**\n     * @notice Loan status\n     * @param Uninitialized Loan has not been initialized\n     * @param Active Loan is active\n     * @param Repaid Loan has been repaid\n     * @param Breached Loan is in breach\n     * @param Liquidated Loan has been liquidated\n     * @param CollateralLiquidated Loan collateral has been liquidated\n     */\n    enum LoanStatus {\n        Uninitialized,\n        Active,\n        Repaid,\n        Breached,\n        Liquidated,\n        CollateralLiquidated\n    }\n\n    /**\n     * @notice Loan state\n     * @param status Loan status\n     * @param repaymentCount Number of completed repayments\n     * @param originationTimestamp Loan origination timestamp\n     * @param balance Scaled loan balance\n     */\n    struct LoanState {\n        LoanStatus status;\n        uint16 repaymentCount;\n        uint64 originationTimestamp;\n        uint256 balance;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid deposit type\n     */\n    error InvalidDepositType();\n\n    /**\n     * @notice Invalid amount\n     */\n    error InvalidAmount();\n\n    /**\n     * @notice Invalid address\n     */\n    error InvalidAddress();\n\n    /**\n     * @notice Invalid caller\n     */\n    error InvalidCaller();\n\n    /**\n     * @notice Invalid loan state\n     */\n    error InvalidLoanState();\n\n    /**\n     * @notice Invalid length\n     */\n    error InvalidLength();\n\n    /**\n     * @notice Invalid loan terms\n     * @param reason Reason\n     */\n    error InvalidLoanTerms(string reason);\n\n    /**\n     * @notice Invalid signature\n     */\n    error InvalidSignature();\n\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Emitted when loan is originated\n     * @param loanTermsHash Loan terms hash\n     * @param loanTerms Encoded loan terms\n     */\n    event LoanOriginated(bytes32 indexed loanTermsHash, bytes loanTerms);\n\n    /**\n     * @notice Emitted when lender position is minted\n     * @param loanTermsHash Loan terms hash\n     * @param lender Lender address\n     * @param trancheIndex Tranche index\n     * @param tokenId Token ID\n     */\n    event LenderPositionMinted(\n        bytes32 indexed loanTermsHash, address indexed lender, uint8 indexed trancheIndex, uint256 tokenId\n    );\n\n    /**\n     * @notice Emitted when lender is repaid\n     * @param loanTermsHash Loan terms hash\n     * @param lender Lender address\n     * @param trancheIndex Tranche index\n     * @param principal Principal repaid\n     * @param interest Interest paid\n     * @param prepay Prepayment\n     */\n    event LenderRepaid(\n        bytes32 indexed loanTermsHash,\n        address indexed lender,\n        uint8 indexed trancheIndex,\n        uint256 principal,\n        uint256 interest,\n        uint256 prepay\n    );\n\n    /**\n     * @notice Emitted when loan is repaid\n     * @param loanTermsHash Loan terms hash\n     * @param borrower Borrower address\n     * @param principal Principal repaid\n     * @param interest Interest paid\n     * @param prepayment Prepayment\n     * @param fee Fee paid\n     * @param isRepaid Whether loan is fully repaid\n     */\n    event LoanRepaid(\n        bytes32 indexed loanTermsHash,\n        address indexed borrower,\n        uint256 principal,\n        uint256 interest,\n        uint256 prepayment,\n        uint256 fee,\n        bool isRepaid\n    );\n\n    /**\n     * @notice Emitted when loan is refinanced\n     * @param oldLoanTermsHash Old loan terms hash\n     * @param newLoanTermsHash New loan terms hash\n     * @param newLoanTerms New loan terms\n     * @param cashOut Net unscaled cash-out to the borrower, zero when the refinance is cash-in\n     * @param cashIn Net unscaled cash-in from the borrower, zero when the refinance is cash-out\n     * @param refinanceFee Refinance fee paid\n     */\n    event LoanRefinanced(\n        bytes32 indexed oldLoanTermsHash,\n        bytes32 indexed newLoanTermsHash,\n        bytes newLoanTerms,\n        uint256 cashOut,\n        uint256 cashIn,\n        uint256 refinanceFee\n    );\n\n    /**\n     * @notice Emitted when loan is set to breached\n     * @param loanTermsHash Loan terms hash\n     */\n    event LoanBreached(bytes32 indexed loanTermsHash);\n\n    /**\n     * @notice Emitted when loan is liquidated\n     * @param loanTermsHash Loan terms hash\n     */\n    event LoanLiquidated(bytes32 indexed loanTermsHash);\n\n    /**\n     * @notice Emitted when lender is refinance repaid\n     * @param loanTermsHash Loan terms hash\n     * @param lender Lender address\n     * @param trancheIndex Tranche index\n     * @param principal Principal repaid\n     */\n    event LenderRefinanceRepaid(\n        bytes32 indexed loanTermsHash, address indexed lender, uint8 indexed trancheIndex, uint256 principal\n    );\n\n    /**\n     * @notice Emitted when lender is liquidation repaid\n     * @param loanTermsHash Loan terms hash\n     * @param lender Lender address\n     * @param trancheIndex Tranche index\n     * @param principal Principal repaid\n     * @param interest Interest paid\n     */\n    event LenderLiquidationRepaid(\n        bytes32 indexed loanTermsHash,\n        address indexed lender,\n        uint8 indexed trancheIndex,\n        uint256 principal,\n        uint256 interest\n    );\n\n    /**\n     * @notice Emitted when collateral is liquidated\n     * @param loanTermsHash Loan terms hash\n     * @param proceeds Proceeds for lenders\n     * @param fee Liquidation fee\n     * @param surplus Liquidation surplus\n     */\n    event LiquidationProceedsDeposited(bytes32 indexed loanTermsHash, uint256 proceeds, uint256 fee, uint256 surplus);\n\n    /**\n     * @notice Emitted when transfer failed\n     * @param token Token address\n     * @param recipient Recipient address\n     * @param intendedRecipient Intended recipient address\n     * @param amount Amount\n     */\n    event TransferFailed(\n        address indexed token, address indexed recipient, address indexed intendedRecipient, uint256 amount\n    );\n\n    /**\n     * @notice Emitted when hook failed\n     * @param reason Reason\n     */\n    event HookFailed(string reason);\n\n    /**\n     * @notice Emitted when a fee is paid\n     * @param loanTermsHash Loan terms hash\n     * @param kind Fee kind\n     * @param recipient Recipient address\n     * @param feeModel Fee model address\n     * @param amount Amount of fee paid\n     */\n    event FeePaid(\n        bytes32 indexed loanTermsHash, FeeKind indexed kind, address indexed recipient, address feeModel, uint256 amount\n    );\n\n    /**\n     * @notice Emitted when ERC20 tokens are rescued\n     * @param token Token address\n     * @param to Recipient address\n     * @param amount Amount\n     */\n    event ERC20Rescued(address indexed token, address indexed to, uint256 amount);\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get collateral timelock address\n     * @return Collateral timelock address\n     */\n    function collateralTimelock() external view returns (address);\n\n    /**\n     * @notice Get deposit timelock address\n     * @return Deposit timelock address\n     */\n    function depositTimelock() external view returns (address);\n\n    /**\n     * @notice Get escrow timelock address\n     * @return Escrow timelock address\n     */\n    function escrowTimelock() external view returns (address);\n\n    /**\n     * @notice Get fee recipient address\n     * @return Fee recipient address\n     */\n    function feeRecipient() external view returns (address);\n\n    /**\n     * @notice Compute loan terms hash\n     * @param loanTerms Loan terms\n     * @return Hash of the loan terms\n     */\n    function loanTermsHash(\n        LoanTermsV2 calldata loanTerms\n    ) external view returns (bytes32);\n\n    /**\n     * @notice Get token IDs of lender positions\n     * @param loanTerms Loan terms\n     * @return Token IDs\n     */\n    function loanTokenIds(\n        LoanTermsV2 calldata loanTerms\n    ) external view returns (uint256[] memory);\n\n    /**\n     * @notice Get loan state by loan terms hash\n     * @param loanTermsHash_ Loan terms hash\n     * @return status Loan status\n     * @return repaymentCount Number of completed repayments\n     * @return originationTimestamp Loan origination timestamp\n     * @return scaledBalance Scaled loan balance\n     */\n    function loanState(\n        bytes32 loanTermsHash_\n    )\n        external\n        view\n        returns (LoanStatus status, uint16 repaymentCount, uint64 originationTimestamp, uint256 scaledBalance);\n\n    /**\n     * @notice Get loan state by token ID\n     * @param tokenId Lender position token ID\n     * @return status Loan status\n     * @return repaymentCount Number of completed repayments\n     * @return originationTimestamp Loan origination timestamp\n     * @return scaledBalance Scaled loan balance\n     */\n    function loanState(\n        uint256 tokenId\n    )\n        external\n        view\n        returns (LoanStatus status, uint16 repaymentCount, uint64 originationTimestamp, uint256 scaledBalance);\n\n    /**\n     * @notice Get the loan deadline schedule in UTC\n     * @param loanTerms Loan terms\n     * @return Array of UTC deadlines\n     */\n    function deadlines(\n        LoanTermsV2 calldata loanTerms\n    ) external view returns (uint64[] memory);\n\n    /**\n     * @notice Get lender position info by token ID\n     * @param tokenId Lender position token ID\n     * @return loanTermsHash_ Loan terms hash\n     * @return trancheIndex Tranche index\n     */\n    function lenderPositionInfo(\n        uint256 tokenId\n    ) external view returns (bytes32 loanTermsHash_, uint8 trancheIndex);\n\n    /**\n     * @notice Quote repayment for loan at a given timestamp\n     * @param loanTerms Loan terms\n     * @param timestamp Timestamp\n     * @return principalPayment Principal payment\n     * @return interestPayment Interest payment\n     * @return feePayment Fees payment\n     */\n    function quote(\n        LoanTermsV2 calldata loanTerms,\n        uint64 timestamp\n    ) external view returns (uint256 principalPayment, uint256 interestPayment, uint256 feePayment);\n\n    /**\n     * @notice Quote repayment for loan at the current timestamp\n     * @param loanTerms Loan terms\n     * @return principalPayment Principal payment\n     * @return interestPayment Interest payment\n     * @return feePayment Fees payment\n     */\n    function quote(\n        LoanTermsV2 calldata loanTerms\n    ) external view returns (uint256 principalPayment, uint256 interestPayment, uint256 feePayment);\n\n    /*------------------------------------------------------------------------*/\n    /* Originator API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Originate a loan\n     * @param loanTerms Loan terms\n     * @param lenderDepositInfos Lender deposit infos\n     * @param approvalSignatures Approval signatures over EIP-712 loan terms digest\n     * @return amount Amount transferred to the borrower\n     */\n    function originate(\n        LoanTermsV2 calldata loanTerms,\n        LenderDepositInfo[] calldata lenderDepositInfos,\n        bytes[] calldata approvalSignatures\n    ) external returns (uint256 amount);\n\n    /*------------------------------------------------------------------------*/\n    /* Borrower API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Repay a loan, or prepay principal when the current window is already paid\n     * @param loanTerms Loan terms\n     * @param amount Amount to pay\n     * @return repaymentAmount Amount repaid\n     */\n    function repay(\n        LoanTermsV2 calldata loanTerms,\n        uint256 amount\n    ) external returns (uint256 repaymentAmount);\n\n    /*------------------------------------------------------------------------*/\n    /* Liquidator API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Mark a loan as breached\n     * @param loanTermsHash_ Loan terms hash\n     */\n    function setLoanBreach(\n        bytes32 loanTermsHash_\n    ) external;\n\n    /**\n     * @notice Liquidate loan after grace period or breach\n     * @param loanTerms Loan terms\n     */\n    function liquidate(\n        LoanTermsV2 calldata loanTerms\n    ) external;\n\n    /**\n     * @notice Deposit liquidation proceeds for a loan and finalize it\n     * @param loanTerms Loan terms\n     * @param proceeds Proceeds\n     */\n    function depositLiquidationProceeds(\n        LoanTermsV2 calldata loanTerms,\n        uint256 proceeds\n    ) external;\n\n    /*------------------------------------------------------------------------*/\n    /* Refinance API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Refinance a loan by replacing its terms with new terms\n     * @param oldLoanTerms Old loan terms\n     * @param newLoanTerms New loan terms\n     * @param expectedBalance Expected pending balance of old loan\n     */\n    function refinance(\n        LoanTermsV2 calldata oldLoanTerms,\n        LoanTermsV2 calldata newLoanTerms,\n        uint256 expectedBalance\n    ) external;\n\n    /*------------------------------------------------------------------------*/\n    /* Pause API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Pause\n     */\n    function pause() external;\n\n    /**\n     * @notice Unpause\n     */\n    function unpause() external;\n\n    /*------------------------------------------------------------------------*/\n    /* Rescue ERC20 API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Rescue ERC20 tokens\n     * @param token Token address\n     * @param to Recipient address\n     * @param amount Amount\n     */\n    function rescueERC20(\n        address token,\n        address to,\n        uint256 amount\n    ) external;\n}\n"},"src/interfaces/IUSDai.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {IERC20} from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\n/**\n * @title USDai Interface\n * @author USD.AI Foundation\n */\ninterface IUSDai is IERC20 {\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid address\n     */\n    error InvalidAddress();\n\n    /**\n     * @notice Invalid amount\n     */\n    error InvalidAmount();\n\n    /**\n     * @notice Blacklisted address\n     * @param value Blacklisted address\n     */\n    error BlacklistedAddress(address value);\n\n    /**\n     * @notice Invalid parameters\n     */\n    error InvalidParameters();\n\n    /*------------------------------------------------------------------------*/\n    /* Structures */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Rate tier\n     * @param rate Rate\n     * @param threshold Threshold\n     */\n    struct RateTier {\n        uint256 rate;\n        uint256 threshold;\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposited event\n     * @param caller Caller\n     * @param recipient Recipient\n     * @param depositToken Deposit token\n     * @param depositAmount Deposit amount\n     * @param mintAmount Mint amount\n     */\n    event Deposited(\n        address indexed caller,\n        address indexed recipient,\n        address depositToken,\n        uint256 depositAmount,\n        uint256 mintAmount\n    );\n\n    /**\n     * @notice Withdrawn event\n     * @param caller Caller\n     * @param recipient Recipient\n     * @param withdrawToken Withdraw token\n     * @param usdaiAmount USDai amount\n     * @param withdrawAmount Withdraw amount\n     */\n    event Withdrawn(\n        address indexed caller,\n        address indexed recipient,\n        address withdrawToken,\n        uint256 usdaiAmount,\n        uint256 withdrawAmount\n    );\n\n    /**\n     * @notice Harvested event\n     * @param usdaiAmount USDai amount\n     */\n    event Harvested(uint256 usdaiAmount);\n\n    /**\n     * @notice Blacklist updated event\n     * @param account Account\n     * @param isBlacklisted Is blacklisted\n     */\n    event BlacklistUpdated(address indexed account, bool isBlacklisted);\n\n    /**\n     * @notice Base yield rate tiers set\n     * @param rateTiers Rate tiers\n     */\n    event BaseYieldRateTiersSet(RateTier[] rateTiers);\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get base token\n     * @return Base token\n     */\n    function baseToken() external view returns (address);\n\n    /**\n     * @notice Get bridged supply\n     * @return Bridged supply\n     */\n    function bridgedSupply() external view returns (uint256);\n\n    /**\n     * @notice Get base yield accrued\n     * @return Base yield accrued\n     */\n    function baseYieldAccrued() external view returns (uint256);\n\n    /**\n     * @notice Check if an address is blacklisted\n     * @param account Account\n     * @return Is blacklisted\n     */\n    function isBlacklisted(\n        address account\n    ) external view returns (bool);\n\n    /*------------------------------------------------------------------------*/\n    /* Public API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit\n     * @param baseTokenAmount Base token amount\n     * @param recipient Recipient\n     * @return USDai amount\n     */\n    function deposit(uint256 baseTokenAmount, address recipient) external returns (uint256);\n\n    /**\n     * @notice Withdraw\n     * @param usdaiAmount USDai amount\n     * @param recipient Recipient\n     * @return Withdraw amount\n     */\n    function withdraw(uint256 usdaiAmount, address recipient) external returns (uint256);\n\n    /**\n     * @notice Deposit (deprecated)\n     * @param depositToken Deposit token\n     * @param depositAmount Deposit amount\n     * @param usdaiAmountMinimum Minimum USDai amount\n     * @param recipient Recipient\n     * @return USDai amount\n     */\n    function deposit(\n        address depositToken,\n        uint256 depositAmount,\n        uint256 usdaiAmountMinimum,\n        address recipient\n    ) external returns (uint256);\n\n    /**\n     * @notice Deposit (deprecated)\n     * @param depositToken Deposit token\n     * @param depositAmount Deposit amount\n     * @param usdaiAmountMinimum Minimum USDai amount\n     * @param recipient Recipient\n     * @param data Data (for swap adapter)\n     * @return USDai amount\n     */\n    function deposit(\n        address depositToken,\n        uint256 depositAmount,\n        uint256 usdaiAmountMinimum,\n        address recipient,\n        bytes calldata data\n    ) external returns (uint256);\n\n    /**\n     * @notice Withdraw (deprecated)\n     * @param withdrawToken Withdraw token\n     * @param usdaiAmount USDai amount\n     * @param withdrawAmountMinimum Minimum withdraw amount\n     * @param recipient Recipient\n     * @return Withdraw amount\n     */\n    function withdraw(\n        address withdrawToken,\n        uint256 usdaiAmount,\n        uint256 withdrawAmountMinimum,\n        address recipient\n    ) external returns (uint256);\n\n    /**\n     * @notice Withdraw (deprecated)\n     * @param withdrawToken Withdraw token\n     * @param usdaiAmount USDai amount\n     * @param withdrawAmountMinimum Minimum withdraw amount\n     * @param recipient Recipient\n     * @param data Data (for swap adapter)\n     * @return Withdraw amount\n     */\n    function withdraw(\n        address withdrawToken,\n        uint256 usdaiAmount,\n        uint256 withdrawAmountMinimum,\n        address recipient,\n        bytes calldata data\n    ) external returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Base Yield Recipient API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Harvest base yield\n     * @return USDai amount\n     */\n    function harvest() external returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Blacklist Admin API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Set blacklist\n     * @param account Account\n     * @param blacklisted Blacklisted\n     */\n    function setBlacklist(address account, bool blacklisted) external;\n\n    /*------------------------------------------------------------------------*/\n    /* Pause Admin API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Pause the contract\n     */\n    function pause() external;\n\n    /**\n     * @notice Unpause the contract\n     */\n    function unpause() external;\n\n    /*------------------------------------------------------------------------*/\n    /* Permissioned API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Set rate tiers\n     * @param rateTiers Rate tiers\n     */\n    function setRateTiers(\n        RateTier[] memory rateTiers\n    ) external;\n}\n"},"lib/openzeppelin-contracts/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.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 Returns the addition of two unsigned integers, with an 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            if (c < a) return (false, 0);\n            return (true, c);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            if (b > a) return (false, 0);\n            return (true, a - b);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n            // benefit is lost if 'b' is also tested.\n            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n            if (a == 0) return (true, 0);\n            uint256 c = a * b;\n            if (c / a != b) return (false, 0);\n            return (true, c);\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            if (b == 0) return (false, 0);\n            return (true, a / b);\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            if (b == 0) return (false, 0);\n            return (true, a % b);\n        }\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. 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. `a ? b : c`) 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        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\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            // 512-bit multiply [prod1 prod0] = 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 = prod1 * 2²⁵⁶ + prod0.\n            uint256 prod0 = x * y; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 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 prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= prod1) {\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 [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, 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 {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, 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 prod1 into prod0.\n            prod0 |= prod1 * 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 prod1\n            // is no longer required.\n            result = prod0 * 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 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 byteArray) private pure returns (bool) {\n        for (uint256 i = 0; i < byteArray.length; ++i) {\n            if (byteArray[i] != 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 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        uint256 exp;\n        unchecked {\n            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);\n            value >>= exp;\n            result += exp;\n\n            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);\n            value >>= exp;\n            result += exp;\n\n            result += SafeCast.toUint(value > 1);\n        }\n        return result;\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 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        uint256 isGt;\n        unchecked {\n            isGt = SafeCast.toUint(value > (1 << 128) - 1);\n            value >>= isGt * 128;\n            result += isGt * 16;\n\n            isGt = SafeCast.toUint(value > (1 << 64) - 1);\n            value >>= isGt * 64;\n            result += isGt * 8;\n\n            isGt = SafeCast.toUint(value > (1 << 32) - 1);\n            value >>= isGt * 32;\n            result += isGt * 4;\n\n            isGt = SafeCast.toUint(value > (1 << 16) - 1);\n            value >>= isGt * 16;\n            result += isGt * 2;\n\n            result += SafeCast.toUint(value > (1 << 8) - 1);\n        }\n        return result;\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"},"lib/openzeppelin-contracts-upgradeable/contracts/access/AccessControlUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.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 \"../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    /**\n     * @dev See {IERC165-supportsInterface}.\n     */\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` to `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"},"src/positionManagers/PositionManager.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\n/**\n * @title Position Manager\n * @author USD.AI Foundation\n */\nabstract contract PositionManager {\n    /*------------------------------------------------------------------------*/\n    /* Constants */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Basis points scale\n     */\n    uint256 internal constant BASIS_POINTS_SCALE = 10_000;\n\n    /*------------------------------------------------------------------------*/\n    /* Structures */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Asset valuation type\n     */\n    enum ValuationType {\n        CONSERVATIVE,\n        OPTIMISTIC\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Insufficient balance\n     */\n    error InsufficientBalance();\n\n    /*------------------------------------------------------------------------*/\n    /* Internal helpers */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Assets value\n     * @return Assets value\n     */\n    function _assets(\n        ValuationType valuationType\n    ) internal view virtual returns (uint256);\n}\n"},"src/interfaces/IBasePositionManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Base Position Manager Interface\n * @author USD.AI Foundation\n */\ninterface IBasePositionManager {\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Base yield deposited\n     * @param depositedAmount Deposited USDai amount\n     * @param adminFee Admin fee\n     */\n    event BaseYieldDeposited(uint256 depositedAmount, uint256 adminFee);\n\n    /*------------------------------------------------------------------------*/\n    /* Getter */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Claimable base yield in USDai\n     * @return Claimable base yield in USDai\n     */\n    function claimableBaseYield() external view returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Permissioned API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Harvest base yield\n     * @return Deposited USDai amount\n     * @return Admin fee\n     */\n    function harvestBaseYield() external returns (uint256, uint256);\n}\n"},"src/interfaces/ILoanRouterPositionManager.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Loan Router Position Manager Interface\n * @author USD.AI Foundation\n */\ninterface ILoanRouterPositionManager {\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid timelock cancellation\n     */\n    error InvalidTimelockCancellation();\n\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Loan escrow timelock deposited\n     * @param loanTermsHash Loan terms hash\n     * @param usdaiAmount USDai amount\n     * @param interestRate Interest rate\n     */\n    event LoanEscrowTimelockDeposited(bytes32 indexed loanTermsHash, uint256 usdaiAmount, uint256 interestRate);\n\n    /**\n     * @notice Loan escrow timelock withdrawn\n     * @param loanTermsHash Loan terms hash\n     * @param interestAmount Interest amount (in USDai)\n     */\n    event LoanEscrowTimelockWithdrawn(bytes32 indexed loanTermsHash, uint256 interestAmount);\n\n    /**\n     * @notice Loan escrow timelock cancelled\n     * @param loanTermsHash Loan terms hash\n     * @param usdaiAmount Deposited USDai amount\n     * @param interestAmount Interest amount (in USDai)\n     */\n    event LoanEscrowTimelockCancelled(bytes32 indexed loanTermsHash, uint256 usdaiAmount, uint256 interestAmount);\n\n    /**\n     * @notice Loan timelock deposited\n     * @param loanTermsHash Loan terms hash\n     * @param usdaiAmount USDai amount\n     * @param expiration Expiration timestamp\n     */\n    event LoanDepositTimelockDeposited(bytes32 indexed loanTermsHash, uint256 usdaiAmount, uint64 expiration);\n\n    /**\n     * @notice Loan timelock cancelled\n     * @param loanTermsHash Loan terms hash\n     * @param usdaiAmount USDai amount\n     */\n    event LoanDepositTimelockCancelled(bytes32 indexed loanTermsHash, uint256 usdaiAmount);\n\n    /*------------------------------------------------------------------------*/\n    /* Getter */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit timelock balance\n     * @return Deposit timelock balance\n     */\n    function depositTimelockBalance() external view returns (uint256);\n\n    /**\n     * @notice Loan router balances\n     * @return Pending loan balance\n     * @return Accrued loan interest balance\n     */\n    function loanRouterBalances() external view returns (uint256, uint256);\n\n    /**\n     * @notice Accrual rate\n     * @return Accrual rate\n     */\n    function accrualRate() external view returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Permissioned API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit escrow loan timelock\n     * @param loanTermsHash Loan terms hash\n     * @param usdaiAmount USDai amount\n     * @param interestRate Interest rate\n     */\n    function depositLoanEscrowTimelock(bytes32 loanTermsHash, uint256 usdaiAmount, uint256 interestRate) external;\n\n    /**\n     * @notice Cancel escrow loan timelock\n     * @param loanTermsHash Loan terms hash\n     */\n    function cancelLoanEscrowTimelock(\n        bytes32 loanTermsHash\n    ) external;\n\n    /**\n     * @notice Deposit loan deposit timelock\n     * @param loanTermsHash Loan terms hash\n     * @param usdaiAmount USDai amount\n     * @param expiration Expiration timestamp\n     */\n    function depositLoanDepositTimelock(bytes32 loanTermsHash, uint256 usdaiAmount, uint64 expiration) external;\n\n    /**\n     * @notice Cancel loan deposit timelock\n     * @param loanTermsHash Loan terms hash\n     */\n    function cancelLoanDepositTimelock(\n        bytes32 loanTermsHash\n    ) external;\n}\n"},"lib/usdai-loan-router-contracts/src/interfaces/IEscrowTimelock.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Escrow Timelock Interface\n * @author USD.AI Foundation\n */\ninterface IEscrowTimelock {\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid amount\n     */\n    error InvalidAmount();\n\n    /**\n     * @notice Invalid address\n     */\n    error InvalidAddress();\n\n    /**\n     * @notice Invalid bytes32\n     */\n    error InvalidBytes32();\n\n    /**\n     * @notice Invalid deposit\n     */\n    error InvalidDeposit();\n\n    /**\n     * @notice Unsupported token\n     */\n    error UnsupportedToken();\n\n    /**\n     * @notice Invalid caller\n     */\n    error InvalidCaller();\n\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Emitted when a deposit is made\n     * @param target Target address\n     * @param context Context identifier\n     * @param amount Amount deposited\n     * @param interestRate Interest rate\n     */\n    event Deposited(address indexed target, bytes32 indexed context, uint256 amount, uint256 interestRate);\n\n    /**\n     * @notice Emitted when a deposit is canceled\n     * @param target Target address\n     * @param context Context identifier\n     * @param amount Amount returned\n     * @param interest Interest returned\n     */\n    event Canceled(address indexed target, bytes32 indexed context, uint256 amount, uint256 interest);\n\n    /**\n     * @notice Emitted when a deposit is withdrawn\n     * @param withdrawer Withdrawer address\n     * @param context Context identifier\n     * @param depositAmount Deposit amount\n     * @param withdrawAmount Withdraw amount\n     * @param interest Interest paid to depositor\n     */\n    event Withdrawn(\n        address indexed withdrawer,\n        bytes32 indexed context,\n        uint256 depositAmount,\n        uint256 withdrawAmount,\n        uint256 interest\n    );\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get deposit token address\n     * @return Deposit token address\n     */\n    function depositToken() external view returns (address);\n\n    /**\n     * @notice Get depositor address\n     * @return Depositor address\n     */\n    function depositor() external view returns (address);\n\n    /**\n     * @notice Get accrued interest\n     * @return Accrued interest\n     */\n    function accrued() external view returns (uint256);\n\n    /**\n     * @notice Get total deposits\n     * @return Total deposits\n     */\n    function totalDeposits() external view returns (uint256);\n\n    /**\n     * @notice Get deposit token ID\n     * @param target Target address\n     * @param context Context identifier\n     * @return Deposit token ID\n     */\n    function depositTokenId(\n        address target,\n        bytes32 context\n    ) external pure returns (uint256);\n\n    /**\n     * @notice Get deposit information\n     * @param tokenId Token ID\n     * @return target Target address\n     * @return context Context identifier\n     * @return amount Amount deposited\n     * @return interestRate Interest rate\n     * @return timestamp Deposit timestamp\n     * @return interest Interest accrued\n     */\n    function depositInfo(\n        uint256 tokenId\n    )\n        external\n        view\n        returns (\n            address target,\n            bytes32 context,\n            uint256 amount,\n            uint256 interestRate,\n            uint64 timestamp,\n            uint256 interest\n        );\n\n    /*------------------------------------------------------------------------*/\n    /* Depositor API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit tokens with offchain timelock\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount to deposit\n     * @param interestRate Interest rate\n     */\n    function deposit(\n        address target,\n        bytes32 context,\n        address token,\n        uint256 amount,\n        uint256 interestRate\n    ) external;\n\n    /**\n     * @notice Cancel deposit\n     * @param target Target address\n     * @param context Context identifier\n     * @return Amount and interest returned\n     */\n    function cancel(\n        address target,\n        bytes32 context\n    ) external returns (uint256, uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Withdrawer API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Withdraw deposit\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount to withdraw\n     * @return Amount withdrawn and interest paid\n     */\n    function withdraw(\n        bytes32 context,\n        address token,\n        uint256 amount\n    ) external returns (uint256, uint256);\n}\n"},"lib/usdai-loan-router-contracts/src/interfaces/IEscrowTimelockHooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Escrow Timelock Callback Hooks\n * @author USD.AI Foundation\n */\ninterface IEscrowTimelockHooks {\n    /**\n     * @notice Called when escrow funds are withdrawn\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount withdrawn\n     * @param interest Interest paid\n     */\n    function onEscrowWithdrawn(\n        address target,\n        bytes32 context,\n        address token,\n        uint256 amount,\n        uint256 interest\n    ) external;\n}\n"},"lib/usdai-loan-router-contracts/src/interfaces/IDepositTimelock.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Deposit Timelock Interface\n * @author USD.AI Foundation\n */\ninterface IDepositTimelock {\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid amount\n     */\n    error InvalidAmount();\n\n    /**\n     * @notice Invalid address\n     */\n    error InvalidAddress();\n\n    /**\n     * @notice Invalid bytes32\n     */\n    error InvalidBytes32();\n\n    /**\n     * @notice Invalid deposit\n     */\n    error InvalidDeposit();\n\n    /**\n     * @notice Invalid timestamp\n     */\n    error InvalidTimestamp();\n\n    /**\n     * @notice Unsupported token\n     */\n    error UnsupportedToken();\n\n    /*------------------------------------------------------------------------*/\n    /* Events */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Emitted when a deposit is made\n     * @param depositor Depositor address\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount deposited\n     * @param expiration Expiration timestamp\n     */\n    event Deposited(\n        address indexed depositor,\n        address indexed target,\n        bytes32 indexed context,\n        address token,\n        uint256 amount,\n        uint64 expiration\n    );\n\n    /**\n     * @notice Emitted when a deposit is canceled\n     * @param depositor Depositor address\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount returned\n     */\n    event Canceled(\n        address indexed depositor, address indexed target, bytes32 indexed context, address token, uint256 amount\n    );\n\n    /**\n     * @notice Emitted when a deposit is withdrawn\n     * @param depositor Depositor address\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param depositAmount Deposit amount\n     * @param withdrawAmount Withdraw amount\n     * @param refundAmount Refund amount\n     */\n    event Withdrawn(\n        address indexed depositor,\n        address indexed target,\n        bytes32 indexed context,\n        address token,\n        uint256 depositAmount,\n        uint256 withdrawAmount,\n        uint256 refundAmount\n    );\n\n    /*------------------------------------------------------------------------*/\n    /* Getters */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get deposit token ID\n     * @param depositor Depositor address\n     * @param target Target address\n     * @param context Context identifier\n     * @return Deposit token ID\n     */\n    function depositTokenId(\n        address depositor,\n        address target,\n        bytes32 context\n    ) external pure returns (uint256);\n\n    /**\n     * @notice Get deposit information\n     * @param tokenId Token ID\n     * @return depositor Depositor address\n     * @return target Target address\n     * @return context Context identifier\n     * @return token Token address\n     * @return amount Amount deposited\n     * @return expiration Expiration timestamp\n     */\n    function depositInfo(\n        uint256 tokenId\n    )\n        external\n        view\n        returns (address depositor, address target, bytes32 context, address token, uint256 amount, uint64 expiration);\n\n    /*------------------------------------------------------------------------*/\n    /* Depositor API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Deposit tokens with timelock\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount to deposit\n     * @param expiration Expiration timestamp\n     */\n    function deposit(\n        address target,\n        bytes32 context,\n        address token,\n        uint256 amount,\n        uint64 expiration\n    ) external;\n\n    /**\n     * @notice Cancel deposit after expiration\n     * @param target Target address\n     * @param context Context identifier\n     * @return Amount returned\n     */\n    function cancel(\n        address target,\n        bytes32 context\n    ) external returns (uint256);\n\n    /*------------------------------------------------------------------------*/\n    /* Withdrawer API */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Withdraw deposit before expiration\n     * @param depositor Depositor address\n     * @param context Context identifier\n     * @param token Token address\n     * @param amount Amount to withdraw\n     * @return Withdraw amount\n     */\n    function withdraw(\n        address depositor,\n        bytes32 context,\n        address token,\n        uint256 amount\n    ) external returns (uint256);\n}\n"},"lib/usdai-loan-router-contracts/src/interfaces/IDepositTimelockHooks.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\n/**\n * @title Deposit Timelock Callback Hooks\n * @author USD.AI Foundation\n */\ninterface IDepositTimelockHooks {\n    /**\n     * @notice Called when deposit is withdrawn\n     * @param target Target address\n     * @param context Context identifier\n     * @param token Token address\n     * @param depositAmount Deposit amount\n     * @param withdrawAmount Withdraw amount\n     * @param refundAmount Refund amount\n     */\n    function onDepositWithdrawn(\n        address target,\n        bytes32 context,\n        address token,\n        uint256 depositAmount,\n        uint256 withdrawAmount,\n        uint256 refundAmount\n    ) external;\n}\n"},"src/positionManagers/LoanRouterPositionManagerLogic.sol":{"content":"// SPDX-License-Identifier: BUSL-1.1\npragma solidity 0.8.29;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nimport {IUSDai} from \"../interfaces/IUSDai.sol\";\n\nimport {ILoanRouterV2} from \"@usdai-loan-router-contracts/interfaces/ILoanRouterV2.sol\";\n\nimport {LoanRouterPositionManager} from \"./LoanRouterPositionManager.sol\";\nimport {StakedUSDaiStorage} from \"../StakedUSDaiStorage.sol\";\nimport {PositionManager} from \"./PositionManager.sol\";\n\n/**\n * @title Loan Router Position Manager Logic\n * @author USD.AI Foundation\n */\nlibrary LoanRouterPositionManagerLogic {\n    /*------------------------------------------------------------------------*/\n    /* Constants */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Fixed point scale\n     */\n    uint256 private constant FIXED_POINT_SCALE = 1e18;\n\n    /**\n     * @notice Basis points scale\n     */\n    uint256 private constant BASIS_POINTS_SCALE = 10_000;\n\n    /*------------------------------------------------------------------------*/\n    /* Errors */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Invalid caller\n     */\n    error InvalidCaller();\n\n    /**\n     * @notice Invalid lender\n     */\n    error InvalidLender();\n\n    /**\n     * @notice Duplicate origination\n     */\n    error DuplicateOrigination();\n\n    /**\n     * @notice Duplicate deposit\n     */\n    error DuplicateDeposit();\n\n    /**\n     * @notice Loan not found\n     */\n    error LoanNotFound();\n\n    /**\n     * @notice Invalid currency token\n     */\n    error InvalidCurrencyToken();\n\n    /*------------------------------------------------------------------------*/\n    /* Internal helpers */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Validate hook context\n     * @param loanTerms Loan terms\n     * @param trancheIndex Tranche index\n     * @param loanRouter Loan router\n     */\n    function _validateHookContext(\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        uint8 trancheIndex,\n        address loanRouter\n    ) internal view {\n        /* Validate caller is loan router */\n        if (msg.sender != loanRouter) revert InvalidCaller();\n\n        /* Validate loan terms */\n        if (loanTerms.trancheSpecs[trancheIndex].lender != address(this)) revert InvalidLender();\n    }\n\n    /**\n     * @notice Update accrued interest and timestamp\n     * @param accrual Accrual\n     * @param oldAccrualRate Old accrual rate\n     * @param timestamp Timestamp\n     * @param lastRepaymentTimestamp Last repayment timestamp\n     */\n    function _accrue(\n        LoanRouterPositionManager.Accrual storage accrual,\n        uint256 oldAccrualRate,\n        uint64 timestamp,\n        uint64 lastRepaymentTimestamp\n    ) internal {\n        /* Accrue scaled interest */\n        accrual.accrued = accrual.accrued + accrual.rate * (block.timestamp - accrual.timestamp)\n            - (oldAccrualRate * (timestamp - lastRepaymentTimestamp));\n\n        /* Update timestamp */\n        accrual.timestamp = uint64(block.timestamp);\n    }\n\n    /**\n     * @notice Handle interest accrued hook\n     * @param depositsStorage Deposits storage\n     * @param usdai USDai\n     * @param adminFeeRate Admin fee rate\n     * @param adminFeeRecipient Admin fee recipient\n     * @param interest Interest amount\n     */\n    function _escrowInterestAccrued(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        address usdai,\n        uint256 adminFeeRate,\n        address adminFeeRecipient,\n        uint256 interest\n    ) internal {\n        /* Do nothing if interest is 0 */\n        if (interest == 0) return;\n\n        /* Compute admin fee amount */\n        uint256 adminFee = interest * adminFeeRate / BASIS_POINTS_SCALE;\n\n        /* Update deposit balance with interest amount minus admin fee */\n        depositsStorage.balance += interest - adminFee;\n\n        /* Transfer admin fee to recipient */\n        if (adminFee != 0) IUSDai(usdai).transfer(adminFeeRecipient, adminFee);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Getter */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Get loan router balances\n     * @param loansStorage Loans storage\n     * @param usdai USDai\n     * @return Pending loan balance\n     * @return Accrued loan interest balance\n     */\n    function loanRouterBalances(\n        LoanRouterPositionManager.Loans storage loansStorage,\n        address usdai\n    ) external view returns (uint256, uint256) {\n        /* Get USDai accrual */\n        LoanRouterPositionManager.Accrual storage accrual = loansStorage.interestAccruals[usdai];\n\n        /* Compute unscaled accrued interest */\n        uint256 accrued = (accrual.accrued + accrual.rate * (block.timestamp - accrual.timestamp)) / FIXED_POINT_SCALE;\n\n        /* Return loan router balance */\n        return (loansStorage.pendingBalances[usdai], accrued);\n    }\n\n    /*------------------------------------------------------------------------*/\n    /* Hook Logic */\n    /*------------------------------------------------------------------------*/\n\n    /**\n     * @notice Handle deposit timelock withdrawn hook\n     * @param depositsStorage Deposits storage\n     * @param depositTimelock Deposit timelock\n     * @param refundedAmount Refunded amount\n     */\n    function depositWithdrawn(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        address depositTimelock,\n        uint256 refundedAmount\n    ) external {\n        /* Validate caller is deposit timelock */\n        if (msg.sender != depositTimelock) revert InvalidCaller();\n\n        /* Do nothing if amount is 0 */\n        if (refundedAmount == 0) return;\n\n        /* Update deposit balance with refunded amount */\n        depositsStorage.balance += refundedAmount;\n    }\n\n    /**\n     * @notice Handle loan originated hook\n     * @param depositTimelockStorage Deposit timelock storage\n     * @param loansStorage Loans storage\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     * @param usdai USDai\n     * @param loanRouter Loan router\n     */\n    function loanOriginated(\n        LoanRouterPositionManager.DepositTimelock storage depositTimelockStorage,\n        LoanRouterPositionManager.Loans storage loansStorage,\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        address usdai,\n        address loanRouter\n    ) external {\n        /* Validate hook context */\n        _validateHookContext(loanTerms, trancheIndex, loanRouter);\n\n        /* Validate USDai */\n        if (loanTerms.currencyToken != usdai) revert InvalidCurrencyToken();\n\n        /* Subtract deposited USDai amount from deposit timelock balance */\n        depositTimelockStorage.balance -= depositTimelockStorage.amounts[loanTermsHash];\n\n        /* Delete deposit timelock amount for loan terms hash */\n        delete depositTimelockStorage.amounts[loanTermsHash];\n\n        /* Compute scaled accrual rate */\n        uint256 accrualRate = loanTerms.trancheSpecs[trancheIndex].rate * loanTerms.trancheSpecs[trancheIndex].amount;\n\n        /* Validate loan not already tracked */\n        if (loansStorage.loan[loanTermsHash].lastRepaymentTimestamp != 0) revert DuplicateOrigination();\n\n        /* Update loan in loans storage */\n        loansStorage.loan[loanTermsHash] = LoanRouterPositionManager.Loan(\n            accrualRate, loanTerms.trancheSpecs[trancheIndex].amount, uint64(block.timestamp), 0\n        );\n\n        /* Add loan balance to currency token balances storage */\n        loansStorage.pendingBalances[loanTerms.currencyToken] += loanTerms.trancheSpecs[trancheIndex].amount;\n\n        /* Get interest accrual */\n        LoanRouterPositionManager.Accrual storage accrual = loansStorage.interestAccruals[loanTerms.currencyToken];\n\n        /* Update accrued interest and timestamp */\n        _accrue(accrual, 0, 0, 0);\n\n        /* Update unscaled rate */\n        accrual.rate += accrualRate;\n    }\n\n    /**\n     * @notice Handle loan repayment hook\n     * @param depositsStorage Deposits storage\n     * @param loansStorage Loans storage\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     * @param loanBalance Loan balance\n     * @param principal Principal amount\n     * @param interest Interest amount\n     * @param loanRouter Loan router\n     * @param adminFeeRate Admin fee rate\n     * @param adminFeeRecipient Admin fee recipient\n     */\n    function loanRepayment(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        LoanRouterPositionManager.Loans storage loansStorage,\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        uint256 loanBalance,\n        uint256 principal,\n        uint256 interest,\n        address loanRouter,\n        uint256 adminFeeRate,\n        address adminFeeRecipient\n    ) external {\n        /* Validate hook context */\n        _validateHookContext(loanTerms, trancheIndex, loanRouter);\n\n        /* Get loan */\n        LoanRouterPositionManager.Loan storage loan = loansStorage.loan[loanTermsHash];\n\n        /* Compute admin fee amount */\n        uint256 adminFee = interest * adminFeeRate / BASIS_POINTS_SCALE;\n\n        /* Compute pending balance reduction, adjusted for rounding losses and rounding gains */\n        uint256 pendingBalanceReduction =\n            loanBalance == 0 ? loan.pendingBalance : Math.min(loan.pendingBalance, principal);\n\n        /* Update deposit balance */\n        depositsStorage.balance += principal + interest - adminFee;\n\n        /* Update total pending loan balances */\n        loansStorage.pendingBalances[loanTerms.currencyToken] -= pendingBalanceReduction;\n\n        /* Compute new loan balance */\n        uint256 newLoanBalance = loan.pendingBalance - pendingBalanceReduction;\n\n        /* Compute scaled new accrual rate */\n        uint256 newAccrualRate = loanTerms.trancheSpecs[trancheIndex].rate * newLoanBalance;\n\n        /* Get interest accrual */\n        LoanRouterPositionManager.Accrual storage accrual = loansStorage.interestAccruals[loanTerms.currencyToken];\n\n        /* Update accrued interest and timestamp */\n        _accrue(accrual, loan.accrualRate, uint64(block.timestamp), loan.lastRepaymentTimestamp);\n\n        /* Update unscaled rate */\n        accrual.rate = accrual.rate + newAccrualRate - loan.accrualRate;\n\n        /* Delete loan if fully repaid */\n        if (loanBalance == 0) {\n            delete loansStorage.loan[loanTermsHash];\n        } else {\n            /* Update loan */\n            loan.accrualRate = newAccrualRate;\n            loan.pendingBalance = newLoanBalance;\n            loan.lastRepaymentTimestamp = uint64(block.timestamp);\n        }\n\n        /* Transfer admin fee to recipient */\n        if (adminFee != 0) IUSDai(loanTerms.currencyToken).transfer(adminFeeRecipient, adminFee);\n    }\n\n    /**\n     * @notice Handle loan refinanced hook\n     * @param depositTimelockStorage Deposit timelock storage\n     * @param loansStorage Loans storage\n     * @param oldLoanTerms Old loan terms\n     * @param newLoanTerms New loan terms\n     * @param oldLoanTermsHash Old loan terms hash\n     * @param newLoanTermsHash New loan terms hash\n     * @param trancheIndex Tranche index\n     * @param cashOut Cash out amount\n     * @param cashIn Cash in amount\n     * @param loanRouter Loan router\n     */\n    function loanRefinanced(\n        LoanRouterPositionManager.DepositTimelock storage depositTimelockStorage,\n        LoanRouterPositionManager.Loans storage loansStorage,\n        ILoanRouterV2.LoanTermsV2 calldata oldLoanTerms,\n        ILoanRouterV2.LoanTermsV2 calldata newLoanTerms,\n        bytes32 oldLoanTermsHash,\n        bytes32 newLoanTermsHash,\n        uint8 trancheIndex,\n        uint256 cashOut,\n        uint256 cashIn,\n        address loanRouter\n    ) external {\n        /* Validate hook context */\n        _validateHookContext(oldLoanTerms, 0, loanRouter);\n        _validateHookContext(newLoanTerms, 0, loanRouter);\n\n        /* Get loans */\n        LoanRouterPositionManager.Loan memory oldLoan = loansStorage.loan[oldLoanTermsHash];\n        LoanRouterPositionManager.Loan storage newLoan = loansStorage.loan[newLoanTermsHash];\n\n        /* Revert if old loan is not tracked by this position manager */\n        if (oldLoan.lastRepaymentTimestamp == 0) revert LoanNotFound();\n\n        /* Revert if new loan is already tracked by this position manager */\n        if (newLoan.lastRepaymentTimestamp != 0) revert DuplicateOrigination();\n\n        /* Revert if old and new loan currency tokens are different */\n        if (oldLoanTerms.currencyToken != newLoanTerms.currencyToken) revert InvalidCurrencyToken();\n\n        /* If deposit timelock amount exists, subtract deposited USDai amount from deposit timelock balance */\n        if (depositTimelockStorage.amounts[newLoanTermsHash] != 0) {\n            depositTimelockStorage.balance -= depositTimelockStorage.amounts[newLoanTermsHash];\n\n            /* Delete deposit timelock amount for loan terms hash */\n            delete depositTimelockStorage.amounts[newLoanTermsHash];\n        }\n\n        /* Get currency accrual state */\n        LoanRouterPositionManager.Accrual storage currencyAccrual =\n            loansStorage.interestAccruals[oldLoanTerms.currencyToken];\n\n        /* Update accrued interest and remove old loan's past interest */\n        _accrue(currencyAccrual, oldLoan.accrualRate, uint64(block.timestamp), oldLoan.lastRepaymentTimestamp);\n\n        /* Remove old accrual rate from currency pool */\n        currencyAccrual.rate -= oldLoan.accrualRate;\n\n        /* Delete old loan entry */\n        delete loansStorage.loan[oldLoanTermsHash];\n\n        /* Update total pending loan balance by the notional delta */\n        loansStorage.pendingBalances[oldLoanTerms.currencyToken] =\n            loansStorage.pendingBalances[oldLoanTerms.currencyToken] + cashOut - cashIn;\n\n        /* Compute new pending balance */\n        uint256 newPendingBalance = oldLoan.pendingBalance + cashOut - cashIn;\n\n        /* Compute new accrual rate on the outstanding balance */\n        uint256 newAccrualRate = newLoanTerms.trancheSpecs[trancheIndex].rate * newPendingBalance;\n\n        /* Add new accrual rate to currency pool */\n        currencyAccrual.rate += newAccrualRate;\n\n        /* Create loan entry carrying the outstanding balance forward */\n        loansStorage.loan[newLoanTermsHash] = LoanRouterPositionManager.Loan({\n            accrualRate: newAccrualRate,\n            pendingBalance: newPendingBalance,\n            lastRepaymentTimestamp: uint64(block.timestamp),\n            liquidationTimestamp: 0\n        });\n    }\n\n    /**\n     * @notice Handle loan fee paid hook\n     * @param depositsStorage Deposits storage\n     * @param loanTerms Loan terms\n     * @param fee Fee paid\n     * @param usdai USDai\n     * @param loanRouter Loan router\n     */\n    function loanFeePaid(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32,\n        uint8,\n        uint256 fee,\n        address usdai,\n        address loanRouter\n    ) external {\n        /* Validate caller is loan router */\n        if (msg.sender != loanRouter) revert InvalidCaller();\n\n        /* Validate loan currency token is USDai */\n        if (loanTerms.currencyToken != usdai) revert InvalidCurrencyToken();\n\n        /* Update deposit balance */\n        depositsStorage.balance += fee;\n    }\n\n    /**\n     * @notice Handle loan liquidated hook\n     * @param loansStorage Loans storage\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     * @param loanRouter Loan router\n     */\n    function loanLiquidated(\n        LoanRouterPositionManager.Loans storage loansStorage,\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        address loanRouter\n    ) external {\n        /* Validate hook context */\n        _validateHookContext(loanTerms, trancheIndex, loanRouter);\n\n        /* Get loan */\n        LoanRouterPositionManager.Loan storage loan = loansStorage.loan[loanTermsHash];\n\n        /* Get interest accrual */\n        LoanRouterPositionManager.Accrual storage accrual = loansStorage.interestAccruals[loanTerms.currencyToken];\n\n        /* Update accrued interest and timestamp */\n        _accrue(accrual, 0, 0, 0);\n\n        /* Update unscaled rate */\n        accrual.rate -= loan.accrualRate;\n\n        /* Update liquidation timestamp */\n        loan.liquidationTimestamp = uint64(block.timestamp);\n    }\n\n    /**\n     * @notice Handle loan collateral liquidated hook\n     * @param depositsStorage Deposits storage\n     * @param loansStorage Loans storage\n     * @param loanTerms Loan terms\n     * @param loanTermsHash Loan terms hash\n     * @param trancheIndex Tranche index\n     * @param principal Principal amount\n     * @param interest Interest amount\n     * @param loanRouter Loan router\n     * @param adminFeeRate Admin fee rate\n     * @param adminFeeRecipient Admin fee recipient\n     */\n    function loanCollateralLiquidated(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        LoanRouterPositionManager.Loans storage loansStorage,\n        ILoanRouterV2.LoanTermsV2 calldata loanTerms,\n        bytes32 loanTermsHash,\n        uint8 trancheIndex,\n        uint256 principal,\n        uint256 interest,\n        address loanRouter,\n        uint256 adminFeeRate,\n        address adminFeeRecipient\n    ) external {\n        /* Validate hook context */\n        _validateHookContext(loanTerms, trancheIndex, loanRouter);\n\n        /* Get loan */\n        LoanRouterPositionManager.Loan memory loan = loansStorage.loan[loanTermsHash];\n\n        /* Compute admin fee amount */\n        uint256 adminFee = interest * adminFeeRate / BASIS_POINTS_SCALE;\n\n        /* Update deposit balance */\n        depositsStorage.balance += principal + interest - adminFee;\n\n        /* Subtract loan balance from pending balances storage */\n        loansStorage.pendingBalances[loanTerms.currencyToken] -= loan.pendingBalance;\n\n        /* Get interest accrual */\n        LoanRouterPositionManager.Accrual storage accrual = loansStorage.interestAccruals[loanTerms.currencyToken];\n\n        /* Update accrued interest and timestamp */\n        _accrue(accrual, loan.accrualRate, loan.liquidationTimestamp, loan.lastRepaymentTimestamp);\n\n        /* Delete loan */\n        delete loansStorage.loan[loanTermsHash];\n\n        /* Transfer admin fee to recipient */\n        if (adminFee != 0) IUSDai(loanTerms.currencyToken).transfer(adminFeeRecipient, adminFee);\n    }\n\n    /**\n     * @notice Handle escrow cancelled interest accrued hook\n     * @param depositsStorage Deposits storage\n     * @param usdai USDai\n     * @param adminFeeRate Admin fee rate\n     * @param adminFeeRecipient Admin fee recipient\n     * @param interest Interest amount\n     */\n    function escrowCancelled(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        address usdai,\n        uint256 adminFeeRate,\n        address adminFeeRecipient,\n        uint256 interest\n    ) external {\n        _escrowInterestAccrued(depositsStorage, usdai, adminFeeRate, adminFeeRecipient, interest);\n    }\n\n    /**\n     * @notice Handle withdrawn escrow interest accrued hook\n     * @param depositsStorage Deposits storage\n     * @param usdai USDai\n     * @param escrowTimelock Escrow timelock\n     * @param adminFeeRate Admin fee rate\n     * @param adminFeeRecipient Admin fee recipient\n     * @param interest Interest amount\n     */\n    function escrowWithdrawn(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        address usdai,\n        address escrowTimelock,\n        uint256 adminFeeRate,\n        address adminFeeRecipient,\n        uint256 interest\n    ) external {\n        /* Validate caller is escrow timelock */\n        if (msg.sender != escrowTimelock) revert InvalidCaller();\n\n        _escrowInterestAccrued(depositsStorage, usdai, adminFeeRate, adminFeeRecipient, interest);\n    }\n\n    /**\n     * @notice Deposit funds\n     * @param depositsStorage Deposits storage\n     * @param redemptionStateStorage Redemption state storage\n     * @param depositTimelockStorage Deposit timelock storage\n     * @param usdai USDai\n     * @param usdaiAmount USDai amount\n     * @param loanTermsHash Loan terms hash\n     * @param timelock Timelock\n     */\n    function depositFunds(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        StakedUSDaiStorage.RedemptionState storage redemptionStateStorage,\n        LoanRouterPositionManager.DepositTimelock storage depositTimelockStorage,\n        address usdai,\n        uint256 usdaiAmount,\n        bytes32 loanTermsHash,\n        address timelock\n    ) external {\n        /* Get USDai balance */\n        uint256 usdaiBalance = depositsStorage.balance - redemptionStateStorage.balance;\n\n        /* Validate USDai balance */\n        if (usdaiAmount > usdaiBalance) revert PositionManager.InsufficientBalance();\n\n        /* Validate not already deposited */\n        if (depositTimelockStorage.amounts[loanTermsHash] != 0) revert DuplicateDeposit();\n\n        /* Update deposit balance */\n        depositsStorage.balance -= usdaiAmount;\n\n        /* Update deposit timelock balance and amounts */\n        depositTimelockStorage.balance += usdaiAmount;\n        depositTimelockStorage.amounts[loanTermsHash] = usdaiAmount;\n\n        /* Approve USDai */\n        IERC20(usdai).approve(timelock, usdaiAmount);\n    }\n\n    /**\n     * @notice Withdraw funds\n     * @param depositsStorage Deposits storage\n     * @param depositTimelockStorage Deposit timelock storage\n     * @param loanTermsHash Loan terms hash\n     * @return USDai amount\n     */\n    function withdrawFunds(\n        StakedUSDaiStorage.Deposits storage depositsStorage,\n        LoanRouterPositionManager.DepositTimelock storage depositTimelockStorage,\n        bytes32 loanTermsHash\n    ) external returns (uint256) {\n        /* Get USDai amount */\n        uint256 usdaiAmount = depositTimelockStorage.amounts[loanTermsHash];\n\n        /* Update deposit timelock balance */\n        depositTimelockStorage.balance -= usdaiAmount;\n\n        /* Delete deposit timelock amount for loan terms hash */\n        delete depositTimelockStorage.amounts[loanTermsHash];\n\n        /* Update deposit balance */\n        depositsStorage.balance += usdaiAmount;\n\n        /* Return USDai amount */\n        return usdaiAmount;\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC20} from \"../token/ERC20/IERC20.sol\";\n"},"lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"../utils/introspection/IERC165.sol\";\n"},"lib/openzeppelin-contracts/contracts/utils/Errors.sol":{"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"},"lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MessageHashUtils.sol)\n\npragma solidity ^0.8.20;\n\nimport {Strings} from \"../Strings.sol\";\n\n/**\n * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.\n *\n * The library provides methods for generating a hash of a message that conforms to the\n * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]\n * specifications.\n */\nlibrary MessageHashUtils {\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing a bytes32 `messageHash` with\n     * `\"\\x19Ethereum Signed Message:\\n32\"` and hashing the result. It corresponds with the\n     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with\n     * keccak256, although any bytes32 value can be safely used because the final digest will\n     * be re-hashed.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\") // 32 is the bytes-length of messageHash\n            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix\n            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)\n        }\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x45` (`personal_sign` messages).\n     *\n     * The digest is calculated by prefixing an arbitrary `message` with\n     * `\"\\x19Ethereum Signed Message:\\n\" + len(message)` and hashing the result. It corresponds with the\n     * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {\n        return\n            keccak256(bytes.concat(\"\\x19Ethereum Signed Message:\\n\", bytes(Strings.toString(message.length)), message));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an ERC-191 signed data with version\n     * `0x00` (data with intended validator).\n     *\n     * The digest is calculated by prefixing an arbitrary `data` with `\"\\x19\\x00\"` and the intended\n     * `validator` address. Then hashing the result.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(hex\"19_00\", validator, data));\n    }\n\n    /**\n     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).\n     *\n     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with\n     * `\\x19\\x01` and hashing the result. It corresponds to the hash signed by the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.\n     *\n     * See {ECDSA-recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            mstore(ptr, hex\"19_01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            digest := keccak256(ptr, 0x42)\n        }\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/interfaces/IERC5267.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)\n\npragma solidity ^0.8.20;\n\ninterface IERC5267 {\n    /**\n     * @dev MAY be emitted to signal that the domain could have changed.\n     */\n    event EIP712DomainChanged();\n\n    /**\n     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712\n     * signature.\n     */\n    function eip712Domain()\n        external\n        view\n        returns (\n            bytes1 fields,\n            string memory name,\n            string memory version,\n            uint256 chainId,\n            address verifyingContract,\n            bytes32 salt,\n            uint256[] memory extensions\n        );\n}\n"},"lib/openzeppelin-contracts/contracts/utils/Panic.sol":{"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"},"lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.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 an uint of `bits` size.\n     */\n    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);\n\n    /**\n     * @dev An int value doesn't fit in an 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 An 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"},"lib/openzeppelin-contracts/contracts/access/IAccessControl.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)\n\npragma solidity ^0.8.20;\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 signaling 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"},"lib/openzeppelin-contracts/contracts/utils/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.2.0) (utils/Strings.sol)\n\npragma solidity ^0.8.20;\n\nimport {Math} from \"./math/Math.sol\";\nimport {SafeCast} from \"./math/SafeCast.sol\";\nimport {SignedMath} from \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    using SafeCast for *;\n\n    bytes16 private constant HEX_DIGITS = \"0123456789abcdef\";\n    uint8 private constant ADDRESS_LENGTH = 20;\n\n    /**\n     * @dev The `value` string doesn't fit in the specified `length`.\n     */\n    error StringsInsufficientHexLength(uint256 value, uint256 length);\n\n    /**\n     * @dev The string being parsed contains characters that are not in scope of the given base.\n     */\n    error StringsInvalidChar();\n\n    /**\n     * @dev The string being parsed is not a properly formatted address.\n     */\n    error StringsInvalidAddressFormat();\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n     */\n    function toString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            assembly (\"memory-safe\") {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                assembly (\"memory-safe\") {\n                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toStringSigned(int256 value) internal pure returns (string memory) {\n        return string.concat(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value)));\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n     */\n    function toHexString(uint256 value) internal pure returns (string memory) {\n        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\n    }\n\n    /**\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n     */\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n        uint256 localValue = value;\n        bytes memory buffer = new bytes(2 * length + 2);\n        buffer[0] = \"0\";\n        buffer[1] = \"x\";\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\n            buffer[i] = HEX_DIGITS[localValue & 0xf];\n            localValue >>= 4;\n        }\n        if (localValue != 0) {\n            revert StringsInsufficientHexLength(value, length);\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal\n     * representation.\n     */\n    function toHexString(address addr) internal pure returns (string memory) {\n        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);\n    }\n\n    /**\n     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal\n     * representation, according to EIP-55.\n     */\n    function toChecksumHexString(address addr) internal pure returns (string memory) {\n        bytes memory buffer = bytes(toHexString(addr));\n\n        // hash the hex part of buffer (skip length + 2 bytes, length 40)\n        uint256 hashValue;\n        assembly (\"memory-safe\") {\n            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))\n        }\n\n        for (uint256 i = 41; i > 1; --i) {\n            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)\n            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {\n                // case shift by xoring with 0x20\n                buffer[i] ^= 0x20;\n            }\n            hashValue >>= 4;\n        }\n        return string(buffer);\n    }\n\n    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input) internal pure returns (uint256) {\n        return parseUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[0-9]*`\n     * - The result must fit into an `uint256` type\n     */\n    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        uint256 result = 0;\n        for (uint256 i = begin; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 9) return (false, 0);\n            result *= 10;\n            result += chr;\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a decimal string and returns the value as a `int256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input) internal pure returns (int256) {\n        return parseInt(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `[-+]?[0-9]*`\n     * - The result must fit in an `int256` type.\n     */\n    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {\n        (bool success, int256 value) = tryParseInt(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if\n     * the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {\n        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    uint256 private constant ABS_MIN_INT256 = 2 ** 255;\n\n    /**\n     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid\n     * character or if the result does not fit in a `int256`.\n     *\n     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.\n     */\n    function tryParseInt(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, int256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseIntUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseIntUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, int256 value) {\n        bytes memory buffer = bytes(input);\n\n        // Check presence of a negative sign.\n        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        bool positiveSign = sign == bytes1(\"+\");\n        bool negativeSign = sign == bytes1(\"-\");\n        uint256 offset = (positiveSign || negativeSign).toUint();\n\n        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);\n\n        if (absSuccess && absValue < ABS_MIN_INT256) {\n            return (true, negativeSign ? -int256(absValue) : int256(absValue));\n        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {\n            return (true, type(int256).min);\n        } else return (false, 0);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as a `uint256`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input) internal pure returns (uint256) {\n        return parseHexUint(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`\n     * - The result must fit in an `uint256` type.\n     */\n    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {\n        (bool success, uint256 value) = tryParseHexUint(input, begin, end);\n        if (!success) revert StringsInvalidChar();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {\n        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an\n     * invalid character.\n     *\n     * NOTE: This function will revert if the result does not fit in a `uint256`.\n     */\n    function tryParseHexUint(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, uint256 value) {\n        if (end > bytes(input).length || begin > end) return (false, 0);\n        return _tryParseHexUintUncheckedBounds(input, begin, end);\n    }\n\n    /**\n     * @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that\n     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.\n     */\n    function _tryParseHexUintUncheckedBounds(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) private pure returns (bool success, uint256 value) {\n        bytes memory buffer = bytes(input);\n\n        // skip 0x prefix if present\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 offset = hasPrefix.toUint() * 2;\n\n        uint256 result = 0;\n        for (uint256 i = begin + offset; i < end; ++i) {\n            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));\n            if (chr > 15) return (false, 0);\n            result *= 16;\n            unchecked {\n                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).\n                // This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.\n                result += chr;\n            }\n        }\n        return (true, result);\n    }\n\n    /**\n     * @dev Parse a hexadecimal string (with or without \"0x\" prefix), and returns the value as an `address`.\n     *\n     * Requirements:\n     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input) internal pure returns (address) {\n        return parseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and\n     * `end` (excluded).\n     *\n     * Requirements:\n     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`\n     */\n    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {\n        (bool success, address value) = tryParseAddress(input, begin, end);\n        if (!success) revert StringsInvalidAddressFormat();\n        return value;\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly\n     * formatted address. See {parseAddress} requirements.\n     */\n    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {\n        return tryParseAddress(input, 0, bytes(input).length);\n    }\n\n    /**\n     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly\n     * formatted address. See {parseAddress} requirements.\n     */\n    function tryParseAddress(\n        string memory input,\n        uint256 begin,\n        uint256 end\n    ) internal pure returns (bool success, address value) {\n        if (end > bytes(input).length || begin > end) return (false, address(0));\n\n        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2(\"0x\"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty\n        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;\n\n        // check that input is the correct length\n        if (end - begin == expectedLength) {\n            // length guarantees that this does not overflow, and value is at most type(uint160).max\n            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);\n            return (s, address(uint160(v)));\n        } else {\n            return (false, address(0));\n        }\n    }\n\n    function _tryParseChr(bytes1 chr) private pure returns (uint8) {\n        uint8 value = uint8(chr);\n\n        // Try to parse `chr`:\n        // - Case 1: [0-9]\n        // - Case 2: [a-f]\n        // - Case 3: [A-F]\n        // - otherwise not supported\n        unchecked {\n            if (value > 47 && value < 58) value -= 48;\n            else if (value > 96 && value < 103) value -= 87;\n            else if (value > 64 && value < 71) value -= 55;\n            else return type(uint8).max;\n        }\n\n        return value;\n    }\n\n    /**\n     * @dev Reads a bytes32 from a bytes array without bounds checking.\n     *\n     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the\n     * assembly block as such would prevent some optimizations.\n     */\n    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {\n        // This is not memory safe in the general case, but all calls to this private function are within bounds.\n        assembly (\"memory-safe\") {\n            value := mload(add(buffer, add(0x20, offset)))\n        }\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.20;\n\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Branchless ternary evaluation for `a ? b : c`. 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. `a ? b : c`) to only compute\n     * one branch when needed, making this function more expensive.\n     */\n    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {\n        unchecked {\n            // branchless ternary works because:\n            // b ^ (a ^ b) == a\n            // b ^ 0 == b\n            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));\n        }\n    }\n\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a > b, a, b);\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return ternary(a < b, a, b);\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // Formula from the \"Bit Twiddling Hacks\" by Sean Eron Anderson.\n            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,\n            // taking advantage of the most significant (or \"sign\" bit) in two's complement representation.\n            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,\n            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).\n            int256 mask = n >> 255;\n\n            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.\n            return uint256((n + mask) ^ mask);\n        }\n    }\n}\n"}},"matchId":"53796535","creationMatch":"match","runtimeMatch":"match","verifiedAt":"2026-09-29T01:13:27Z","match":"match","chainId":"42161","address":"0x4637193852dF85b7Ac05DD052B187460D81551f6"}