{"sources":{"src/Transmuter.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.28;\n\nimport {IAlchemistV3} from \"./interfaces/IAlchemistV3.sol\";\nimport {ITransmuter} from \"./interfaces/ITransmuter.sol\";\nimport {ERC721} from \"@openzeppelin/contracts/token/ERC721/ERC721.sol\";\nimport {ERC721Enumerable} from \"@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol\";\nimport {NFTMetadataGenerator} from \"./libraries/NFTMetadataGenerator.sol\";\nimport {SafeCast} from \"./libraries/SafeCast.sol\";\nimport {StakingGraph} from \"./libraries/StakingGraph.sol\";\nimport {TokenUtils} from \"./libraries/TokenUtils.sol\";\nimport {FixedPointMath} from \"./libraries/FixedPointMath.sol\";\n\nimport {Unauthorized, IllegalArgument, IllegalState} from \"./base/Errors.sol\";\nimport \"./base/TransmuterErrors.sol\";\n\n/// @title AlchemixV3 Transmuter\n///\n/// @notice A contract which facilitates the exchange of alAssets to yield bearing assets.\ncontract Transmuter is ITransmuter, ERC721Enumerable {\n    using StakingGraph for StakingGraph.Graph;\n    using SafeCast for int256;\n    using SafeCast for uint256;\n\n    uint256 public constant BPS = 10_000;\n    uint256 public constant FIXED_POINT_SCALAR = 1e18;\n    int256 public constant BLOCK_SCALING_FACTOR = 1e8;\n    \n    /// @inheritdoc ITransmuter\n    string public constant version = \"3.0.0\";\n\n    /// @inheritdoc ITransmuter\n    uint256 public depositCap;\n\n    /// @inheritdoc ITransmuter\n    uint256 public exitFee;\n\n    /// @inheritdoc ITransmuter\n    uint256 public transmutationFee;\n\n    /// @inheritdoc ITransmuter\n    uint256 public timeToTransmute;\n\n    /// @inheritdoc ITransmuter\n    uint256 public totalLocked;\n\n    /// @inheritdoc ITransmuter\n    uint256 public totalActiveLocked; \n\n    /// @inheritdoc ITransmuter\n    address public admin;\n\n    /// @inheritdoc ITransmuter\n    address public pendingAdmin;\n\n    /// @inheritdoc ITransmuter\n    address public protocolFeeReceiver;\n\n    /// @inheritdoc ITransmuter\n    address public syntheticToken;\n\n    /// @inheritdoc ITransmuter\n    IAlchemistV3 public alchemist;\n\n    /// @dev Map of user positions data.\n    mapping(uint256 => StakingPosition) private _positions;\n\n    /// @dev Map of users whos position counts towards deposit cap.\n    mapping(uint256 => bool) private _countsTowardCap;\n\n    /// @dev Graph of transmuter positions.\n    StakingGraph.Graph private _stakingGraph;\n\n    /// @dev Nonce data used for minting of new nft positions.\n    uint256 private _nonce;\n\n    modifier onlyAdmin() {\n        _checkArgument(msg.sender == admin);\n        _;\n    }\n\n    constructor(ITransmuter.TransmuterInitializationParams memory params) ERC721(\"Alchemix V3 Transmuter\", \"TRNSMTR\") {\n        _checkArgument(params.feeReceiver != address(0));\n        _checkArgument(params.timeToTransmute != 0);\n        _checkArgument(params.timeToTransmute <= type(int256).max.toUint256());\n        _checkArgument(params.transmutationFee <= BPS);\n        _checkArgument(params.exitFee <= BPS);\n\n        syntheticToken = params.syntheticToken;\n        timeToTransmute = params.timeToTransmute;\n        transmutationFee = params.transmutationFee;\n        exitFee = params.exitFee;\n        protocolFeeReceiver = params.feeReceiver;\n        admin = msg.sender;\n    }\n\n    /// @inheritdoc ITransmuter\n    function setPendingAdmin(address value) external onlyAdmin {\n        pendingAdmin = value;\n\n        emit PendingAdminUpdated(value);\n    }\n\n    /// @inheritdoc ITransmuter\n    function acceptAdmin() external {\n        _checkState(pendingAdmin != address(0));\n\n        if (msg.sender != pendingAdmin) {\n            revert Unauthorized();\n        }\n\n        admin = pendingAdmin;\n        pendingAdmin = address(0);\n\n        emit AdminUpdated(admin);\n        emit PendingAdminUpdated(address(0));\n    }\n\n    /// @inheritdoc ITransmuter\n    function setAlchemist(address value) external onlyAdmin {\n        alchemist = IAlchemistV3(value);\n\n        emit AlchemistUpdated(value);\n    }\n\n    /// @inheritdoc ITransmuter\n    function setDepositCap(uint256 cap) external onlyAdmin {\n        _checkArgument(cap <= type(int256).max.toUint256());\n\n        depositCap = cap;\n        emit DepositCapUpdated(cap);\n    }\n\n    /// @inheritdoc ITransmuter\n    function setTransmutationFee(uint256 fee) external onlyAdmin {\n        _checkArgument(fee <= BPS);\n\n        transmutationFee = fee;\n        emit TransmutationFeeUpdated(fee);\n    }\n\n    /// @inheritdoc ITransmuter\n    function setExitFee(uint256 fee) external onlyAdmin {\n        _checkArgument(fee <= BPS);\n\n        exitFee = fee;\n        emit ExitFeeUpdated(fee);\n    }\n\n    /// @inheritdoc ITransmuter\n    function setTransmutationTime(uint256 time) external onlyAdmin {\n        _checkArgument(time != 0);\n        _checkArgument(time <= type(int256).max.toUint256());\n        timeToTransmute = time;\n\n        emit TransmutationTimeUpdated(time);\n    }\n\n    /// @inheritdoc ITransmuter\n    function setProtocolFeeReceiver(address value) external onlyAdmin {\n        _checkArgument(value != address(0));\n        protocolFeeReceiver = value;\n        emit ProtocolFeeReceiverUpdated(value);\n    }\n\n    function tokenURI(uint256 id) public view override returns (string memory) {\n        return NFTMetadataGenerator.generateTokenURI(id, \"Transmuter V3 Position\");\n    }\n\n    /// @inheritdoc ITransmuter\n    function getPosition(uint256 id) external view returns (StakingPosition memory) {\n        return _positions[id];\n    }\n\n    /// @inheritdoc ITransmuter\n    function createRedemption(uint256 syntheticDepositAmount, address recipient) external {\n        if (syntheticDepositAmount == 0) {\n            revert DepositZeroAmount();\n        }\n\n        _checkArgument(recipient != address(0));\n\n        if (totalActiveLocked + syntheticDepositAmount > depositCap) {\n            revert DepositCapReached();\n        }\n\n        if (totalLocked + syntheticDepositAmount > alchemist.totalSyntheticsIssued()) {\n            revert DepositCapReached();\n        }\n\n        TokenUtils.safeTransferFrom(syntheticToken, msg.sender, address(this), syntheticDepositAmount);\n\n        _positions[++_nonce] = StakingPosition(syntheticDepositAmount, block.number, block.number + timeToTransmute);\n\n        // Update Fenwick Tree\n        _updateStakingGraph(syntheticDepositAmount.toInt256() * BLOCK_SCALING_FACTOR / timeToTransmute.toInt256(), timeToTransmute);\n\n        totalLocked += syntheticDepositAmount;\n\n        totalActiveLocked += syntheticDepositAmount;\n        _countsTowardCap[_nonce] = true;\n\n        _mint(recipient, _nonce);\n\n        emit PositionCreated(msg.sender, syntheticDepositAmount, _nonce);\n    }\n\n    /// @inheritdoc ITransmuter\n    function claimRedemption(uint256 id) external returns (uint256 claimYield, uint256 feeYield, uint256 syntheticReturned, uint256 syntheticFee) {\n        StakingPosition storage position = _positions[id];\n\n        if (position.maturationBlock == 0) {\n            revert PositionNotFound();\n        }\n\n        if (position.startBlock == block.number) {\n            revert PrematureClaim();\n        }\n\n        uint256 transmutationTime = position.maturationBlock - position.startBlock;\n        uint256 blocksLeft = position.maturationBlock > block.number ? position.maturationBlock - block.number : 0;\n        uint256 amountNottransmuted = blocksLeft > 0 ? FixedPointMath.mulDivUp(position.amount, blocksLeft, transmutationTime) : 0;\n        uint256 amountTransmuted = position.amount - amountNottransmuted;\n\n        if (_requireOwned(id) != msg.sender) {\n            revert CallerNotOwner();\n        }\n\n        // Burn position NFT\n        _burn(id);\n        \n        // Ratio of total synthetics issued by the alchemist / underlingying value of collateral stored in the alchemist\n        // If the system experiences bad debt we use this ratio to scale back the value of yield tokens that are transmuted\n        address myt = alchemist.myt();\n        uint256 yieldTokenBalance = TokenUtils.safeBalanceOf(myt, address(this));\n\n        // Avoid divide by 0\n        uint256 backingUnderlying = alchemist.getTotalLockedUnderlyingValue() + alchemist.convertYieldTokensToUnderlying(yieldTokenBalance);\n        uint256 denominator = backingUnderlying > 0 ? backingUnderlying : 1;\n\n        // Round up so badDebtRatio is never understated.\n        // Understating badDebtRatio makes scaledTransmuted slightly too large, which can cause alchemist.redeem(amountToRedeem) to revert due to share rounding.\n        uint256 badDebtRatio = FixedPointMath.mulDivUp(alchemist.totalSyntheticsIssued(), 10 ** TokenUtils.expectDecimals(alchemist.underlyingToken()), denominator);\n\n        uint256 scaledTransmuted = amountTransmuted;\n\n        if (badDebtRatio > 1e18) {\n            scaledTransmuted = amountTransmuted * FIXED_POINT_SCALAR / badDebtRatio;\n        }\n\n        // If the contract has a balance of yield tokens from alchemist repayments then we only need to redeem partial or none from Alchemist earmarked\n        uint256 debtValue = alchemist.convertYieldTokensToDebt(yieldTokenBalance);\n        uint256 amountToRedeem = scaledTransmuted > debtValue ? scaledTransmuted - debtValue : 0;\n\n        uint256 redeemedShares = 0;\n        if (amountToRedeem > 0) {\n            redeemedShares = alchemist.redeem(amountToRedeem);\n        }\n\n        uint256 sharesAvailable = yieldTokenBalance + redeemedShares;\n        uint256 totalYield = alchemist.convertDebtTokensToYield(scaledTransmuted);\n        uint256 distributable = totalYield <= sharesAvailable ? totalYield : sharesAvailable;\n\n        // Split distributable amount. Round fee down. claimant gets the remainder.\n        feeYield = distributable * transmutationFee / BPS;\n        claimYield = distributable - feeYield;\n\n        uint256 debtPaid = alchemist.convertYieldTokensToDebt(distributable);\n        if (debtPaid > scaledTransmuted) {\n            debtPaid = scaledTransmuted;\n        }\n\n        // Shortfall debt to offset if some amount of MYT cannot be paid to the user\n        // We will return some synthetics instead of burning them all if this is the case\n        uint256 shortfallDebt = scaledTransmuted > debtPaid ? scaledTransmuted - debtPaid : 0;\n\n        syntheticFee = amountNottransmuted * exitFee / BPS;\n        syntheticReturned = (amountNottransmuted - syntheticFee) + shortfallDebt;\n\n        uint256 burnAmountDebt = position.amount - (syntheticReturned + syntheticFee);\n\n        // Remove untransmuted amount from the staking graph\n        if (blocksLeft > 0) _updateStakingGraph(-position.amount.toInt256() * BLOCK_SCALING_FACTOR / transmutationTime.toInt256(), blocksLeft);\n\n        TokenUtils.safeTransfer(myt, msg.sender, claimYield);\n        TokenUtils.safeTransfer(myt, protocolFeeReceiver, feeYield);\n\n        TokenUtils.safeTransfer(syntheticToken, msg.sender, syntheticReturned);\n        TokenUtils.safeTransfer(syntheticToken, protocolFeeReceiver, syntheticFee);\n\n        if (burnAmountDebt > 0) {\n            TokenUtils.safeBurn(syntheticToken, burnAmountDebt);\n            alchemist.reduceSyntheticsIssued(burnAmountDebt);\n        }\n\n        alchemist.setTransmuterTokenBalance(TokenUtils.safeBalanceOf(myt, address(this)));\n\n        // If this position still counted toward cap, remove it now.\n        if (_countsTowardCap[id]) {\n            _countsTowardCap[id] = false;\n            totalActiveLocked -= position.amount;\n        }\n\n        totalLocked -= position.amount;\n\n        emit PositionClaimed(msg.sender, claimYield, syntheticReturned);\n\n        delete _positions[id];\n    }\n\n    /// @inheritdoc ITransmuter\n    function queryGraph(uint256 startBlock, uint256 endBlock) external view returns (uint256) {\n        if (endBlock < startBlock) return 0;\n\n        int256 queried = _stakingGraph.queryStake(startBlock, endBlock);\n        if (queried == 0) return 0;\n\n        return FixedPointMath.mulDivUp(queried.toUint256(), 1, uint256(BLOCK_SCALING_FACTOR));\n    }\n\n    /// @inheritdoc ITransmuter\n    function pokeMatured(uint256 id) external {\n        StakingPosition storage position = _positions[id];\n\n        if (position.maturationBlock == 0) revert PositionNotFound();\n\n        // must be fully matured\n        if (block.number < position.maturationBlock) {\n            revert PositionNotMatured(id, position.maturationBlock, block.number);\n        }\n\n        if (!_countsTowardCap[id]) revert PositionAlreadyPoked(id);\n\n        _countsTowardCap[id] = false;\n        totalActiveLocked -= position.amount;\n\n        emit PositionPoked(id, position.amount);\n    }\n\n    /// @dev Updates staking graphs\n    function _updateStakingGraph(int256 amount, uint256 blocks) private {\n        _stakingGraph.addStake(amount, block.number, blocks);\n    }\n\n    /// @dev Checks an expression and reverts with an {IllegalArgument} error if the expression is {false}.\n    ///\n    /// @param expression The expression to check.\n    function _checkArgument(bool expression) internal pure {\n        if (!expression) {\n            revert IllegalArgument();\n        }\n    }\n\n    /// @dev Checks an expression and reverts with an {IllegalState} error if the expression is {false}.\n    ///\n    /// @param expression The expression to check.\n    function _checkState(bool expression) internal pure {\n        if (!expression) {\n            revert IllegalState();\n        }\n    }\n}\n"},"src/interfaces/IAlchemistV3.sol":{"content":"// SPDX-License-Identifier: MIT\npragma solidity ^0.8.28;\n\n/// @notice Contract initialization parameters.\nstruct AlchemistInitializationParams {\n    // The initial admin account.\n    address admin;\n    // The ERC20 token used to represent debt. i.e. the alAsset.\n    address debtToken;\n    // The ERC20 token used to represent the underlying token of the yield token.\n    address underlyingToken;\n    // The global maximum amount of deposited collateral.\n    uint256 depositCap;\n    // The minimum collateralization between 0 and 1 exclusive\n    uint256 minimumCollateralization;\n    // The global minimum collateralization, >= minimumCollateralization.\n    uint256 globalMinimumCollateralization;\n    // The minimum collateralization for liquidation eligibility. between 1 and minimumCollateralization inclusive.\n    uint256 collateralizationLowerBound;\n    // The target collateralization ratio to restore accounts to after liquidation. Must be >= minimumCollateralization.\n    uint256 liquidationTargetCollateralization;\n    // The initial transmuter or transmuter buffer.\n    address transmuter;\n    // The fee on user debt paid to the protocol.\n    uint256 protocolFee;\n    // The address that receives protocol fees.\n    address protocolFeeReceiver;\n    // Fee paid to liquidators.\n    uint256 liquidatorFee;\n    // Fee paid to liquidators forcing an account earmarked debt repayment.\n    uint256 repaymentFee;\n    // The address of the morpho v2 vault.\n    address myt;\n}\n\n/// @notice A user account.\n/// @notice This account struct is included in the main contract, AlchemistV3.sol, to aid readability.\nstruct Account {\n    /// @notice User's collateral.\n    uint256 collateralBalance;\n    /// @notice User's debt.\n    uint256 debt;\n    /// @notice User debt earmarked for redemption.\n    uint256 earmarked;\n    /// @notice The amount of unlocked collateral.\n    uint256 freeCollateral;\n    /// @notice Last weight of earmark from most recent account sync.\n    uint256 lastAccruedEarmarkWeight;\n    /// @notice Last weight of redemption from most recent account sync.\n    uint256 lastAccruedRedemptionWeight;\n    /// @notice Last weight of collateral from most recent account sync.\n    uint256 lastCollateralWeight;\n    /// @notice Block of the most recent mint\n    uint256 lastMintBlock;\n    /// @notice Block of the most recent repay\n    uint256 lastRepayBlock;\n    /// @notice Last stored survival accumulator\n    uint256 lastSurvivalAccumulator;\n    /// @notice Total debt redeemed at last sync\n    uint256 lastTotalRedeemedDebt;\n    /// @notice Total debt paid out from redemptions at last sync\n    uint256 lastTotalRedeemedSharesOut;\n    /// @notice allowances for minting alAssets, per version.\n    mapping(uint256 => mapping(address => uint256)) mintAllowances;\n    /// @notice id used in the mintAllowances map which is incremented on reset.\n    uint256 allowancesVersion;\n}\n\n/// @notice Information associated with a redemption.\n/// @notice This redemption struct is included in the main contract, AlchemistV3.sol, to aid in calculating user debt from historic redemptions.\nstruct RedemptionInfo {\n    uint256 earmarked;\n    uint256 debt;\n    uint256 earmarkWeight;\n}\n\ninterface IAlchemistV3Actions {\n    /// @notice Approve `spender` to mint `amount` debt tokens.\n    ///\n    /// @param tokenId The tokenId of account granting approval.\n    /// @param spender The address that will be approved to mint.\n    /// @param amount  The amount of tokens that `spender` will be allowed to mint.\n\n    function approveMint(uint256 tokenId, address spender, uint256 amount) external;\n\n    /// @notice Synchronizes the state of the account owned by `owner`.\n    ///\n    /// @param tokenId   The tokenId of account\n    function poke(uint256 tokenId) external;\n\n    /// @notice Deposit a yield token into a user's account.\n    /// @notice Create a new position by using zero (0) for the `recipientId`.\n    /// @notice Users may create as many positions as they want.\n    ///\n    /// @notice An approval must be set for `yieldToken` which is greater than `amount`.\n    ///\n    /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.\n    /// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.\n    ///\n    /// @notice Emits a {Deposit} event.\n    ///\n    /// @notice **_NOTE:_** When depositing, the `AlchemistV3` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited.  This can be done via the standard `ERC20.approve()` method.\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;\n    /// @notice uint256 amount = 50000;\n    /// @notice IERC20(ydai).approve(alchemistAddress, amount);\n    /// @notice (uint256 tokenId, uint256 debtValue) = AlchemistV3(alchemistAddress).deposit(amount, msg.sender, 0);\n    /// @notice ```\n    ///\n    /// @param amount     The amount of yield tokens to deposit.\n    /// @param recipient  The owner of the account that will receive the resulting shares.\n    /// @param recipientId The id of account.\n    /// @return tokenId The id of the account.\n    /// @return debtValue The value of deposited tokens normalized to debt token value.\n    function deposit(uint256 amount, address recipient, uint256 recipientId) external returns (uint256 tokenId, uint256 debtValue);\n\n    /// @notice Withdraw `amount` yield tokens to `recipient`.\n    ///\n    /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.\n    ///\n    /// @notice Emits a {Withdraw} event.\n    ///\n    /// @notice **_NOTE:_** When withdrawing, th amount withdrawn must not put user over allowed LTV ratio.\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;\n    /// @notice (uint256 LTV, ) = AlchemistV3(alchemistAddress).getLoanTerms(msg.sender);\n    /// @notice (uint256 yieldTokens, ) = AlchemistV3(alchemistAddress).getCDP(tokenId);\n    /// @notice uint256 maxWithdrawableTokens = (AlchemistV3(alchemistAddress).LTV() - LTV) * yieldTokens / LTV;\n    /// @notice AlchemistV3(alchemistAddress).withdraw(maxWithdrawableTokens, msg.sender);\n    /// @notice ```\n    ///\n    /// @param amount     The number of tokens to withdraw.\n    /// @param recipient  The address of the recipient.\n    /// @param tokenId The tokenId of account.\n    ///\n    /// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.\n    function withdraw(uint256 amount, address recipient, uint256 tokenId) external returns (uint256 amountWithdrawn);\n\n    /// @notice Mint `amount` debt tokens.\n    ///\n    /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.\n    /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.\n    ///\n    /// @notice Emits a {Mint} event.\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice uint256 amtDebt = 5000;\n    /// @notice AlchemistV3(alchemistAddress).mint(amtDebt, msg.sender);\n    /// @notice ```\n    ///\n    /// @param tokenId The tokenId of account.\n    /// @param amount    The amount of tokens to mint.\n    /// @param recipient The address of the recipient.\n    function mint(uint256 tokenId, uint256 amount, address recipient) external;\n\n    /// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`.\n    ///\n    /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.\n    /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.\n    ///\n    /// @notice Emits a {Mint} event.\n    ///\n    /// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to.  This can be done via the `approveMint()` or `permitMint()` methods.\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice uint256 amtDebt = 5000;\n    /// @notice AlchemistV3(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender);\n    /// @notice ```\n    ///\n    /// @param tokenId   The tokenId of account.\n    /// @param amount    The amount of tokens to mint.\n    /// @param recipient The address of the recipient.\n    function mintFrom(uint256 tokenId, uint256 amount, address recipient) external;\n\n    /// @notice Burn `amount` debt tokens to credit the account owned by `recipientId`.\n    ///\n    /// @notice `amount` will be limited up to the amount of unearmarked debt that `recipient` currently holds.\n    ///\n    /// @notice `recipientId` must be non-zero or this call will revert with an {IllegalArgument} error.\n    /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.\n    /// @notice account for `recipientId` must have non-zero debt or this call will revert with an {IllegalState} error.\n    ///\n    /// @notice Emits a {Burn} event.\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice uint256 amtBurn = 5000;\n    /// @notice AlchemistV3(alchemistAddress).burn(amtBurn, 420);\n    /// @notice ```\n    ///\n    /// @param amount    The amount of tokens to burn.\n    /// @param recipientId   The tokenId of account to being credited.\n    ///\n    /// @return amountBurned The amount of tokens that were burned.\n    function burn(uint256 amount, uint256 recipientId) external returns (uint256 amountBurned);\n\n    /// @notice Repay `amount` debt using yield tokens to credit the account owned by `recipientId`.\n    ///\n    /// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.\n    ///\n    /// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.\n    /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.\n    ///\n    /// @notice Emits a {Repay} event.\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice uint256 amtRepay = 5000;\n    /// @notice AlchemistV3(alchemistAddress).repay(amtRepay, msg.sender);\n    /// @notice ```\n    ///\n    /// @param amount          The amount of the yield tokens to repay with.\n    /// @param recipientTokenId   The tokenId of account to be repaid\n    ///\n    /// @return amountRepaid The amount of tokens that were repaid.\n    function repay(uint256 amount, uint256 recipientTokenId) external returns (uint256 amountRepaid);\n\n    /**\n     * @notice Liquidates `owner` if the debt for account `owner` is greater than the underlying value of their collateral * LTV.\n     *\n     * @notice `owner` must be non-zero or this call will revert with an {IllegalArgument} error.\n     *\n     * @notice Emits a {Liquidate} event.\n     *\n     * @notice **Example:**\n     * @notice ```\n     * @notice AlchemistV2(alchemistAddress).liquidate(id4);\n     * @notice ```\n     *\n     * @param accountId   The tokenId of account\n     *\n     * @return yieldAmount         Yield tokens sent to the transmuter.\n     * @return feeInYield          Fee paid to liquidator in yield tokens.\n     * @return feeInUnderlying     Fee paid to liquidator in underlying token.\n     */\n    function liquidate(uint256 accountId) external returns (uint256 yieldAmount, uint256 feeInYield, uint256 feeInUnderlying);\n\n\n    /// @notice Self liquidates the account owned by `accountId`.\n    ///\n    /// @notice `accountId` must be non-zero or this call will revert with an {IllegalArgument} error.\n    /// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.\n    /// @notice `accountId` must be owned by `msg.sender` or this call will revert with an {Unauthorized} error.\n    /// @notice `accountId` must be healthy (overcollateralized) or this call will revert with an {AccountNotHealthy} error.\n    /// @notice in the event that account is not healthy, the account can only be liquidated using the regular liquidation path. (i.e. liquidate(accountId))\n    ///\n    /// @notice Emits a {SelfLiquidated} event.\n    ///\n    /// @param accountId The tokenId of account to be self liquidated.\n    /// @param recipient The address of the recipient.\n    function selfLiquidate(uint256 accountId, address recipient) external returns (uint256 amountLiquidated);\n\n    /// @notice Liquidates `owners` if the debt for account `owner` is greater than the underlying value of their collateral * LTV.\n    ///\n    /// @notice `owner` must be non-zero or this call will revert with an {IllegalArgument} error.\n    ///\n    ///\n    /// @notice **Example:**\n    /// @notice ```\n    /// @notice AlchemistV3(alchemistAddress).batchLiquidate([id1, id35]);\n    /// @notice ```\n    ///\n    /// @param accountIds   The tokenId of each account\n    ///\n    /// @return totalAmountLiquidated   Amount in yield tokens sent to the transmuter.\n    /// @return totalFeesInYield        Amount sent to liquidator in yield tokens.\n    /// @return totalFeesInUnderlying   Amount sent to liquidator in underlying token.\n    function batchLiquidate(uint256[] memory accountIds)\n        external\n        returns (uint256 totalAmountLiquidated, uint256 totalFeesInYield, uint256 totalFeesInUnderlying);\n\n    /// @notice Redeems `amount` debt from the alchemist in exchange for yield tokens sent to the transmuter.\n    ///\n    /// @notice This function is only callable by the transmuter.\n    ///\n    /// @notice Emits a {Redeem} event.\n    ///\n    /// @param amount The amount of tokens to redeem.\n    function redeem(uint256 amount) external returns (uint256 sharesSent);\n\n    /// @notice Reduces syntheticTokensIssued by `amount`.\n    ///\n    /// @notice This function is only callable by the transmuter.\n    ///\n    /// @param amount The amount of tokens burned during redemption.\n    function reduceSyntheticsIssued(uint256 amount) external;\n\n    /// @notice Sets lastTransmuterTokenBalance to `amount`.\n    ///\n    /// @notice This function is only callable by the transmuter.\n    ///\n    /// @param amount The balance of the transmuter.\n    function setTransmuterTokenBalance(uint256 amount) external;\n\n    /// @notice Resets all mint allowances by account managed by `tokenId`.\n    ///\n    /// @notice This function is only callable by the owner of the token id or the AlchemistV3Position contract.\n    ///\n    /// @notice Emits a {MintAllowancesReset} event.\n    ///\n    /// @param tokenId The token id of the account.\n    function resetMintAllowances(uint256 tokenId) external;\n}\n\ninterface IAlchemistV3AdminActions {\n    /// @notice Sets the pending administrator.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {PendingAdminUpdated} event.\n    ///\n    /// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process.\n    ///\n    /// @param value The address to set the pending admin to.\n    function setPendingAdmin(address value) external;\n\n    /// @notice Sets the active state of a guardian.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {GuardianSet} event.\n    ///\n    /// @param guardian The address of the target guardian.\n    /// @param isActive The active state to set for the guardian.\n    function setGuardian(address guardian, bool isActive) external;\n\n    /// @notice Allows for `msg.sender` to accepts the role of administrator.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    /// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error.\n    ///\n    /// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set.\n    ///\n    /// @notice Emits a {AdminUpdated} event.\n    /// @notice Emits a {PendingAdminUpdated} event.\n    function acceptAdmin() external;\n\n    /// @notice Set a new alchemist deposit cap.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {DepositCapUpdated} event.\n    ///\n    /// @param value The value of the new deposit cap.\n    function setDepositCap(uint256 value) external;\n\n    /// @notice Sets the token adapter for the yield token.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {TokenAdapterSet} event.\n    ///\n    /// @param value The address of token adapter.\n    function setTokenAdapter(address value) external;\n\n    /// @notice Set the minimum collateralization ratio.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {MinimumCollateralizationUpdated} event.\n    ///\n    /// @param value The new minimum collateralization ratio.\n    function setMinimumCollateralization(uint256 value) external;\n\n    /// @notice Set a new protocol fee receiver.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {ProtocolFeeReceiverUpdated} event.\n    ///\n    /// @param receiver The address of the new fee receiver.\n    function setProtocolFeeReceiver(address receiver) external;\n\n    /// @notice Set a new protocol debt fee.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {ProtocolFeeUpdated} event.\n    ///\n    /// @param fee The new protocol debt fee.\n    function setProtocolFee(uint256 fee) external;\n\n    /// @notice Set a new liquidator fee.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {LiquidatorFeeUpdated} event.\n    ///\n    /// @param fee The new liquidator fee.\n    function setLiquidatorFee(uint256 fee) external;\n\n    /// @notice Set a new repayment fee.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {RepaymentFeeUpdated} event.\n    ///\n    /// @param fee The new repayment fee.\n    function setRepaymentFee(uint256 fee) external;\n\n    /// @notice Set the global minimum collateralization ratio.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {GlobalMinimumCollateralizationUpdated} event.\n    ///\n    /// @param value The new global minimum collateralization ratio.\n    function setGlobalMinimumCollateralization(uint256 value) external;\n\n    /// @notice Set the collateralization lower bound ratio.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {CollateralizationLowerBoundUpdated} event.\n    ///\n    /// @param value The new collateralization lower bound ratio.\n    function setCollateralizationLowerBound(uint256 value) external;\n\n    /// @notice Set the liquidation target collateralization ratio.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {LiquidationTargetCollateralizationUpdated} event.\n    ///\n    /// @param value The new liquidation target collateralization ratio.\n    function setLiquidationTargetCollateralization(uint256 value) external;\n\n    /// @notice Pause all future deposits in the Alchemist.\n    ///\n    /// @notice `msg.sender` must be the admin or guardian or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {DepositsPaused} event.\n    ///\n    /// @param isPaused The new pause state for deposits in the alchemist.\n    function pauseDeposits(bool isPaused) external;\n\n    /// @notice Pause all future loans in the Alchemist.\n    ///\n    /// @notice `msg.sender` must be the admin or guardian or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {LoansPaused} event.\n    ///\n    /// @param isPaused The new pause state for loans in the alchemist.\n    function pauseLoans(bool isPaused) external;\n\n    /// @notice Set the alchemist Fee vault.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {AlchemistFeeVaultUpdated} event.\n    ///\n    /// @param value The address of the new alchemist Fee vault.\n    function setAlchemistFeeVault(address value) external;\n}\n\ninterface IAlchemistV3Events {\n    /// @notice Emitted when the pending admin is updated.\n    ///\n    /// @param pendingAdmin The address of the pending admin.\n    event PendingAdminUpdated(address pendingAdmin);\n\n    /// @notice Emitted when the alchemist Fee vault is updated.\n    ///\n    /// @param alchemistFeeVault The address of the alchemist Fee vault.\n    event AlchemistFeeVaultUpdated(address alchemistFeeVault);\n\n    /// @notice Emitted when the administrator is updated.\n    ///\n    /// @param admin The address of the administrator.\n    event AdminUpdated(address admin);\n\n    /// @notice Emitted when the deposit cap is updated.\n    ///\n    /// @param value The value of the new deposit cap.\n    event DepositCapUpdated(uint256 value);\n\n    /// @notice Emitted when a guardian is added or removed from the alchemist.\n    ///\n    /// @param guardian The addres of the new guardian.\n    /// @param state    The active state of the guardian.\n    event GuardianSet(address guardian, bool state);\n\n    /// @notice Emitted when a new token adapter is set in the alchemist.\n    ///\n    /// @param adapter The addres of the new adapter.\n    event TokenAdapterUpdated(address adapter);\n\n    /// @notice Emitted when the transmuter is updated.\n    ///\n    /// @param transmuter The updated address of the transmuter.\n    event TransmuterUpdated(address transmuter);\n\n    /// @notice Emitted when the minimum collateralization is updated.\n    ///\n    /// @param minimumCollateralization The updated minimum collateralization.\n    event MinimumCollateralizationUpdated(uint256 minimumCollateralization);\n\n    /// @notice Emitted when the global minimum collateralization is updated.\n    ///\n    /// @param globalMinimumCollateralization The updated global minimum collateralization.\n    event GlobalMinimumCollateralizationUpdated(uint256 globalMinimumCollateralization);\n\n    /// @notice Emitted when the collateralization lower bound (for a liquidation) is updated.\n    ///\n    /// @param collateralizationLowerBound The updated collateralization lower bound.\n    event CollateralizationLowerBoundUpdated(uint256 collateralizationLowerBound);\n\n    /// @notice Emitted when the liquidation target collateralization ratio is updated.\n    ///\n    /// @param liquidationTargetCollateralization The updated liquidation target collateralization.\n    event LiquidationTargetCollateralizationUpdated(uint256 liquidationTargetCollateralization);\n\n    /// @notice Emitted when deposits are paused or unpaused in the alchemist.\n    ///\n    /// @param isPaused The current pause state of deposits in the alchemist.\n    event DepositsPaused(bool isPaused);\n\n    /// @notice Emitted when loans are paused or unpaused in the alchemist.\n    ///\n    /// @param isPaused The current pause state of loans in the alchemist.\n    event LoansPaused(bool isPaused);\n\n    /// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf.\n    ///\n    /// @param ownerTokenId   The id of the account authorized to grant approval\n    /// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.\n    /// @param amount  The amount of debt tokens that `spender` is allowed to mint.\n    event ApproveMint(uint256 indexed ownerTokenId, address indexed spender, uint256 amount);\n\n    /// @notice Emitted when a user deposits `amount of yieldToken to `recipient`.\n    ///\n    /// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the\n    ///         underlying tokens were wrapped.\n    ///\n    /// @param amount       The amount of yield tokens that were deposited.\n    /// @param recipientId    The id of the account that received the deposited funds.\n    event Deposit(uint256 amount, uint256 indexed recipientId);\n\n    /// @notice Emitted when yieldToken is withdrawn from the account owned.\n    ///         by `owner` to `recipient`.\n    ///\n    /// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens\n    ///         were unwrapped.\n    ///\n    /// @param amount     Amount of tokens withdrawn.\n    /// @param tokenId The id of the account that the funds are withdrawn from.\n    /// @param recipient  The address that received the withdrawn funds.\n    event Withdraw(uint256 amount, uint256 indexed tokenId, address recipient);\n\n    /// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`.\n    ///\n    /// @param tokenId     The tokenId of the account owner.\n    /// @param amount    The amount of tokens that were minted.\n    /// @param recipient The recipient of the minted tokens.\n    event Mint(uint256 indexed tokenId, uint256 amount, address recipient);\n\n    /// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to  account owner `recipientId`.\n    ///\n    /// @param amount    The amount of tokens that were burned.\n    /// @param recipientId The token id of account owned by recipientId that received credit for the burned tokens.\n    event Burn(address indexed sender, uint256 amount, uint256 indexed recipientId);\n\n    /// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to account owned by `recipientId`.\n    ///\n    /// @param sender          The address which is repaying tokens.\n    /// @param amount          The amount of the underlying token that was used to repay debt.\n    /// @param recipientId     The id of account that received credit for the repaid tokens.\n    /// @param credit          The amount of debt that was paid-off to the account owned by owner.\n    event Repay(address indexed sender, uint256 amount, uint256 indexed recipientId, uint256 credit);\n\n    /// @notice Emitted when the transmuter triggers a redemption.\n    ///\n    /// @param amount   The amount of debt to redeem.\n    event Redemption(uint256 amount);\n\n    /// @notice Emitted when the protocol debt fee is updated.\n    ///\n    /// @param fee  The new protocol fee.\n    event ProtocolFeeUpdated(uint256 fee);\n\n    /// @notice Emitted when the liquidator fee is updated.\n    ///\n    /// @param fee  The new liquidator fee.\n    event LiquidatorFeeUpdated(uint256 fee);\n\n    /// @notice Emitted when the repayment fee is updated.\n    ///\n    /// @param fee  The new repayment fee.\n    event RepaymentFeeUpdated(uint256 fee);\n\n    /// @notice Emitted when the fee receiver is updated.\n    ///\n    /// @param receiver   The address of the new receiver.\n    event ProtocolFeeReceiverUpdated(address receiver);\n\n    /// @notice Emitted when account owned by 'accountId' has been liquidated.\n    ///\n    /// @param accountId        The token id of the account liquidated\n    /// @param liquidator   The address of the liquidator\n    /// @param amount       The amount liquidated in yield tokens\n    /// @param feeInYield          The liquidation fee sent to 'liquidator' in yield tokens.\n    /// @param feeInUnderlying            The liquidation fee sent to 'liquidator' in ETH (if needed i.e. if there isn't enough remaining collateral to cover the fee).\n    event Liquidated(uint256 indexed accountId, address liquidator, uint256 amount, uint256 feeInYield, uint256 feeInUnderlying);\n\n    /// @notice Emitted when account owned by 'accountId' has been self liquidated.\n    ///\n    /// @param accountId        The token id of the account self liquidated\n    /// @param amountLiquidated The amount liquidated in yield tokens\n    event SelfLiquidated(uint256 indexed accountId, uint256 amountLiquidated);\n\n    /// @notice Emitted when account for 'owner' has been liquidated.\n    ///\n    /// @param accounts       The address of the accounts liquidated\n    /// @param liquidator   The address of the liquidator\n    /// @param amount       The amount liquidated\n    /// @param feeInYield          The liquidation fee sent to 'liquidator' in yield tokens.\n    /// @param feeInETH            The liquidation fee sent to 'liquidator' in ETH (if needed i.e. if there isn't enough remaining collateral to cover the fee).\n    event BatchLiquidated(uint256[] indexed accounts, address liquidator, uint256 amount, uint256 feeInYield, uint256 feeInETH);\n\n    /// @notice Emitted when all mint allowances for account managed by `tokenId` are reset.\n    ///\n    /// @param tokenId       The tokenId of the account.\n    event MintAllowancesReset(uint256 indexed tokenId);\n\n    /// @notice Emitted when `amount` of debt is force repaid from `accountId`.\n    ///\n    /// @param accountId       The tokenId of the account.\n    /// @param amount          The amount of debt repaid.\n    /// @param creditToYield   The amount of collateral used to repay the debt in yield tokens.\n    /// @param protocolFeeTotal The amount of protocol fee paid.\n    event ForceRepay(uint256 indexed accountId, uint256 amount, uint256 creditToYield, uint256 protocolFeeTotal);\n\n    /// @notice Emitted when `amount` of debt is repaid from `accountId`.\n    ///\n    /// @param accountId       The tokenId of the account.\n    /// @param feeReciever     The address of the fee receiver.\n    /// @param feeInYield      The amount of fee paid in yield tokens.\n    /// @param feeInUnderlying The amount of fee paid in underlying tokens.\n    event RepaymentFee(uint256 indexed accountId, address feeReciever, uint256 feeInYield, uint256 feeInUnderlying);\n\n    /// @notice Emitted when a fee-vault payout is short of the requested amount.\n    ///\n    /// @param liquidator The liquidator receiving the payout.\n    /// @param requested  The requested fee amount in underlying tokens.\n    /// @param paid       The amount actually paid from the fee vault.\n    event FeeShortfall(address indexed liquidator, uint256 requested, uint256 paid);\n\n\n    /// @notice Emitted when a new Position NFT is minted.\n    ///\n    /// @param to The address of the account that minted the Position NFT.\n    /// @param tokenId The tokenId of the Position NFT.\n    event AlchemistV3PositionNFTMinted(address indexed to, uint256 indexed tokenId);\n}\n\ninterface IAlchemistV3Immutables {\n    /// @notice Returns the version of the alchemist.\n    ///\n    /// @return The version.\n    function version() external view returns (string memory);\n\n    /// @notice Returns the address of the debt token used by the system.\n    ///\n    /// @return The address of the debt token.\n    function debtToken() external view returns (address);\n}\n\ninterface IAlchemistV3State {\n    /// @notice Gets the address of the admin.\n    ///\n    /// @return admin The admin address.\n    function admin() external view returns (address admin);\n\n    function depositCap() external view returns (uint256 cap);\n\n    function guardians(address guardian) external view returns (bool isActive);\n\n    function cumulativeEarmarked() external view returns (uint256 earmarked);\n\n    function lastEarmarkBlock() external view returns (uint256 block);\n\n    function lastRedemptionBlock() external view returns (uint256 block);\n\n    function lastTransmuterTokenBalance() external view returns (uint256 balance);\n\n    function totalDebt() external view returns (uint256 debt);\n\n    function totalSyntheticsIssued() external view returns (uint256 syntheticAmount);\n\n    function protocolFee() external view returns (uint256 fee);\n\n    function liquidatorFee() external view returns (uint256 fee);\n\n    function repaymentFee() external view returns (uint256 fee);\n\n    function underlyingConversionFactor() external view returns (uint256 factor);\n\n    function protocolFeeReceiver() external view returns (address receiver);\n\n    function underlyingToken() external view returns (address token);\n\n    function myt() external view returns (address token);\n\n    function depositsPaused() external view returns (bool isPaused);\n\n    function loansPaused() external view returns (bool isPaused);\n\n    function alchemistPositionNFT() external view returns (address nftContract);\n\n    /// @notice Gets the address of the pending administrator.\n    ///\n    /// @return pendingAdmin The pending administrator address.\n    function pendingAdmin() external view returns (address pendingAdmin);\n\n    /// @notice Gets the address of the current yield token adapter.\n    ///\n    /// @return adapter The token adapter address.\n    function tokenAdapter() external returns (address adapter);\n\n    /// @notice Gets the address of the alchemist fee vault.\n    ///\n    /// @return vault The alchemist fee vault address.\n    function alchemistFeeVault() external view returns (address vault);\n\n    /// @notice Gets the address of the transmuter.\n    ///\n    /// @return transmuter The transmuter address.\n    function transmuter() external view returns (address transmuter);\n\n    /// @notice Gets the minimum collateralization.\n    ///\n    /// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt.\n    ///\n    /// @dev The value returned is a 18 decimal fixed point integer.\n    ///\n    /// @return minimumCollateralization The minimum collateralization.\n    function minimumCollateralization() external view returns (uint256 minimumCollateralization);\n\n    /// @notice Gets the global minimum collateralization.\n    ///\n    /// @notice Collateralization is determined by taking the total value of collateral deposited in the alchemist and dividing it by the total debt.\n    ///\n    /// @dev The value returned is a 18 decimal fixed point integer.\n    ///\n    /// @return globalMinimumCollateralization The global minimum collateralization.\n    function globalMinimumCollateralization() external view returns (uint256 globalMinimumCollateralization);\n\n    ///  @notice Gets collaterlization level that will result in an account being eligible for partial liquidation\n    function collateralizationLowerBound() external view returns (uint256 ratio);\n\n    /// @notice Gets the liquidation target collateralization ratio.\n    ///\n    /// @notice This is the collateralization ratio that accounts are restored to after liquidation.\n    ///\n    /// @dev The value returned is a 18 decimal fixed point integer.\n    ///\n    /// @return liquidationTargetCollateralization The liquidation target collateralization.\n    function liquidationTargetCollateralization() external view returns (uint256 liquidationTargetCollateralization);\n\n    /// @dev Returns the debt value of `amount` yield tokens.\n    ///\n    /// @param amount   The amount to convert.\n    function convertYieldTokensToDebt(uint256 amount) external view returns (uint256);\n\n    /// @dev Returns the underlying value of `amount` yield tokens.\n    ///\n    /// @param amount   The amount to convert.\n    function convertYieldTokensToUnderlying(uint256 amount) external view returns (uint256);\n\n    /// @dev Returns the yield token value of `amount` debt tokens.\n    ///\n    /// @param amount   The amount to convert.\n    function convertDebtTokensToYield(uint256 amount) external view returns (uint256);\n\n    /// @dev Returns the yield token value of `amount` underlying tokens.\n    ///\n    /// @param amount   The amount to convert.\n    function convertUnderlyingTokensToYield(uint256 amount) external view returns (uint256);\n\n    /// @notice Calculates fee, net debt burn, and gross collateral seize,\n    ///         using a single minCollateralization factor (FIXED_POINT_SCALAR scaled).\n    /// @param collateral               Current collateral value\n    /// @param debt                     Current debt value\n    /// @param targetCollateralization  Target collateralization ratio, (e.g. 100/90 =  1.1111e18 for 111.11%)\n    /// @param alchemistCurrentCollateralization Current collateralization ratio of the alchemist\n    /// @param alchemistMinimumCollateralization Minimum collateralization ratio of the alchemist to trigger full liquidation\n    /// @param feeBps                   Fee in basis points on the surplus (0–10000)\n    /// @return grossCollateralToSeize  Total collateral to take (fee + net)\n    /// @return debtToBurn              Amount of debt to erase (sent to protocol)\n    /// @return fee                     Amount of collateral paid to liquidator\n    /// @return outsourcedFee           Amount of fee paid to liquidator in underlying tokens in the event that account funds are insufficient to cover the fee\n    function calculateLiquidation(\n        uint256 collateral,\n        uint256 debt,\n        uint256 targetCollateralization,\n        uint256 alchemistCurrentCollateralization,\n        uint256 alchemistMinimumCollateralization,\n        uint256 feeBps\n    ) external view returns (uint256 grossCollateralToSeize, uint256 debtToBurn, uint256 fee, uint256 outsourcedFee);\n\n    /// @dev Normalizes underlying tokens to debt tokens.\n    /// @notice This is to handle decimal conversion in the case where underlying tokens have < 18 decimals.\n    ///\n    /// @param amount   The amount to convert.\n    function normalizeUnderlyingTokensToDebt(uint256 amount) external view returns (uint256);\n\n    /// @dev Normalizes debt tokens to underlying tokens.\n    /// @notice This is to handle decimal conversion in the case where underlying tokens have < 18 decimals.\n    ///\n    /// @param amount   The amount to convert.\n    function normalizeDebtTokensToUnderlying(uint256 amount) external view returns (uint256);\n\n    /// @dev Get information about CDP of tokenId\n    ///\n    /// @param  tokenId   The token Id of the account.\n    ///\n    /// @return collateral  Collateral balance.\n    /// @return debt        Current debt.\n    /// @return earmarked   Current debt that is earmarked for redemption.\n    function getCDP(uint256 tokenId) external view returns (uint256 collateral, uint256 debt, uint256 earmarked);\n\n    /// @dev Gets total value of account managed by `tokenId` in units of underlying tokens.\n    ///\n    /// @param tokenId    tokenId of the account to query.\n    ///\n    /// @return value   Underlying value of the account.\n    function totalValue(uint256 tokenId) external view returns (uint256 value);\n\n    /// @dev Gets total value deposited in the alchemist\n    ///\n    /// @return amount   Total deposite amount.\n    function getTotalDeposited() external view returns (uint256 amount);\n\n    /// @dev Gets maximum debt that `user` can borrow from their CDP.\n    ///\n    /// @param tokenId    tokenId of the account to query.\n    ///\n    /// @return maxDebt   Maximum debt that can be taken.\n    function getMaxBorrowable(uint256 tokenId) external view returns (uint256 maxDebt);\n\n    \n    /// @notice Returns the maximum MYT shares that could be withdrawn from a position\n    ///\n    /// @param tokenId    tokenId of the account to query.\n    ///\n    /// @return maxWithraw   Maximum yield tokens that can be withdrawn.\n    function getMaxWithdrawable(uint256 tokenId) external view returns (uint256 maxWithraw);\n\n    /// @dev Gets total underlying value deposited in the alchemist.\n    ///\n    /// @return TVL   Total value deposited.\n    function getTotalUnderlyingValue() external view returns (uint256 TVL);\n\n    /// @dev Gets total underlying value locked in the alchemist.\n    ///\n    /// @return TVL   Total value locked.\n    function getTotalLockedUnderlyingValue() external view returns (uint256);\n\n    /// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`.\n    ///\n    /// @param ownerTokenId    tokenId of the account to query.\n    /// @param spender The address which is allowed to mint on behalf of `owner`.\n    ///\n    /// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`.\n    function mintAllowance(uint256 ownerTokenId, address spender) external view returns (uint256 allowance);\n}\n\ninterface IAlchemistV3Errors {\n    /// @notice An error which is used to indicate that an operation failed because an account became undercollateralized.\n    error Undercollateralized();\n\n    /// @notice An error which is used to indicate that a liquidate operation failed because an account is sufficiaenly collateralized.\n    error LiquidationError();\n\n    /// @notice An error which is used to indicate that a user is performing an action on an account that requires account ownership\n    error UnauthorizedAccountAccessError();\n\n    /// @notice An error which is used to indicate that a burn operation failed because the transmuter requires more debt in the system.\n    ///\n    /// @param amount    The amount of debt tokens that were requested to be burned.\n    /// @param available The amount of debt tokens which can be burned;\n    error BurnLimitExceeded(uint256 amount, uint256 available);\n\n    /// @notice An error which is used to indicate that the account id used is not linked to any owner\n    error UnknownAccountOwnerIDError();\n\n    /// @notice An error which is used to indicate that the NFT address being set is the zero address\n    error AlchemistV3NFTZeroAddressError();\n\n    /// @notice An error which is used to indicate that the NFT address for the Alchemist has already been set\n    error AlchemistV3NFTAlreadySetError();\n\n    /// @notice An error which is used to indicate that the token address for the AlchemistTokenVault does not match the underlyingToken\n    error AlchemistVaultTokenMismatchError();\n\n    /// @notice An error which is used to indicate that a user is trying to repay on the same block they are minting\n    error CannotRepayOnMintBlock();\n    error CannotMintOnRepayBlock();\n\n    error GlobalCollateralizationTooLow(uint256, uint256);\n\n    /// @notice An error which is used to indicate that an account is not healthy\n    error AccountNotHealthy();\n}\n\n/// @title  IAlchemistV3\n/// @author Alchemix Finance\ninterface IAlchemistV3 is IAlchemistV3Actions, IAlchemistV3AdminActions, IAlchemistV3Errors, IAlchemistV3Immutables, IAlchemistV3Events, IAlchemistV3State {}\n"},"src/interfaces/ITransmuter.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.28;\n\nimport \"./IAlchemistV3.sol\";\n\ninterface ITransmuter {\n    struct StakingPosition {\n        // Amount staked.\n        uint256 amount;\n        // Block when the position was opened\n        uint256 startBlock;\n        // Time when the transmutation will be complete/claimable.\n        uint256 maturationBlock;\n    }\n\n    struct TransmuterInitializationParams {\n        address syntheticToken;\n        address feeReceiver;\n        uint256 timeToTransmute;\n        uint256 transmutationFee;\n        uint256 exitFee;\n        uint256 graphSize;\n    }\n\n    /// @notice Gets the address of the alchemist.\n    ///\n    /// @return alchemist The alchemist address.\n    function alchemist() external view returns (IAlchemistV3 alchemist);\n\n    /// @notice Gets the address of the admin.\n    ///\n    /// @return admin The admin address.\n    function admin() external view returns (address admin);\n\n    /// @notice Gets the address of the pending admin.\n    ///\n    /// @return pendingAdmin The pending admin address.\n    function pendingAdmin() external view returns (address pendingAdmin);\n\n    /// @notice Returns the version of the alchemist.\n    function version() external view returns (string memory version);\n\n    /// @notice Returns the address of the synthetic token.\n    function syntheticToken() external view returns (address token);\n\n    /// @notice Returns the current transmuter deposit cap.\n    function depositCap() external view returns (uint256 cap);\n\n    /// @notice Returns the transmutation early exit fee.\n    /// @notice This is for users who choose to pull from the transmuter before their position has fully matured.\n    function exitFee() external view returns (uint256 fee);\n\n    /// @notice Returns the transmutation fee.\n    /// @notice This fee affects all claims.\n    function transmutationFee() external view returns (uint256 fee);\n\n    /// @notice Returns the current time to transmute (in blocks).\n    function timeToTransmute() external view returns (uint256 transmutationTime);\n\n    /// @notice Returns the total locked debt tokens in the transmuter adjusted for poked accounts.\n    function totalActiveLocked() external view returns (uint256 totalLocked);\n\n    /// @notice Returns the total locked debt tokens in the transmuter.\n    function totalLocked() external view returns (uint256 totalLocked);\n\n    function protocolFeeReceiver() external view returns (address receiver);\n\n    /// @notice Sets the pending administrator.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {PendingAdminUpdated} event.\n    ///\n    /// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process.\n    ///\n    /// @param value The address to set the pending admin to.\n    function setPendingAdmin(address value) external;\n\n    /// @notice Allows for `msg.sender` to accepts the role of administrator.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    /// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error.\n    ///\n    /// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set.\n    ///\n    /// @notice Emits a {AdminUpdated} event.\n    /// @notice Emits a {PendingAdminUpdated} event.\n    function acceptAdmin() external;\n\n    /// @notice Set a new alchemist for redemptions.\n    ///\n    /// @param alchemist The address of the new alchemist.\n    function setAlchemist(address alchemist) external;\n\n    /// @notice Updates transmuter deposit limit to `cap`.\n    ///\n    /// @notice `cap` must be greater or equal to current synths locked in the transmuter.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    ///\n    /// @param cap    The new deposit cap.\n    function setDepositCap(uint256 cap) external;\n\n    /// @notice Sets time to transmute to `time`.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @param time    The new transmutation time.\n    function setTransmutationTime(uint256 time) external;\n\n    /// @notice Sets the transmutation fee to `fee`.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @param fee    The new transmutation fee.\n    function setTransmutationFee(uint256 fee) external;\n\n    /// @notice Sets the early exit fee to `fee`.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @param fee    The new exit fee.\n    function setExitFee(uint256 fee) external;\n\n    /// @notice Set a new protocol fee receiver.\n    ///\n    /// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.\n    ///\n    /// @notice Emits a {ProtocolFeeReceiverUpdated} event.\n    ///\n    /// @param receiver The address of the new fee receiver.\n    function setProtocolFeeReceiver(address receiver) external;\n\n    /// @notice Gets position info for `id`.\n    ///\n    /// @param id      NFT ID,\n    ///\n    /// @return position   Position data.\n    function getPosition(uint256 id) external view returns (StakingPosition memory position);\n\n    /// @notice Creates a new staking position in the transmuter.\n    ///\n    /// @notice `depositAmount` must be non-zero or this call will revert with a {DepositZeroAmount} error.\n    ///\n    /// @notice Emits a {PositionCreated} event.\n    ///\n    /// @param depositAmount    Amount of debt tokens to deposit.\n    /// @param recipient        Address which will own the minted redemption position NFT.\n    function createRedemption(uint256 depositAmount, address recipient) external;\n\n    /// @notice Claims a staking position from the transmuter.\n    ///\n    /// @notice `id` must return a valid position or this call will revert with a {PositionNotFound} error.\n    /// @notice End block of position must be <= to current block or this call will revert with a {PrematureClaim} error.\n    ///\n    /// @notice Emits a {PositionClaimed} event.\n    ///\n    /// @param id   Id of the nft representing the position.\n    function claimRedemption(\n        uint256 id\n    ) external returns (uint256 claimYield, uint256 feeYield, uint256 syntheticReturned, uint256 syntheticFee);\n\n    /// @notice Queries the staking graph from `startBlock` to `endBlock`.\n    ///\n    /// @param startBlock   The block to start query from.\n    /// @param endBlock     The last block to query up to.\n    ///\n    /// @return totalValue  Total value of tokens needed to fulfill redemptions between `startBlock` and `endBlock`.\n    function queryGraph(uint256 startBlock, uint256 endBlock) external view returns (uint256 totalValue);\n\n    /// @notice Poke matured account to lower deposit cap\n    ///\n    /// @param id   The position ID.\n    function pokeMatured(uint256 id) external;\n\n    /// @notice Emitted when the admin address is updated.\n    ///\n    /// @param admin The new admin address.\n    event AdminUpdated(address admin);\n\n    /// @notice Emitted when the pending admin is updated.\n    ///\n    /// @param pendingAdmin The address of the pending admin.\n    event PendingAdminUpdated(address pendingAdmin);\n\n    /// @notice Emitted when the associated alchemist is updated.\n    ///\n    /// @param alchemist The address of the new alchemist.\n    event AlchemistUpdated(address alchemist);\n\n    /// @dev Emitted when a position is created.\n    ///\n    /// @param creator          The address that created the position.\n    /// @param amountStaked     The amount of tokens staked.\n    /// @param nftId            The id of the newly minted NFT.\n    event PositionCreated(address indexed creator, uint256 amountStaked, uint256 nftId);\n\n    /// @dev Emitted when a position is claimed.\n    ///\n    /// @param claimer          The address that claimed the position.\n    /// @param amountClaimed    The amount of tokens claimed.\n    /// @param amountUnclaimed  The amount of tokens that were not transmuted.\n    event PositionClaimed(address indexed claimer, uint256 amountClaimed, uint256 amountUnclaimed);\n\n    /// @dev Emitted when the graph size is extended.\n    ///\n    /// @param size  The new length of the graph.\n    event GraphSizeUpdated(uint256 size);\n\n    /// @dev Emitted when the deposit cap is updated.\n    ///\n    /// @param cap  The new transmuter deposit cap.\n    event DepositCapUpdated(uint256 cap);\n\n    /// @dev Emitted when the transmutaiton time is updated.\n    ///\n    /// @param time  The new transmutation time in blocks.\n    event TransmutationTimeUpdated(uint256 time);\n\n    /// @dev Emitted when the transmutaiton fee is updated.\n    ///\n    /// @param fee  The new transmutation fee.\n    event TransmutationFeeUpdated(uint256 fee);\n\n    /// @dev Emitted when the early exit fee is updated.\n    ///\n    /// @param fee  The new exit fee.\n    event ExitFeeUpdated(uint256 fee);\n\n    /// @dev Emitted when the fee receiver is updates.\n    ///\n    /// @param recevier  The new receiver.\n    event ProtocolFeeReceiverUpdated(address recevier);\n\n    event PositionPoked(uint256 indexed id, uint256 amountRemovedFromCap);\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC721/ERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721} from \"./IERC721.sol\";\nimport {IERC721Metadata} from \"./extensions/IERC721Metadata.sol\";\nimport {ERC721Utils} from \"./utils/ERC721Utils.sol\";\nimport {Context} from \"../../utils/Context.sol\";\nimport {Strings} from \"../../utils/Strings.sol\";\nimport {IERC165, ERC165} from \"../../utils/introspection/ERC165.sol\";\nimport {IERC721Errors} from \"../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\nabstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {\n    using Strings for uint256;\n\n    // Token name\n    string private _name;\n\n    // Token symbol\n    string private _symbol;\n\n    mapping(uint256 tokenId => address) private _owners;\n\n    mapping(address owner => uint256) private _balances;\n\n    mapping(uint256 tokenId => address) private _tokenApprovals;\n\n    mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;\n\n    /**\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n     */\n    constructor(string memory name_, string memory symbol_) {\n        _name = name_;\n        _symbol = symbol_;\n    }\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\n        return\n            interfaceId == type(IERC721).interfaceId ||\n            interfaceId == type(IERC721Metadata).interfaceId ||\n            super.supportsInterface(interfaceId);\n    }\n\n    /// @inheritdoc IERC721\n    function balanceOf(address owner) public view virtual returns (uint256) {\n        if (owner == address(0)) {\n            revert ERC721InvalidOwner(address(0));\n        }\n        return _balances[owner];\n    }\n\n    /// @inheritdoc IERC721\n    function ownerOf(uint256 tokenId) public view virtual returns (address) {\n        return _requireOwned(tokenId);\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function name() public view virtual returns (string memory) {\n        return _name;\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function symbol() public view virtual returns (string memory) {\n        return _symbol;\n    }\n\n    /// @inheritdoc IERC721Metadata\n    function tokenURI(uint256 tokenId) public view virtual returns (string memory) {\n        _requireOwned(tokenId);\n\n        string memory baseURI = _baseURI();\n        return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : \"\";\n    }\n\n    /**\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n     * by default, can be overridden in child contracts.\n     */\n    function _baseURI() internal view virtual returns (string memory) {\n        return \"\";\n    }\n\n    /// @inheritdoc IERC721\n    function approve(address to, uint256 tokenId) public virtual {\n        _approve(to, tokenId, _msgSender());\n    }\n\n    /// @inheritdoc IERC721\n    function getApproved(uint256 tokenId) public view virtual returns (address) {\n        _requireOwned(tokenId);\n\n        return _getApproved(tokenId);\n    }\n\n    /// @inheritdoc IERC721\n    function setApprovalForAll(address operator, bool approved) public virtual {\n        _setApprovalForAll(_msgSender(), operator, approved);\n    }\n\n    /// @inheritdoc IERC721\n    function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {\n        return _operatorApprovals[owner][operator];\n    }\n\n    /// @inheritdoc IERC721\n    function transferFrom(address from, address to, uint256 tokenId) public virtual {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        // Setting an \"auth\" arguments enables the `_isAuthorized` check which verifies that the token exists\n        // (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.\n        address previousOwner = _update(to, tokenId, _msgSender());\n        if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /// @inheritdoc IERC721\n    function safeTransferFrom(address from, address to, uint256 tokenId) public {\n        safeTransferFrom(from, to, tokenId, \"\");\n    }\n\n    /// @inheritdoc IERC721\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {\n        transferFrom(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n     *\n     * IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the\n     * core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances\n     * consistent with ownership. The invariant to preserve is that for any address `a` the value returned by\n     * `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.\n     */\n    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n        return _owners[tokenId];\n    }\n\n    /**\n     * @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.\n     */\n    function _getApproved(uint256 tokenId) internal view virtual returns (address) {\n        return _tokenApprovals[tokenId];\n    }\n\n    /**\n     * @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in\n     * particular (ignoring whether it is owned by `owner`).\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {\n        return\n            spender != address(0) &&\n            (owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);\n    }\n\n    /**\n     * @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.\n     * Reverts if:\n     * - `spender` does not have approval from `owner` for `tokenId`.\n     * - `spender` does not have approval to manage all of `owner`'s assets.\n     *\n     * WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this\n     * assumption.\n     */\n    function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {\n        if (!_isAuthorized(owner, spender, tokenId)) {\n            if (owner == address(0)) {\n                revert ERC721NonexistentToken(tokenId);\n            } else {\n                revert ERC721InsufficientApproval(spender, tokenId);\n            }\n        }\n    }\n\n    /**\n     * @dev Unsafe write access to the balances, used by extensions that \"mint\" tokens using an {ownerOf} override.\n     *\n     * NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that\n     * a uint256 would ever overflow from increments when these increments are bounded to uint128 values.\n     *\n     * WARNING: Increasing an account's balance using this function tends to be paired with an override of the\n     * {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership\n     * remain consistent with one another.\n     */\n    function _increaseBalance(address account, uint128 value) internal virtual {\n        unchecked {\n            _balances[account] += value;\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner\n     * (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that\n     * `auth` is either the owner of the token, or approved to operate on the token (by the owner).\n     *\n     * Emits a {Transfer} event.\n     *\n     * NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.\n     */\n    function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {\n        address from = _ownerOf(tokenId);\n\n        // Perform (optional) operator check\n        if (auth != address(0)) {\n            _checkAuthorized(from, auth, tokenId);\n        }\n\n        // Execute the update\n        if (from != address(0)) {\n            // Clear approval. No need to re-authorize or emit the Approval event\n            _approve(address(0), tokenId, address(0), false);\n\n            unchecked {\n                _balances[from] -= 1;\n            }\n        }\n\n        if (to != address(0)) {\n            unchecked {\n                _balances[to] += 1;\n            }\n        }\n\n        _owners[tokenId] = to;\n\n        emit Transfer(from, to, tokenId);\n\n        return from;\n    }\n\n    /**\n     * @dev Mints `tokenId` and transfers it to `to`.\n     *\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - `to` cannot be the zero address.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _mint(address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner != address(0)) {\n            revert ERC721InvalidSender(address(0));\n        }\n    }\n\n    /**\n     * @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must not exist.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeMint(address to, uint256 tokenId) internal {\n        _safeMint(to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {\n        _mint(to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);\n    }\n\n    /**\n     * @dev Destroys `tokenId`.\n     * The approval is cleared when the token is burned.\n     * This is an internal function that does not check if the sender is authorized to operate on the token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _burn(uint256 tokenId) internal {\n        address previousOwner = _update(address(0), tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n    }\n\n    /**\n     * @dev Transfers `tokenId` from `from` to `to`.\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n     *\n     * Requirements:\n     *\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _transfer(address from, address to, uint256 tokenId) internal {\n        if (to == address(0)) {\n            revert ERC721InvalidReceiver(address(0));\n        }\n        address previousOwner = _update(to, tokenId, address(0));\n        if (previousOwner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        } else if (previousOwner != from) {\n            revert ERC721IncorrectOwner(from, tokenId, previousOwner);\n        }\n    }\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients\n     * are aware of the ERC-721 standard to prevent tokens from being forever locked.\n     *\n     * `data` is additional data, it has no specified format and it is sent in call to `to`.\n     *\n     * This internal function is like {safeTransferFrom} in the sense that it invokes\n     * {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\n     *\n     * Requirements:\n     *\n     * - `tokenId` token must exist and be owned by `from`.\n     * - `to` cannot be the zero address.\n     * - `from` cannot be the zero address.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId) internal {\n        _safeTransfer(from, to, tokenId, \"\");\n    }\n\n    /**\n     * @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n     */\n    function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {\n        _transfer(from, to, tokenId);\n        ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);\n    }\n\n    /**\n     * @dev Approve `to` to operate on `tokenId`\n     *\n     * The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is\n     * either the owner of the token, or approved to operate on all tokens held by this owner.\n     *\n     * Emits an {Approval} event.\n     *\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\n     */\n    function _approve(address to, uint256 tokenId, address auth) internal {\n        _approve(to, tokenId, auth, true);\n    }\n\n    /**\n     * @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not\n     * emitted in the context of transfers.\n     */\n    function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {\n        // Avoid reading the owner unless necessary\n        if (emitEvent || auth != address(0)) {\n            address owner = _requireOwned(tokenId);\n\n            // We do not use _isAuthorized because single-token approvals should not be able to call approve\n            if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {\n                revert ERC721InvalidApprover(auth);\n            }\n\n            if (emitEvent) {\n                emit Approval(owner, to, tokenId);\n            }\n        }\n\n        _tokenApprovals[tokenId] = to;\n    }\n\n    /**\n     * @dev Approve `operator` to operate on all of `owner` tokens\n     *\n     * Requirements:\n     * - operator can't be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {\n        if (operator == address(0)) {\n            revert ERC721InvalidOperator(operator);\n        }\n        _operatorApprovals[owner][operator] = approved;\n        emit ApprovalForAll(owner, operator, approved);\n    }\n\n    /**\n     * @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).\n     * Returns the owner.\n     *\n     * Overrides to ownership logic should be done to {_ownerOf}.\n     */\n    function _requireOwned(uint256 tokenId) internal view returns (address) {\n        address owner = _ownerOf(tokenId);\n        if (owner == address(0)) {\n            revert ERC721NonexistentToken(tokenId);\n        }\n        return owner;\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC721/extensions/ERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/ERC721Enumerable.sol)\n\npragma solidity ^0.8.20;\n\nimport {ERC721} from \"../ERC721.sol\";\nimport {IERC721Enumerable} from \"./IERC721Enumerable.sol\";\nimport {IERC165} from \"../../../utils/introspection/ERC165.sol\";\n\n/**\n * @dev This implements an optional extension of {ERC721} defined in the ERC that adds enumerability\n * of all the token ids in the contract as well as all token ids owned by each account.\n *\n * CAUTION: {ERC721} extensions that implement custom `balanceOf` logic, such as {ERC721Consecutive},\n * interfere with enumerability and should not be used together with {ERC721Enumerable}.\n */\nabstract contract ERC721Enumerable is ERC721, IERC721Enumerable {\n    mapping(address owner => mapping(uint256 index => uint256)) private _ownedTokens;\n    mapping(uint256 tokenId => uint256) private _ownedTokensIndex;\n\n    uint256[] private _allTokens;\n    mapping(uint256 tokenId => uint256) private _allTokensIndex;\n\n    /**\n     * @dev An `owner`'s token query was out of bounds for `index`.\n     *\n     * NOTE: The owner being `address(0)` indicates a global out of bounds index.\n     */\n    error ERC721OutOfBoundsIndex(address owner, uint256 index);\n\n    /**\n     * @dev Batch mint is not allowed.\n     */\n    error ERC721EnumerableForbiddenBatchMint();\n\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\n        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\n    }\n\n    /// @inheritdoc IERC721Enumerable\n    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {\n        if (index >= balanceOf(owner)) {\n            revert ERC721OutOfBoundsIndex(owner, index);\n        }\n        return _ownedTokens[owner][index];\n    }\n\n    /// @inheritdoc IERC721Enumerable\n    function totalSupply() public view virtual returns (uint256) {\n        return _allTokens.length;\n    }\n\n    /// @inheritdoc IERC721Enumerable\n    function tokenByIndex(uint256 index) public view virtual returns (uint256) {\n        if (index >= totalSupply()) {\n            revert ERC721OutOfBoundsIndex(address(0), index);\n        }\n        return _allTokens[index];\n    }\n\n    /// @inheritdoc ERC721\n    function _update(address to, uint256 tokenId, address auth) internal virtual override returns (address) {\n        address previousOwner = super._update(to, tokenId, auth);\n\n        if (previousOwner == address(0)) {\n            _addTokenToAllTokensEnumeration(tokenId);\n        } else if (previousOwner != to) {\n            _removeTokenFromOwnerEnumeration(previousOwner, tokenId);\n        }\n        if (to == address(0)) {\n            _removeTokenFromAllTokensEnumeration(tokenId);\n        } else if (previousOwner != to) {\n            _addTokenToOwnerEnumeration(to, tokenId);\n        }\n\n        return previousOwner;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's ownership-tracking data structures.\n     * @param to address representing the new owner of the given token ID\n     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\n     */\n    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\n        uint256 length = balanceOf(to) - 1;\n        _ownedTokens[to][length] = tokenId;\n        _ownedTokensIndex[tokenId] = length;\n    }\n\n    /**\n     * @dev Private function to add a token to this extension's token tracking data structures.\n     * @param tokenId uint256 ID of the token to be added to the tokens list\n     */\n    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\n        _allTokensIndex[tokenId] = _allTokens.length;\n        _allTokens.push(tokenId);\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\n     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\n     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\n     * This has O(1) time complexity, but alters the order of the _ownedTokens array.\n     * @param from address representing the previous owner of the given token ID\n     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\n     */\n    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\n        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = balanceOf(from);\n        uint256 tokenIndex = _ownedTokensIndex[tokenId];\n\n        mapping(uint256 index => uint256) storage _ownedTokensByOwner = _ownedTokens[from];\n\n        // When the token to delete is the last token, the swap operation is unnecessary\n        if (tokenIndex != lastTokenIndex) {\n            uint256 lastTokenId = _ownedTokensByOwner[lastTokenIndex];\n\n            _ownedTokensByOwner[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n        }\n\n        // This also deletes the contents at the last position of the array\n        delete _ownedTokensIndex[tokenId];\n        delete _ownedTokensByOwner[lastTokenIndex];\n    }\n\n    /**\n     * @dev Private function to remove a token from this extension's token tracking data structures.\n     * This has O(1) time complexity, but alters the order of the _allTokens array.\n     * @param tokenId uint256 ID of the token to be removed from the tokens list\n     */\n    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\n        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\n        // then delete the last slot (swap and pop).\n\n        uint256 lastTokenIndex = _allTokens.length - 1;\n        uint256 tokenIndex = _allTokensIndex[tokenId];\n\n        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\n        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\n        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\n        uint256 lastTokenId = _allTokens[lastTokenIndex];\n\n        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\n        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\n\n        // This also deletes the contents at the last position of the array\n        delete _allTokensIndex[tokenId];\n        _allTokens.pop();\n    }\n\n    /**\n     * See {ERC721-_increaseBalance}. We need that to account tokens that were minted in batch\n     */\n    function _increaseBalance(address account, uint128 amount) internal virtual override {\n        if (amount > 0) {\n            revert ERC721EnumerableForbiddenBatchMint();\n        }\n        super._increaseBalance(account, amount);\n    }\n}\n"},"src/libraries/NFTMetadataGenerator.sol":{"content":"pragma solidity 0.8.28;\n\nimport {Base64} from \"@openzeppelin/contracts/utils/Base64.sol\";\nimport {Strings} from \"@openzeppelin/contracts/utils/Strings.sol\";\n\nlibrary NFTMetadataGenerator {\n    using Strings for uint256;\n\n    // SVG colors\n    string private constant SVG_BG_COLOR = \"#1e1e1f\";\n    string private constant SVG_TEXT_COLOR = \"#f5c09a\";\n    uint256 private constant TOKEN_ID_CHARS_PER_LINE = 25;\n    uint256 private constant TOKEN_ID_LINE_HEIGHT = 22;\n    uint256 private constant TOKEN_ID_FONT_SIZE = 30;\n    uint256 private constant TOKEN_ID_START_Y = 250;\n\n    /**\n     * @notice Generate on-chain SVG for token\n     * @param tokenId The token ID\n     * @return SVG string\n     */\n    function generateSVG(uint256 tokenId, string memory title) internal pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 500 500\" width=\"500\" height=\"500\">',\n                '<rect width=\"500\" height=\"500\" fill=\"',\n                SVG_BG_COLOR,\n                '\" />',\n                '<text x=\"250\" y=\"190\" font-family=\"monospace\" font-size=\"34\" fill=\"',\n                SVG_TEXT_COLOR,\n                '\" text-anchor=\"middle\">',\n                title,\n                \"</text>\",\n                _generateTokenIdText(tokenId),\n                _generateLogo(),\n                \"</svg>\"\n            )\n        );\n    }\n\n    function _generateTokenIdText(uint256 tokenId) private pure returns (string memory) {\n        bytes memory tokenIdBytes = bytes(string(abi.encodePacked(\"#\", tokenId.toString())));\n        uint256 lineCount = (tokenIdBytes.length + TOKEN_ID_CHARS_PER_LINE - 1) / TOKEN_ID_CHARS_PER_LINE;\n\n        bytes memory output = abi.encodePacked(\n            '<text x=\"250\" y=\"',\n            TOKEN_ID_START_Y.toString(),\n            '\" font-family=\"monospace\" font-size=\"',\n            TOKEN_ID_FONT_SIZE.toString(),\n            '\" fill=\"',\n            SVG_TEXT_COLOR,\n            '\" text-anchor=\"middle\">'\n        );\n\n        for (uint256 i = 0; i < lineCount; i++) {\n            uint256 start = i * TOKEN_ID_CHARS_PER_LINE;\n            uint256 end = start + TOKEN_ID_CHARS_PER_LINE;\n            if (end > tokenIdBytes.length) {\n                end = tokenIdBytes.length;\n            }\n\n            bytes memory line = new bytes(end - start);\n            for (uint256 j = start; j < end; j++) {\n                line[j - start] = tokenIdBytes[j];\n            }\n\n            output = abi.encodePacked(\n                output,\n                i == 0 ? '<tspan x=\"250\">' : string(abi.encodePacked('<tspan x=\"250\" dy=\"', TOKEN_ID_LINE_HEIGHT.toString(), '\">')),\n                line,\n                \"</tspan>\"\n            );\n        }\n\n        return string(abi.encodePacked(output, \"</text>\"));\n    }\n\n    function _generateLogo() private pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<g transform=\"translate(135 414) scale(0.237)\">',\n                _generateLogoWordmark(),\n                _generateLogoMark(),\n                \"</g>\"\n            )\n        );\n    }\n\n    function _generateLogoWordmark() private pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<rect x=\"614.1\" y=\"48.9\" width=\"63.9\" height=\"16.1\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<polygon points=\"672.9 89.3 614.1 89.3 614.1 105.4 665.3 105.4 672.9 89.3\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<rect x=\"614.1\" y=\"129.7\" width=\"65.7\" height=\"16.1\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<path d=\"M251.3,49.1h-2.8l-42.2,96.8h16.6l9.6-23.3h33l9.2,23.3h18.8l-41.8-95.9-.4-.9ZM238.4,108l10.9-23.6,10.4,23.6h-21.3Z\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<polygon points=\"332.8 48.7 316.4 48.7 316.4 145.9 379.5 145.9 379.5 129.8 332.8 129.8 332.8 48.7\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<path d=\"M466,124.1c-2.2,1.8-5.1,3.4-8.7,4.8h0c-3.5,1.4-7.6,2.1-12.3,2.1s-12.2-1.5-16.9-4.3c-4.8-2.9-8.5-6.9-11.1-11.9-2.6-5.1-3.9-10.9-3.9-17.3s1.4-12.1,4.3-17.1c2.9-5.1,6.7-9.1,11.5-12.1,4.7-3,10-4.5,15.5-4.5s8.2.7,11.7,2.2c3.6,1.5,6.6,3.1,9,4.8l1.5,1.1,6.7-15.7-1.1-.7c-3.3-2.1-7.4-3.9-12.2-5.5-4.8-1.6-10.2-2.4-16.1-2.4s-13.4,1.3-19.3,3.8c-5.9,2.5-11,6.1-15.3,10.6-4.3,4.5-7.7,9.9-10,16-2.4,6.1-3.6,12.9-3.6,20.2s1.1,12.9,3.4,18.7c2.2,5.8,5.5,11.1,9.8,15.6,4.2,4.5,9.4,8.1,15.4,10.7,6,2.6,12.8,3.9,20.4,4,.4,0,.7,0,1.1,0,4.1,0,7.9-.5,11.4-1.4,3.8-1,7.1-2.2,9.9-3.6,2.8-1.4,5-2.6,6.5-3.5l1.1-.7-7.3-15.2-1.5,1.2Z\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<polygon points=\"565.1 89.1 520.5 89.1 520.5 48.7 504.2 48.7 504.2 145.9 520.5 145.9 520.5 105.1 565.1 105.1 565.1 145.9 581.6 145.9 581.6 48.7 565.1 48.7 565.1 89.1\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<polygon points=\"759.9 111.7 714.7 48.7 712.3 48.7 712.3 145.9 728.3 145.9 728.3 94.4 758.8 136.1 760.6 136.1 792 92.4 792 145.9 808.3 145.9 808.3 48.7 805.8 48.7 759.9 111.7\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<rect x=\"839.8\" y=\"48.9\" width=\"16.3\" height=\"97\" fill=\"', SVG_TEXT_COLOR, '\"/>',\n                '<polygon points=\"935.2 96.8 965.6 48.9 945.8 48.9 926 82.6 904.3 48.9 883.8 48.9 914 96 882.5 145.9 902.6 145.9 923.3 110.6 946 145.9 966.9 145.9 935.2 96.8\" fill=\"', SVG_TEXT_COLOR, '\"/>'\n            )\n        );\n    }\n\n    function _generateLogoMark() private pure returns (string memory) {\n        return string(\n            abi.encodePacked(\n                '<circle cx=\"92.5\" cy=\"97.5\" r=\"79.1\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<line x1=\"92.5\" y1=\"120.4\" x2=\"92.5\" y2=\"176.6\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<line x1=\"92.5\" y1=\"18.4\" x2=\"92.5\" y2=\"35\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<polyline points=\"92.5 120.4 38.6 77.7 92.5 35 146.4 77.7 122.3 96.8\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<polyline points=\"138.1 124.1 146.4 117.6 146.4 77.7\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<polyline points=\"38.6 77.7 38.6 117.6 92.5 160.3 116.8 141\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<polyline points=\"48 125.1 38.8 141 68.2 141\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>',\n                '<polyline points=\"92.5 141 146.2 141 92.5 48.1 64.4 96.6\" fill=\"none\" stroke=\"', SVG_TEXT_COLOR, '\" stroke-linecap=\"round\" stroke-linejoin=\"round\" stroke-width=\"5\"/>'\n            )\n        );\n    }\n\n    /**\n     * @notice Generate the JSON string for the given token ID and SVG.\n     * @param tokenId The token ID.\n     * @param svg The SVG string.\n     * @return The JSON string.\n     */\n    function generateJSONString(uint256 tokenId, string memory svg) internal pure returns (string memory) {\n        string memory json = Base64.encode(\n            abi.encodePacked(\n                '{\"name\": \"AlchemistV3 Position #',\n                tokenId.toString(),\n                '\", ',\n                '\"description\": \"Position token for Alchemist V3\", ',\n                '\"image\": \"data:image/svg+xml;base64,',\n                Base64.encode(bytes(svg)),\n                '\"}'\n            )\n        );\n        return json;\n    }\n\n    /**\n     * @notice Generate the token URI for the given token ID and title.\n     * @param tokenId The token ID.\n     * @param title The title of the token.\n     * @return The full token URI with data.\n     */\n    function generateTokenURI(uint256 tokenId, string memory title) internal pure returns (string memory) {\n        string memory svg = generateSVG(tokenId, title);\n        string memory json = generateJSONString(tokenId, svg);\n        return string(abi.encodePacked(\"data:application/json;base64,\", json));\n    }\n}\n"},"src/libraries/SafeCast.sol":{"content":"// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport {IllegalArgument} from \"../base/Errors.sol\";\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n    /// @notice Cast a uint256 to a int256, revert on overflow\n    /// @param y The uint256 to be casted\n    /// @return z The casted integer, now type int256\n    function toInt256(uint256 y) internal pure returns (int256 z) {\n        if (y >= 2 ** 255) {\n            revert IllegalArgument();\n        }\n        z = int256(y);\n    }\n\n    /// @notice Cast a int256 to a uint256, revert on underflow\n    /// @param y The int256 to be casted\n    /// @return z The casted integer, now type uint256\n    function toUint256(int256 y) internal pure returns (uint256 z) {\n        if (y < 0) {\n            revert IllegalArgument();\n        }\n        z = uint256(y);\n    }\n\n    /// @notice Cast a uint256 to a uint128, revert on underflow\n    /// @param y The uint256 to be casted\n    /// @return z The casted integer, now type uint128\n    function uint256ToUint128(uint256 y) internal pure returns (uint128 z) {\n        if (y > type(uint128).max) {\n            revert IllegalArgument();\n        }\n        z = uint128(y);\n    }\n\n    /// @notice Cast a uint128 to a uint256\n    /// @param y The uint128 to be casted\n    /// @return z The casted integer, now type uint256\n    function uint128ToUint256(uint128 y) internal pure returns (uint256 z) {\n        // Upcast will not overflow\n        z = uint256(y);\n    }\n}\n"},"src/libraries/StakingGraph.sol":{"content":"// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity 0.8.28;\n\n/* Block-granular stake progression tracking for the Transmuter implemented\n * as a double, delta Fenwick tree.  By tracking stake size and range, this\n * structure reports a block-granular report of the full amount of the stake\n * that can be redeemed in aggregate across all Transmuter stakes.\n *\n * For better gas effeciency, storage operations are halved by packing the\n * individual nodes of the two trees into a single 256-bit slot, utilizing\n * a 144/112 bit split.  The least significant portion storing the raw\n * amount, and the other storing the amount * block.  This 144/112 split\n * thus provides 32-bits for block numbers\n */\n\nlibrary StakingGraph {\n\n    //112/144 bit split for delta and product storage, providing 32 bits for start/expiration\n    uint256 private constant DELTA_BITS = 112;\n\n    // Derive related constants from DELTA_BITS\n    uint256 private constant DELTA_MASK    = (uint256(1) << DELTA_BITS) - 1;\n    uint256 private constant DELTA_SIGNBIT =  uint256(1) << (DELTA_BITS - 1);\n\n    uint256 private constant PRODUCT_BITS = 256 - DELTA_BITS;\n    uint256 private constant PRODUCT_SIGNBIT = uint256(1) << (PRODUCT_BITS - 1);\n\n    // Signed ranges that are actually representable in the packed fields\n    int256 private constant DELTA_MAX = int256(DELTA_SIGNBIT - 1);\n    int256 private constant DELTA_MIN = -int256(DELTA_SIGNBIT);\n\n    int256 private constant PRODUCT_MAX = int256(PRODUCT_SIGNBIT - 1);\n    int256 private constant PRODUCT_MIN = -int256(PRODUCT_SIGNBIT);\n\n    // Maximum graph size as per bit-split (32-bit timeline when DELTA_BITS=112)\n    uint256 private constant GRAPH_MAX = uint256(1) << (PRODUCT_BITS - DELTA_BITS);\n\n    //Structure containing full graph state\n    struct Graph {\n        uint256 size;\n        mapping(uint256 => uint256) g;\n    }\n\n    /**\n     * Add/update a position in/to the graph\n     * Revert if amount underflows or overflows, or if start/duration would exceed GRAPH_MAX\n     *\n     * @param g contract storage instance of a Graph struct\n     * @param amount (DELTA_MIN >= amount >= DELTA_MAX)\n     * @param start  block where the stake change begins\n     * @param duration total range of the stake change\n     */\n    function addStake(Graph storage g, int256 amount, uint256 start, uint256 duration) internal {\n        unchecked {\n            require(amount <= DELTA_MAX && amount >= DELTA_MIN);\n            require(start < GRAPH_MAX-1);\n\n            uint256 expiration = start + duration;\n            require(expiration < GRAPH_MAX-1);\n\n            uint256 graphSize = g.size;\n            \n            //check if the tree must be expanded\n\n            uint256 newSize = expiration + 2;\n            if (newSize >= graphSize) {\n                //round expiration up to the next power of 2\n                newSize |= newSize >> 1;\n                newSize |= newSize >> 2;\n                newSize |= newSize >> 4;\n                newSize |= newSize >> 8;\n                newSize |= newSize >> 16;\n                if (GRAPH_MAX > 2**32) {//handle GRAPH_MAX > 32-bit\n                    newSize |= newSize >> 32;\n                    newSize |= newSize >> 64;\n                    newSize |= newSize >> 128;\n                }\n                newSize++;\n\n                //DEBUG: uncomment for maximum tree size\n                //newSize = GRAPH_MAX;\n\n                require (newSize <= GRAPH_MAX);\n\n                if (graphSize != 0) {\n                    //if the graph isn't null, copy the last entry up to the new end\n                    uint256 copy = g.g[graphSize];\n                    while (graphSize <= newSize) {\n                        g.g[graphSize] = copy;\n                        graphSize += graphSize;\n                    }\n                }\n                graphSize = newSize;\n                g.size = newSize;\n            }\n\n            //update tree storage with deltas, revert if results cannot be packed into storage\n            update(g.g, start + 1, graphSize, amount, amount * int256(start));\n            update(g.g, expiration + 1, graphSize, -amount, -amount * int256(expiration));\n        }\n    }\n\n    /**\n     * Query the new amount that is earmarked between blocks start and end\n     * Revert if start or end exceed GRAPH_MAX\n     *\n     * @param g contract storage instance of a Graph struct\n     * @param start block at the start of the query range\n     * @param end block at end of the query range\n     */\n    function queryStake(Graph storage g, uint256 start, uint256 end) internal view returns (int256) {\n        int256 begDelta;\n        int256 begProd;\n        int256 endDelta;\n        int256 endProd;\n        uint256 graphSize;\n        unchecked {\n            require (end <= GRAPH_MAX); //catch overflow\n\n            start--;\n            require (start <= GRAPH_MAX); //catch overflow and underflow\n\n            graphSize = g.size;\n            if (graphSize == 0) return 0;\n\n            // Clamp both prefix query indices to the tree domain.\n            start = start > graphSize ? graphSize : start;\n            end = end > graphSize ? graphSize : end;\n            if (end <= start) return 0;\n\n            (begDelta,begProd) = query(g.g, start);\n            (endDelta,endProd) = query(g.g, end);\n\n            return ((int256(end) * endDelta) - endProd) - ((int256(start) * begDelta) - begProd);\n        }\n    }\n\n    /**\n     * Update the packed fenwick tree with delta & deltaProd.  Extend the tree if possible/necessary\n     * Revert if the partial sums cannot be packed back into the structure\n     *\n     * For internal use within the library for index validation\n     */\n    function update(mapping(uint256 => uint256) storage graph, uint256 index, uint256 treeSize, int256 delta, int256 deltaProd) private {\n        unchecked {\n            index += 1;\n            while (index <= treeSize) {\n                //graph[index] += delta on 2 packed values\n                uint256 packed = graph[index];\n                int256 ad;\n                int256 ap;\n\n                //unpack values\n                if ((packed&DELTA_SIGNBIT) != 0) {\n                    ad = int256(packed | ~DELTA_MASK); //extend set sign bit\n                } else {\n                    ad = int256(packed & DELTA_MASK); //extend zero sign bit\n                }\n                ap = int256(packed)>>DELTA_BITS; //automatic sign extension\n\n                ad+=delta;\n                ap+=deltaProd;\n\n                //pack and store new values\n                require(ad <= DELTA_MAX && ad >= DELTA_MIN);\n                require(ap <= PRODUCT_MAX && ap >= PRODUCT_MIN);\n                graph[index] = (uint256(ad)&DELTA_MASK)|uint256(ap<<DELTA_BITS);\n\n                assembly {\n                    index := add(index, and(index, sub(0, index)))\n                }\n            }\n        }\n    }\n\n    /**\n     * Retrieve a pair of values at the given point index within the packed fenwick tree\n     * No reverts, as the sum of 256 144-bit values cannot overflow int256\n     *\n     * For internal use within the library for index validation\n     */\n     function query(mapping(uint256 => uint256) storage graph, uint256 index) private view returns (int256 sum, int256 sumProd) {\n        unchecked {\n            index += 1;\n            while (index > 0) {\n                //sum += graph[index] on 2 packed values\n                uint256 packed = graph[index];\n                int256 ad;\n                int256 ap;\n\n                //unpack values\n                if ((packed&(2**(DELTA_BITS-1))) != 0) {\n                    ad = int256(packed | ~DELTA_MASK); //extend set sign bit\n                } else {\n                    ad = int256(packed & DELTA_MASK); //extend zero sign bit\n                }\n                ap = int256(packed)>>DELTA_BITS; //automatic sign extension\n\n                sum += ad;\n                sumProd += ap;\n\n                assembly {\n                    index := sub(index, and(index, sub(0, index)))\n                }\n            }\n        }\n    }\n}\n"},"src/libraries/TokenUtils.sol":{"content":"pragma solidity ^0.8.23;\n\nimport \"../../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol\";\nimport \"../../lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"../interfaces/IERC20Burnable.sol\";\nimport \"../interfaces/IERC20Mintable.sol\";\n\n/// @title  TokenUtils\n/// @author Alchemix Finance\nlibrary TokenUtils {\n    /// @notice An error used to indicate that a call to an ERC20 contract failed.\n    ///\n    /// @param target  The target address.\n    /// @param success If the call to the token was a success.\n    /// @param data    The resulting data from the call. This is error data when the call was not a success. Otherwise,\n    ///                this is malformed data when the call was a success.\n    error ERC20CallFailed(address target, bool success, bytes data);\n\n    /// @dev A safe function to get the decimals of an ERC20 token.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.\n    ///\n    /// @param token The target token.\n    ///\n    /// @return The amount of decimals of the token.\n    function expectDecimals(address token) internal view returns (uint8) {\n        (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(IERC20Metadata.decimals.selector));\n\n        if (token.code.length == 0 || !success || data.length < 32) {\n            revert ERC20CallFailed(token, success, data);\n        }\n\n        return abi.decode(data, (uint8));\n    }\n\n    /// @dev Gets the balance of tokens held by an account.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.\n    ///\n    /// @param token   The token to check the balance of.\n    /// @param account The address of the token holder.\n    ///\n    /// @return The balance of the tokens held by an account.\n    function safeBalanceOf(address token, address account) internal view returns (uint256) {\n        (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(IERC20.balanceOf.selector, account));\n\n        if (token.code.length == 0 || !success || data.length < 32) {\n            revert ERC20CallFailed(token, success, data);\n        }\n\n        return abi.decode(data, (uint256));\n    }\n\n    /// @dev Transfers tokens to another address.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value.\n    ///\n    /// @param token     The token to transfer.\n    /// @param recipient The address of the recipient.\n    /// @param amount    The amount of tokens to transfer.\n    function safeTransfer(address token, address recipient, uint256 amount) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, recipient, amount));\n\n        if (token.code.length == 0 || !success || (data.length != 0 && !abi.decode(data, (bool)))) {\n            revert ERC20CallFailed(token, success, data);\n        }\n    }\n\n    /// @dev Approves tokens for the smart contract.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value.\n    ///\n    /// @param token   The token to approve.\n    /// @param spender The contract to spend the tokens.\n    /// @param value   The amount of tokens to approve.\n    function safeApprove(address token, address spender, uint256 value) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, spender, value));\n\n        if (token.code.length == 0 || !success || (data.length != 0 && !abi.decode(data, (bool)))) {\n            revert ERC20CallFailed(token, success, data);\n        }\n    }\n\n    /// @dev Transfer tokens from one address to another address.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value.\n    ///\n    /// @param token     The token to transfer.\n    /// @param owner     The address of the owner.\n    /// @param recipient The address of the recipient.\n    /// @param amount    The amount of tokens to transfer.\n    function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, owner, recipient, amount));\n\n        if (token.code.length == 0 || !success || (data.length != 0 && !abi.decode(data, (bool)))) {\n            revert ERC20CallFailed(token, success, data);\n        }\n    }\n\n    /// @dev Mints tokens to an address.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value.\n    ///\n    /// @param token     The token to mint.\n    /// @param recipient The address of the recipient.\n    /// @param amount    The amount of tokens to mint.\n    function safeMint(address token, address recipient, uint256 amount) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount));\n\n        if (token.code.length == 0 || !success || (data.length != 0 && !abi.decode(data, (bool)))) {\n            revert ERC20CallFailed(token, success, data);\n        }\n    }\n\n    /// @dev Burns tokens.\n    ///\n    /// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value.\n    ///\n    /// @param token  The token to burn.\n    /// @param amount The amount of tokens to burn.\n    function safeBurn(address token, uint256 amount) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20Burnable.burn.selector, amount));\n\n        if (token.code.length == 0 || !success || (data.length != 0 && !abi.decode(data, (bool)))) {\n            revert ERC20CallFailed(token, success, data);\n        }\n    }\n\n    /// @dev Burns tokens from its total supply.\n    ///\n    /// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value.\n    ///\n    /// @param token  The token to burn.\n    /// @param owner  The owner of the tokens.\n    /// @param amount The amount of tokens to burn.\n    function safeBurnFrom(address token, address owner, uint256 amount) internal {\n        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount));\n\n        if (token.code.length == 0 || !success || (data.length != 0 && !abi.decode(data, (bool)))) {\n            revert ERC20CallFailed(token, success, data);\n        }\n    }\n}"},"src/libraries/FixedPointMath.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity ^0.8.23;\n\n/**\n * @notice A library which implements fixed point decimal math.\n */\nlibrary FixedPointMath {\n    /**\n     * @dev This will give approximately 60 bits of precision\n     */\n    uint256 public constant DECIMALS = 18;\n    uint256 public constant ONE = 10 ** DECIMALS;\n\n    error MulDivZeroDenominator();\n    error MulDivOverflow();\n\n    /**\n     * @notice A struct representing a fixed point decimal.\n     */\n    struct Number {\n        uint256 n;\n    }\n\n    /**\n     * @notice Encodes a unsigned 256-bit integer into a fixed point decimal.\n     *\n     * @param value The value to encode.\n     * @return      The fixed point decimal representation.\n     */\n    function encode(uint256 value) internal pure returns (Number memory) {\n        return Number(FixedPointMath.encodeRaw(value));\n    }\n\n    /**\n     * @notice Encodes a unsigned 256-bit integer into a uint256 representation of a\n     *         fixed point decimal.\n     *\n     * @param value The value to encode.\n     * @return      The fixed point decimal representation.\n     */\n    function encodeRaw(uint256 value) internal pure returns (uint256) {\n        return value * ONE;\n    }\n\n    /**\n     * @notice Encodes a uint256 MAX VALUE into a uint256 representation of a\n     *         fixed point decimal.\n     *\n     * @return      The uint256 MAX VALUE fixed point decimal representation.\n     */\n    function max() internal pure returns (Number memory) {\n        return Number(type(uint256).max);\n    }\n\n    /**\n     * @notice Creates a rational fraction as a Number from 2 uint256 values\n     *\n     * @param n The numerator.\n     * @param d The denominator.\n     * @return  The fixed point decimal representation.\n     */\n    function rational(uint256 n, uint256 d) internal pure returns (Number memory) {\n        Number memory numerator = encode(n);\n        return FixedPointMath.div(numerator, d);\n    }\n\n    /**\n     * @notice Adds two fixed point decimal numbers together.\n     *\n     * @param self  The left hand operand.\n     * @param value The right hand operand.\n     * @return      The result.\n     */\n    function add(Number memory self, Number memory value) internal pure returns (Number memory) {\n        return Number(self.n + value.n);\n    }\n\n    /**\n     * @notice Adds a fixed point number to a unsigned 256-bit integer.\n     *\n     * @param self  The left hand operand.\n     * @param value The right hand operand. This will be converted to a fixed point decimal.\n     * @return      The result.\n     */\n    function add(Number memory self, uint256 value) internal pure returns (Number memory) {\n        return add(self, FixedPointMath.encode(value));\n    }\n\n    /**\n     * @notice Subtract a fixed point decimal from another.\n     *\n     * @param self  The left hand operand.\n     * @param value The right hand operand.\n     * @return      The result.\n     */\n    function sub(Number memory self, Number memory value) internal pure returns (Number memory) {\n        return Number(self.n - value.n);\n    }\n\n    /**\n     * @notice Subtract a unsigned 256-bit integer from a fixed point decimal.\n     *\n     * @param self  The left hand operand.\n     * @param value The right hand operand. This will be converted to a fixed point decimal.\n     * @return      The result.\n     */\n    function sub(Number memory self, uint256 value) internal pure returns (Number memory) {\n        return sub(self, FixedPointMath.encode(value));\n    }\n\n    /**\n     * @notice Multiplies a fixed point decimal by another fixed point decimal.\n     *\n     * @param self  The fixed point decimal to multiply.\n     * @param number The fixed point decimal to multiply by.\n     * @return      The result.\n     */\n    function mul(Number memory self, Number memory number) internal pure returns (Number memory) {\n        return Number((self.n * number.n) / ONE);\n    }\n\n    /**\n     * @notice Multiplies a fixed point decimal by an unsigned 256-bit integer.\n     *\n     * @param self  The fixed point decimal to multiply.\n     * @param value The unsigned 256-bit integer to multiply by.\n     * @return      The result.\n     */\n    function mul(Number memory self, uint256 value) internal pure returns (Number memory) {\n        return Number(self.n * value);\n    }\n\n    /**\n     * @notice Divides a fixed point decimal by an unsigned 256-bit integer.\n     *\n     * @param self  The fixed point decimal to multiply by.\n     * @param value The unsigned 256-bit integer to divide by.\n     * @return      The result.\n     */\n    function div(Number memory self, uint256 value) internal pure returns (Number memory) {\n        return Number(self.n / value);\n    }\n\n    /// @notice floor(x * y / denominator) with full precision.\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            if (denominator == 0) revert MulDivZeroDenominator();\n\n            // 512-bit multiply: [prod1 prod0] = x * y\n            uint256 prod0;\n            uint256 prod1;\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow case (prod1 == 0)\n            if (prod1 == 0) {\n                return prod0 / denominator;\n            }\n\n            // Ensure result fits in 256 bits and denominator != 0\n            if (denominator <= prod1) revert MulDivOverflow();\n\n            // Make division exact by subtracting remainder from [prod1 prod0]\n            uint256 remainder;\n            assembly {\n                remainder := mulmod(x, y, denominator)\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                denominator := div(denominator, twos)\n                prod0 := div(prod0, twos)\n                // twos = 2^256 / twos\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift high bits into prod0\n            prod0 |= prod1 * twos;\n\n            // Compute modular inverse of denominator mod 2^256 (denominator is now odd)\n            uint256 inv = (3 * denominator) ^ 2;\n            inv *= 2 - denominator * inv; // 8 bits\n            inv *= 2 - denominator * inv; // 16\n            inv *= 2 - denominator * inv; // 32\n            inv *= 2 - denominator * inv; // 64\n            inv *= 2 - denominator * inv; // 128\n            inv *= 2 - denominator * inv; // 256\n\n            // Multiply by inverse to get the quotient\n            result = prod0 * inv;\n        }\n    }\n\n    /// @notice ceil(x * y / denominator) with full precision.\n    function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        result = mulDiv(x, y, denominator);\n        unchecked {\n            if (mulmod(x, y, denominator) != 0) {\n                if (result == type(uint256).max) revert MulDivOverflow();\n                result += 1;\n            }\n        }\n    }\n    \n    /**\n     * @notice Compares two fixed point decimals.\n     *\n     * @param self  The left hand number to compare.\n     * @param value The right hand number to compare.\n     * @return      When the left hand number is less than the right hand number this returns -1,\n     *              when the left hand number is greater than the right hand number this returns 1,\n     *              when they are equal this returns 0.\n     */\n    function cmp(Number memory self, Number memory value) internal pure returns (int256) {\n        if (self.n < value.n) {\n            return -1;\n        }\n\n        if (self.n > value.n) {\n            return 1;\n        }\n\n        return 0;\n    }\n\n    /**\n     * @notice Gets if two fixed point numbers are equal.\n     *\n     * @param self  the first fixed point number.\n     * @param value the second fixed point number.\n     *\n     * @return if they are equal.\n     */\n    function equals(Number memory self, Number memory value) internal pure returns (bool) {\n        return self.n == value.n;\n    }\n\n    /**\n     * @notice Truncates a fixed point decimal into an unsigned 256-bit integer.\n     *\n     * @return The integer portion of the fixed point decimal.\n     */\n    function truncate(Number memory self) internal pure returns (uint256) {\n        return self.n / ONE;\n    }\n\n    // Math helpers for Q128.128\n    function mulQ128(uint256 aQ, uint256 bQ) internal pure returns (uint256 z) {\n        if (aQ == 0 || bQ == 0) return 0;\n        uint256 lo;\n        uint256 hi;\n        assembly {\n            // 512-bit product [hi lo] = aQ * bQ\n            let mm := mulmod(aQ, bQ, not(0))\n            lo := mul(aQ, bQ)\n            hi := sub(sub(mm, lo), lt(mm, lo))\n        }\n        // floor((a*b) / 2^128)\n        z = (hi << 128) | (lo >> 128);\n        // if there are non-zero low bits, round up\n        if (lo & ((uint256(1) << 128) - 1) != 0) {\n            unchecked {\n                z += 1;\n            }\n        }\n    }\n\n    function divQ128(uint256 numerQ128, uint256 denomQ128) internal pure returns (uint256) {\n        if (numerQ128 == 0) return 0;\n        unchecked {\n            // Fast path: shifting is safe if numerQ128 < 2^128\n            if (numerQ128 <= type(uint256).max >> 128) {\n                return (numerQ128 << 128) / denomQ128;\n            }\n            // Slow path: numerQ128 can only be 2^128 here.\n            uint256 q = numerQ128 / denomQ128; // 0 or 1 in our domain\n            uint256 r = numerQ128 - q * denomQ128; // remainder\n            return (q << 128) + ((r << 128) / denomQ128);\n        }\n    }\n}"},"src/base/Errors.sol":{"content":"pragma solidity ^0.8.23;\n\n/// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or\n///         `msg.origin` is not authorized.\nerror Unauthorized();\n\n/// @notice An error used to indicate that an action could not be completed because the contract either already existed\n///         or entered an illegal condition which is not recoverable from.\nerror IllegalState();\n\n/// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed\n///         to the function.\nerror IllegalArgument();\n\n/// @notice An error used to indicate that an action could not be completed because the required amount of allowance has not\n///         been approved.\nerror InsufficientAllowance();\n\n/// @notice An error used to indicate that the function input data is missing\nerror MissingInputData();\n\n/// @notice An error used to indicate that the function input data is missing\nerror ZeroAmount();\n\n/// @notice An error used to indicate that the function input data is missing\nerror ZeroAddress();\n"},"src/base/TransmuterErrors.sol":{"content":"// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.28;\n\nerror NotRegisteredAlchemist();\n\nerror AlchemistDuplicateEntry();\n\nerror DepositCapReached();\n\nerror DepositZeroAmount();\n\nerror PositionNotFound();\n\nerror PrematureClaim();\n\nerror DepositTooLarge();\n\nerror CallerNotOwner();\n\nerror PositionNotMatured(uint256 id, uint256 maturationBlock, uint256 currentBlock);\n\nerror PositionAlreadyPoked(uint256 id);"},"lib/openzeppelin-contracts/contracts/token/ERC721/IERC721.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC165} from \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev Required interface of an ERC-721 compliant contract.\n */\ninterface IERC721 is IERC165 {\n    /**\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n     */\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n    /**\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n     */\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n    /**\n     * @dev Returns the number of tokens in ``owner``'s account.\n     */\n    function balanceOf(address owner) external view returns (uint256 balance);\n\n    /**\n     * @dev Returns the owner of the `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function ownerOf(uint256 tokenId) external view returns (address owner);\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;\n\n    /**\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n     * are aware of the ERC-721 protocol to prevent tokens from being forever locked.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must exist and be owned by `from`.\n     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or\n     *   {setApprovalForAll}.\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon\n     *   a safe transfer.\n     *\n     * Emits a {Transfer} event.\n     */\n    function safeTransferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Transfers `tokenId` token from `from` to `to`.\n     *\n     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721\n     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n     * understand this adds an external call which potentially creates a reentrancy vulnerability.\n     *\n     * Requirements:\n     *\n     * - `from` cannot be the zero address.\n     * - `to` cannot be the zero address.\n     * - `tokenId` token must be owned by `from`.\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 tokenId) external;\n\n    /**\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n     * The approval is cleared when the token is transferred.\n     *\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n     *\n     * Requirements:\n     *\n     * - The caller must own the token or be an approved operator.\n     * - `tokenId` must exist.\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address to, uint256 tokenId) external;\n\n    /**\n     * @dev Approve or remove `operator` as an operator for the caller.\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n     *\n     * Requirements:\n     *\n     * - The `operator` cannot be the address zero.\n     *\n     * Emits an {ApprovalForAll} event.\n     */\n    function setApprovalForAll(address operator, bool approved) external;\n\n    /**\n     * @dev Returns the account approved for `tokenId` token.\n     *\n     * Requirements:\n     *\n     * - `tokenId` must exist.\n     */\n    function getApproved(uint256 tokenId) external view returns (address operator);\n\n    /**\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n     *\n     * See {setApprovalForAll}\n     */\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC721/extensions/IERC721Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Metadata is IERC721 {\n    /**\n     * @dev Returns the token collection name.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the token collection symbol.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n     */\n    function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Utils.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/utils/ERC721Utils.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC721Receiver} from \"../IERC721Receiver.sol\";\nimport {IERC721Errors} from \"../../../interfaces/draft-IERC6093.sol\";\n\n/**\n * @dev Library that provide common ERC-721 utility functions.\n *\n * See https://eips.ethereum.org/EIPS/eip-721[ERC-721].\n *\n * _Available since v5.1._\n */\nlibrary ERC721Utils {\n    /**\n     * @dev Performs an acceptance check for the provided `operator` by calling {IERC721Receiver-onERC721Received}\n     * on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).\n     *\n     * The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).\n     * Otherwise, the recipient must implement {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept\n     * the transfer.\n     */\n    function checkOnERC721Received(\n        address operator,\n        address from,\n        address to,\n        uint256 tokenId,\n        bytes memory data\n    ) internal {\n        if (to.code.length > 0) {\n            try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {\n                if (retval != IERC721Receiver.onERC721Received.selector) {\n                    // Token rejected\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                }\n            } catch (bytes memory reason) {\n                if (reason.length == 0) {\n                    // non-IERC721Receiver implementer\n                    revert IERC721Errors.ERC721InvalidReceiver(to);\n                } else {\n                    assembly (\"memory-safe\") {\n                        revert(add(reason, 0x20), mload(reason))\n                    }\n                }\n            }\n        }\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/utils/Context.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\n\npragma solidity ^0.8.20;\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 Context {\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/Strings.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.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    uint256 private constant SPECIAL_CHARS_LOOKUP =\n        (1 << 0x08) | // backspace\n            (1 << 0x09) | // tab\n            (1 << 0x0a) | // newline\n            (1 << 0x0c) | // form feed\n            (1 << 0x0d) | // carriage return\n            (1 << 0x22) | // double quote\n            (1 << 0x5c); // backslash\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(add(buffer, 0x20), 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-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 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-string-uint256-uint256} 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-string-uint256-uint256} 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-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 `(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-string-uint256-uint256} 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 guarantees 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-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 `(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-string} 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-string-uint256-uint256} 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 Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.\n     *\n     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.\n     *\n     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of\n     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode\n     * characters that are not in this range, but other tooling may provide different results.\n     */\n    function escapeJSON(string memory input) internal pure returns (string memory) {\n        bytes memory buffer = bytes(input);\n        bytes memory output = new bytes(2 * buffer.length); // worst case scenario\n        uint256 outputLength = 0;\n\n        for (uint256 i; i < buffer.length; ++i) {\n            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));\n            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {\n                output[outputLength++] = \"\\\\\";\n                if (char == 0x08) output[outputLength++] = \"b\";\n                else if (char == 0x09) output[outputLength++] = \"t\";\n                else if (char == 0x0a) output[outputLength++] = \"n\";\n                else if (char == 0x0c) output[outputLength++] = \"f\";\n                else if (char == 0x0d) output[outputLength++] = \"r\";\n                else if (char == 0x5c) output[outputLength++] = \"\\\\\";\n                else if (char == 0x22) {\n                    // solhint-disable-next-line quotes\n                    output[outputLength++] = '\"';\n                }\n            } else {\n                output[outputLength++] = char;\n            }\n        }\n        // write the actual length and deallocate unused memory\n        assembly (\"memory-safe\") {\n            mstore(output, outputLength)\n            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))\n        }\n\n        return string(output);\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(add(buffer, 0x20), offset))\n        }\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.20;\n\nimport {IERC165} from \"./IERC165.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 ERC165 is IERC165 {\n    /// @inheritdoc IERC165\n    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {\n        return interfaceId == type(IERC165).interfaceId;\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)\npragma solidity >=0.8.4;\n\n/**\n * @dev Standard ERC-20 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\n */\ninterface IERC20Errors {\n    /**\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     * @param balance Current balance for the interacting account.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\n     * @param sender Address whose tokens are being transferred.\n     */\n    error ERC20InvalidSender(address sender);\n\n    /**\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\n     * @param receiver Address to which tokens are being transferred.\n     */\n    error ERC20InvalidReceiver(address receiver);\n\n    /**\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\n     * @param needed Minimum amount required to perform a transfer.\n     */\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\n\n    /**\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\n     * @param approver Address initiating an approval operation.\n     */\n    error ERC20InvalidApprover(address approver);\n\n    /**\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\n     */\n    error ERC20InvalidSpender(address spender);\n}\n\n/**\n * @dev Standard ERC-721 Errors\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\n */\ninterface IERC721Errors {\n    /**\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-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/ERC721/extensions/IERC721Enumerable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/extensions/IERC721Enumerable.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC721} from \"../IERC721.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721Enumerable is IERC721 {\n    /**\n     * @dev Returns the total amount of tokens stored by the contract.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\n     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\n     */\n    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);\n\n    /**\n     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\n     * Use along with {totalSupply} to enumerate all tokens.\n     */\n    function tokenByIndex(uint256 index) external view returns (uint256);\n}\n"},"lib/openzeppelin-contracts/contracts/utils/Base64.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/Base64.sol)\n\npragma solidity ^0.8.20;\n\n/**\n * @dev Provides a set of functions to operate with Base64 strings.\n */\nlibrary Base64 {\n    /**\n     * @dev Base64 Encoding/Decoding Table\n     * See sections 4 and 5 of https://datatracker.ietf.org/doc/html/rfc4648\n     */\n    string internal constant _TABLE = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n    string internal constant _TABLE_URL = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n    /**\n     * @dev Converts a `bytes` to its Bytes64 `string` representation.\n     */\n    function encode(bytes memory data) internal pure returns (string memory) {\n        return _encode(data, _TABLE, true);\n    }\n\n    /**\n     * @dev Converts a `bytes` to its Bytes64Url `string` representation.\n     * Output is not padded with `=` as specified in https://www.rfc-editor.org/rfc/rfc4648[rfc4648].\n     */\n    function encodeURL(bytes memory data) internal pure returns (string memory) {\n        return _encode(data, _TABLE_URL, false);\n    }\n\n    /**\n     * @dev Internal table-agnostic conversion\n     */\n    function _encode(bytes memory data, string memory table, bool withPadding) private pure returns (string memory) {\n        /**\n         * Inspired by Brecht Devos (Brechtpd) implementation - MIT licence\n         * https://github.com/Brechtpd/base64/blob/e78d9fd951e7b0977ddca77d92dc85183770daf4/base64.sol\n         */\n        if (data.length == 0) return \"\";\n\n        // If padding is enabled, the final length should be `bytes` data length divided by 3 rounded up and then\n        // multiplied by 4 so that it leaves room for padding the last chunk\n        // - `data.length + 2`  -> Prepare for division rounding up\n        // - `/ 3`              -> Number of 3-bytes chunks (rounded up)\n        // - `4 *`              -> 4 characters for each chunk\n        // This is equivalent to: 4 * Math.ceil(data.length / 3)\n        //\n        // If padding is disabled, the final length should be `bytes` data length multiplied by 4/3 rounded up as\n        // opposed to when padding is required to fill the last chunk.\n        // - `4 * data.length`  -> 4 characters for each chunk\n        // - ` + 2`             -> Prepare for division rounding up\n        // - `/ 3`              -> Number of 3-bytes chunks (rounded up)\n        // This is equivalent to: Math.ceil((4 * data.length) / 3)\n        uint256 resultLength = withPadding ? 4 * ((data.length + 2) / 3) : (4 * data.length + 2) / 3;\n\n        string memory result = new string(resultLength);\n\n        assembly (\"memory-safe\") {\n            // Prepare the lookup table (skip the first \"length\" byte)\n            let tablePtr := add(table, 1)\n\n            // Prepare result pointer, jump over length\n            let resultPtr := add(result, 0x20)\n            let dataPtr := data\n            let endPtr := add(data, mload(data))\n\n            // In some cases, the last iteration will read bytes after the end of the data. We cache the value, and\n            // set it to zero to make sure no dirty bytes are read in that section.\n            let afterPtr := add(endPtr, 0x20)\n            let afterCache := mload(afterPtr)\n            mstore(afterPtr, 0x00)\n\n            // Run over the input, 3 bytes at a time\n            for {} lt(dataPtr, endPtr) {} {\n                // Advance 3 bytes\n                dataPtr := add(dataPtr, 3)\n                let input := mload(dataPtr)\n\n                // To write each character, shift the 3 byte (24 bits) chunk\n                // 4 times in blocks of 6 bits for each character (18, 12, 6, 0)\n                // and apply logical AND with 0x3F to bitmask the least significant 6 bits.\n                // Use this as an index into the lookup table, mload an entire word\n                // so the desired character is in the least significant byte, and\n                // mstore8 this least significant byte into the result and continue.\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n\n                mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F))))\n                resultPtr := add(resultPtr, 1) // Advance\n            }\n\n            // Reset the value that was cached\n            mstore(afterPtr, afterCache)\n\n            if withPadding {\n                // When data `bytes` is not exactly 3 bytes long\n                // it is padded with `=` characters at the end\n                switch mod(mload(data), 3)\n                case 1 {\n                    mstore8(sub(resultPtr, 1), 0x3d)\n                    mstore8(sub(resultPtr, 2), 0x3d)\n                }\n                case 2 {\n                    mstore8(sub(resultPtr, 1), 0x3d)\n                }\n            }\n        }\n\n        return result;\n    }\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-20 standard as defined in the ERC.\n */\ninterface IERC20 {\n    /**\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\n     * another (`to`).\n     *\n     * Note that `value` may be zero.\n     */\n    event Transfer(address indexed from, address indexed to, uint256 value);\n\n    /**\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n     * a call to {approve}. `value` is the new allowance.\n     */\n    event Approval(address indexed owner, address indexed spender, uint256 value);\n\n    /**\n     * @dev Returns the value of tokens in existence.\n     */\n    function totalSupply() external view returns (uint256);\n\n    /**\n     * @dev Returns the value of tokens owned by `account`.\n     */\n    function balanceOf(address account) external view returns (uint256);\n\n    /**\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transfer(address to, uint256 value) external returns (bool);\n\n    /**\n     * @dev Returns the remaining number of tokens that `spender` will be\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\n     * zero by default.\n     *\n     * This value changes when {approve} or {transferFrom} are called.\n     */\n    function allowance(address owner, address spender) external view returns (uint256);\n\n    /**\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\n     * caller's tokens.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\n     * that someone may use both the old and the new allowance by unfortunate\n     * transaction ordering. One possible solution to mitigate this race\n     * condition is to first reduce the spender's allowance to 0 and set the\n     * desired value afterwards:\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n     *\n     * Emits an {Approval} event.\n     */\n    function approve(address spender, uint256 value) external returns (bool);\n\n    /**\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\n     * allowance mechanism. `value` is then deducted from the caller's\n     * allowance.\n     *\n     * Returns a boolean value indicating whether the operation succeeded.\n     *\n     * Emits a {Transfer} event.\n     */\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity >=0.6.2;\n\nimport {IERC20} from \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\n */\ninterface IERC20Metadata is IERC20 {\n    /**\n     * @dev Returns the name of the token.\n     */\n    function name() external view returns (string memory);\n\n    /**\n     * @dev Returns the symbol of the token.\n     */\n    function symbol() external view returns (string memory);\n\n    /**\n     * @dev Returns the decimals places of the token.\n     */\n    function decimals() external view returns (uint8);\n}\n"},"src/interfaces/IERC20Burnable.sol":{"content":"pragma solidity >=0.5.0;\n\nimport \"../../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol\";\n\n/// @title  IERC20Burnable\n/// @author Alchemix Finance\ninterface IERC20Burnable is IERC20 {\n    /// @notice Burns `amount` tokens from the balance of `msg.sender`.\n    ///\n    /// @param amount The amount of tokens to burn.\n    ///\n    /// @return If burning the tokens was successful.\n    function burn(uint256 amount) external returns (bool);\n\n    /// @notice Burns `amount` tokens from `owner`'s balance.\n    ///\n    /// @param owner  The address to burn tokens from.\n    /// @param amount The amount of tokens to burn.\n    ///\n    /// @return If burning the tokens was successful.\n    function burnFrom(address owner, uint256 amount) external returns (bool);\n}"},"src/interfaces/IERC20Mintable.sol":{"content":"pragma solidity >=0.5.0;\n\nimport \"../../lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol\";\n\n/// @title  IERC20Mintable\n/// @author Alchemix Finance\ninterface IERC20Mintable is IERC20 {\n    /// @notice Mints `amount` tokens to `recipient`.\n    ///\n    /// @param recipient The address which will receive the minted tokens.\n    /// @param amount    The amount of tokens to mint.\n    function mint(address recipient, uint256 amount) external;\n}"},"lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)\n\npragma solidity >=0.4.16;\n\n/**\n * @dev Interface of the ERC-165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[ERC].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n    /**\n     * @dev Returns true if this contract implements the interface defined by\n     * `interfaceId`. See the corresponding\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]\n     * to learn more about how these ids are created.\n     *\n     * This function call must use less than 30 000 gas.\n     */\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity >=0.5.0;\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/contracts/utils/math/Math.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.20;\n\nimport {Panic} from \"../Panic.sol\";\nimport {SafeCast} from \"./SafeCast.sol\";\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Floor, // Toward negative infinity\n        Ceil, // Toward positive infinity\n        Trunc, // Toward zero\n        Expand // Away from zero\n    }\n\n    /**\n     * @dev Return the 512-bit addition of two uint256.\n     *\n     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.\n     */\n    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        assembly (\"memory-safe\") {\n            low := add(a, b)\n            high := lt(low, a)\n        }\n    }\n\n    /**\n     * @dev Return the 512-bit multiplication of two uint256.\n     *\n     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.\n     */\n    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {\n        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use\n        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n        // variables such that product = high * 2²⁵⁶ + low.\n        assembly (\"memory-safe\") {\n            let mm := mulmod(a, b, not(0))\n            low := mul(a, b)\n            high := sub(sub(mm, low), lt(mm, low))\n        }\n    }\n\n    /**\n     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a + b;\n            success = c >= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).\n     */\n    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a - b;\n            success = c <= a;\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).\n     */\n    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            uint256 c = a * b;\n            assembly (\"memory-safe\") {\n                // Only true when the multiplication doesn't overflow\n                // (c / a == b) || (a == 0)\n                success := or(eq(div(c, a), b), iszero(a))\n            }\n            // equivalent to: success ? c : 0\n            result = c * SafeCast.toUint(success);\n        }\n    }\n\n    /**\n     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `DIV` opcode returns zero when the denominator is 0.\n                result := div(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).\n     */\n    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {\n        unchecked {\n            success = b > 0;\n            assembly (\"memory-safe\") {\n                // The `MOD` opcode returns zero when the denominator is 0.\n                result := mod(a, b)\n            }\n        }\n    }\n\n    /**\n     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryAdd(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.\n     */\n    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {\n        (, uint256 result) = trySub(a, b);\n        return result;\n    }\n\n    /**\n     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.\n     */\n    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {\n        (bool success, uint256 result) = tryMul(a, b);\n        return ternary(success, result, type(uint256).max);\n    }\n\n    /**\n     * @dev Branchless ternary evaluation for `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            (uint256 high, uint256 low) = mul512(x, y);\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (high == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return low / denominator;\n            }\n\n            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.\n            if (denominator <= high) {\n                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));\n            }\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [high low].\n            uint256 remainder;\n            assembly (\"memory-safe\") {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                high := sub(high, gt(remainder, low))\n                low := sub(low, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.\n            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.\n\n            uint256 twos = denominator & (0 - denominator);\n            assembly (\"memory-safe\") {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [high low] by twos.\n                low := div(low, twos)\n\n                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from high into low.\n            low |= high * twos;\n\n            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such\n            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also\n            // works in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶\n            inverse *= 2 - denominator * inverse; // inverse mod 2³²\n            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴\n            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸\n            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is\n            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high\n            // is no longer required.\n            result = low * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);\n    }\n\n    /**\n     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {\n        unchecked {\n            (uint256 high, uint256 low) = mul512(x, y);\n            if (high >= 1 << n) {\n                Panic.panic(Panic.UNDER_OVERFLOW);\n            }\n            return (high << (256 - n)) | (low >> n);\n        }\n    }\n\n    /**\n     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.\n     */\n    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {\n        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);\n    }\n\n    /**\n     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.\n     *\n     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.\n     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.\n     *\n     * If the input value is not inversible, 0 is returned.\n     *\n     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the\n     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.\n     */\n    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {\n        unchecked {\n            if (n == 0) return 0;\n\n            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)\n            // Used to compute integers x and y such that: ax + ny = gcd(a, n).\n            // When the gcd is 1, then the inverse of a modulo n exists and it's x.\n            // ax + ny = 1\n            // ax = 1 + (-y)n\n            // ax ≡ 1 (mod n) # x is the inverse of a modulo n\n\n            // If the remainder is 0 the gcd is n right away.\n            uint256 remainder = a % n;\n            uint256 gcd = n;\n\n            // Therefore the initial coefficients are:\n            // ax + ny = gcd(a, n) = n\n            // 0a + 1n = n\n            int256 x = 0;\n            int256 y = 1;\n\n            while (remainder != 0) {\n                uint256 quotient = gcd / remainder;\n\n                (gcd, remainder) = (\n                    // The old remainder is the next gcd to try.\n                    remainder,\n                    // Compute the next remainder.\n                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd\n                    // where gcd is at most n (capped to type(uint256).max)\n                    gcd - remainder * quotient\n                );\n\n                (x, y) = (\n                    // Increment the coefficient of a.\n                    y,\n                    // Decrement the coefficient of n.\n                    // Can overflow, but the result is casted to uint256 so that the\n                    // next value of y is \"wrapped around\" to a value between 0 and n - 1.\n                    x - y * int256(quotient)\n                );\n            }\n\n            if (gcd != 1) return 0; // No inverse exists.\n            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.\n        }\n    }\n\n    /**\n     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.\n     *\n     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is\n     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that\n     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.\n     *\n     * NOTE: this function does NOT check that `p` is a prime greater than `2`.\n     */\n    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {\n        unchecked {\n            return Math.modExp(a, p - 2, p);\n        }\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)\n     *\n     * Requirements:\n     * - modulus can't be zero\n     * - underlying staticcall to precompile must succeed\n     *\n     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make\n     * sure the chain you're using it on supports the precompiled contract for modular exponentiation\n     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,\n     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly\n     * interpreted as 0.\n     */\n    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {\n        (bool success, uint256 result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).\n     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying\n     * to operate modulo 0 or if the underlying precompile reverted.\n     *\n     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain\n     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in\n     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack\n     * of a revert, but the result may be incorrectly interpreted as 0.\n     */\n    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {\n        if (m == 0) return (false, 0);\n        assembly (\"memory-safe\") {\n            let ptr := mload(0x40)\n            // | Offset    | Content    | Content (Hex)                                                      |\n            // |-----------|------------|--------------------------------------------------------------------|\n            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |\n            // | 0x60:0x7f | value of b | 0x<.............................................................b> |\n            // | 0x80:0x9f | value of e | 0x<.............................................................e> |\n            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |\n            mstore(ptr, 0x20)\n            mstore(add(ptr, 0x20), 0x20)\n            mstore(add(ptr, 0x40), 0x20)\n            mstore(add(ptr, 0x60), b)\n            mstore(add(ptr, 0x80), e)\n            mstore(add(ptr, 0xa0), m)\n\n            // Given the result < m, it's guaranteed to fit in 32 bytes,\n            // so we can use the memory scratch space located at offset 0.\n            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)\n            result := mload(0x00)\n        }\n    }\n\n    /**\n     * @dev Variant of {modExp} that supports inputs of arbitrary length.\n     */\n    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {\n        (bool success, bytes memory result) = tryModExp(b, e, m);\n        if (!success) {\n            Panic.panic(Panic.DIVISION_BY_ZERO);\n        }\n        return result;\n    }\n\n    /**\n     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.\n     */\n    function tryModExp(\n        bytes memory b,\n        bytes memory e,\n        bytes memory m\n    ) internal view returns (bool success, bytes memory result) {\n        if (_zeroBytes(m)) return (false, new bytes(0));\n\n        uint256 mLen = m.length;\n\n        // Encode call args in result and move the free memory pointer\n        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);\n\n        assembly (\"memory-safe\") {\n            let dataPtr := add(result, 0x20)\n            // Write result on top of args to avoid allocating extra memory.\n            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)\n            // Overwrite the length.\n            // result.length > returndatasize() is guaranteed because returndatasize() == m.length\n            mstore(result, mLen)\n            // Set the memory pointer after the returned data.\n            mstore(0x40, add(dataPtr, mLen))\n        }\n    }\n\n    /**\n     * @dev Returns whether the provided byte array is zero.\n     */\n    function _zeroBytes(bytes memory 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 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // If upper 8 bits of 16-bit half set, add 8 to result\n        r |= SafeCast.toUint((x >> r) > 0xff) << 3;\n        // If upper 4 bits of 8-bit half set, add 4 to result\n        r |= SafeCast.toUint((x >> r) > 0xf) << 2;\n\n        // Shifts value right by the current result and use it as an index into this lookup table:\n        //\n        // | x (4 bits) |  index  | table[index] = MSB position |\n        // |------------|---------|-----------------------------|\n        // |    0000    |    0    |        table[0] = 0         |\n        // |    0001    |    1    |        table[1] = 0         |\n        // |    0010    |    2    |        table[2] = 1         |\n        // |    0011    |    3    |        table[3] = 1         |\n        // |    0100    |    4    |        table[4] = 2         |\n        // |    0101    |    5    |        table[5] = 2         |\n        // |    0110    |    6    |        table[6] = 2         |\n        // |    0111    |    7    |        table[7] = 2         |\n        // |    1000    |    8    |        table[8] = 3         |\n        // |    1001    |    9    |        table[9] = 3         |\n        // |    1010    |   10    |        table[10] = 3        |\n        // |    1011    |   11    |        table[11] = 3        |\n        // |    1100    |   12    |        table[12] = 3        |\n        // |    1101    |   13    |        table[13] = 3        |\n        // |    1110    |   14    |        table[14] = 3        |\n        // |    1111    |   15    |        table[15] = 3        |\n        //\n        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.\n        assembly (\"memory-safe\") {\n            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256 of a positive value rounded towards zero.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 x) internal pure returns (uint256 r) {\n        // If value has upper 128 bits set, log2 result is at least 128\n        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;\n        // If upper 64 bits of 128-bit half set, add 64 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;\n        // If upper 32 bits of 64-bit half set, add 32 to result\n        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;\n        // If upper 16 bits of 32-bit half set, add 16 to result\n        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;\n        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8\n        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);\n        }\n    }\n\n    /**\n     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.\n     */\n    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {\n        return uint8(rounding) % 2 == 1;\n    }\n}\n"},"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/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"},"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"}},"matchId":"51024400","creationMatch":"exact_match","runtimeMatch":"exact_match","verifiedAt":"2026-09-15T01:36:19Z","match":"exact_match","chainId":"8453","address":"0x5B1c7180C630d3B2b6782Df70f43aE5Ea80425ba"}