Skip to content
Verified contractPartialBUSL-1.1

PrincipalTokenModule

Address0xa5944d594635ff1533b8fb26d961573d47110306
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,420,632
Creation transaction
0xab7749b5bb…8f81fa25b9
Libraries
src/router/modules/PrincipalTokenModule.sol:LibPreviewCommandsManagerModule0x78f3…801c82

31 files

src/router/modules/PrincipalTokenModule.sol

/// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import {SafeERC20, IERC20} from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC4626} from "openzeppelin-contracts/interfaces/IERC4626.sol";
import {Constants} from "src/router/Constants.sol";
import {IPrincipalToken} from "core-v2/src/interfaces/IPrincipalToken.sol";
import {LibExecutionModule} from "diamond-router/src/modules/libraries/LibExecutionModule.sol";
import {LibPreviewCommandsManagerModule} from "src/router/modules/libraries/LibPreviewCommandsManagerModule.sol";
import {RouterCommandsUtilities} from "src/libraries/RouterCommandsUtilities.sol";
import {RouterUtil} from "src/router/util/RouterUtil.sol";
import {RayMath} from "core-v2/src/libraries/RayMath.sol";
import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {LibRegistryStorage} from "src/router/modules/libraries/LibRegistryStorage.sol";
import {IRegistry} from "core-v2/src/interfaces/IRegistry.sol";
import {IPrincipalTokenModule} from "src/router/modules/interfaces/IPrincipalTokenModule.sol";

/**
 * @title PrincipalTokenModule
 * @notice Handles Principal Token and IBT operations for the router
 */
contract PrincipalTokenModule is IPrincipalTokenModule {
    using SafeERC20 for IERC20;
    using Math for uint256;
    using RayMath for uint256;

    /**
     * @dev Deposits assets into IBT
     * @param ibt The address of the IBT
     * @param assets The amount of assets to deposit
     * @param recipient The address of the recipient
     */
    function depositAssetInIBT(address ibt, uint256 assets, address recipient) external payable {
        address asset = IERC4626(ibt).asset();
        assets = RouterCommandsUtilities._resolveTokenValue(asset, assets);
        recipient = RouterCommandsUtilities._resolveAddress(recipient);

        IERC20(asset).forceApprove(ibt, assets);
        IERC4626(ibt).deposit(assets, recipient);
        IERC20(asset).forceApprove(ibt, 0);
    }

    /**
     * @dev Deposits assets into PT
     * @param pt The address of the PT
     * @param assets The amount of assets to deposit
     * @param ptRecipient The address of the PT recipient
     * @param ytRecipient The address of the YT recipient
     * @param minShares The minimum amount of shares to receive
     */
    function depositAssetInPT(address pt, uint256 assets, address ptRecipient, address ytRecipient, uint256 minShares)
        external
        payable
    {
        address asset = IPrincipalToken(pt).underlying();
        assets = RouterCommandsUtilities._resolveTokenValue(asset, assets);
        ptRecipient = RouterCommandsUtilities._resolveAddress(ptRecipient);
        ytRecipient = RouterCommandsUtilities._resolveAddress(ytRecipient);
        bool isRegisteredPT = IRegistry(LibRegistryStorage.getRegistry()).isRegisteredPT(pt);
        if (isRegisteredPT) {
            RouterCommandsUtilities._ensureApproved(asset, pt, assets);
        } else {
            IERC20(asset).forceApprove(pt, assets);
        }
        IPrincipalToken(pt).deposit(assets, ptRecipient, ytRecipient, minShares);
        if (!isRegisteredPT) {
            IERC20(asset).forceApprove(pt, 0);
        }
    }

    /**
     * @dev Deposits IBT into PT
     * @param pt The address of the PT
     * @param ibts The amount of IBTs to deposit
     * @param ptRecipient The address of the PT recipient
     * @param ytRecipient The address of the YT recipient
     * @param minShares The minimum amount of shares to receive
     */
    function depositIBTInPT(address pt, uint256 ibts, address ptRecipient, address ytRecipient, uint256 minShares)
        external
        payable
    {
        address ibt = IPrincipalToken(pt).getIBT();
        ibts = RouterCommandsUtilities._resolveTokenValue(ibt, ibts);
        ptRecipient = RouterCommandsUtilities._resolveAddress(ptRecipient);
        ytRecipient = RouterCommandsUtilities._resolveAddress(ytRecipient);
        bool isRegisteredPT = IRegistry(LibRegistryStorage.getRegistry()).isRegisteredPT(pt);
        if (isRegisteredPT) {
            RouterCommandsUtilities._ensureApproved(ibt, pt, ibts);
        } else {
            IERC20(ibt).forceApprove(pt, ibts);
        }
        IPrincipalToken(pt).depositIBT(ibts, ptRecipient, ytRecipient, minShares);
        if (!isRegisteredPT) {
            IERC20(ibt).forceApprove(pt, 0);
        }
    }

    /**
     * @dev Redeems IBT for underlying assets
     * @param ibt The address of the IBT
     * @param shares The amount of shares to redeem
     * @param recipient The address of the recipient
     */
    function redeemIBTForAsset(address ibt, uint256 shares, address recipient) external payable {
        shares = RouterCommandsUtilities._resolveTokenValue(ibt, shares);
        recipient = RouterCommandsUtilities._resolveAddress(recipient);

        IERC4626(ibt).redeem(shares, recipient, address(this));
    }

    /**
     * @dev Redeems PT for underlying assets
     * @param pt The address of the PT
     * @param shares The amount of shares to redeem
     * @param recipient The address of the recipient
     * @param minOut The minimum amount of assets to receive
     */
    function redeemPTForAsset(address pt, uint256 shares, address recipient, uint256 minOut) external payable {
        shares = RouterCommandsUtilities._resolveTokenValue(pt, shares);
        recipient = RouterCommandsUtilities._resolveAddress(recipient);
        uint256 redeemShares = block.timestamp < IPrincipalToken(pt).maturity()
            ? Math.min(shares, IERC20(IPrincipalToken(pt).getYT()).balanceOf(address(this)))
            : shares;
        IPrincipalToken(pt).redeem(redeemShares, recipient, address(this), minOut);
    }

    /**
     * @dev Redeems PT for IBT
     * @param pt The address of the PT
     * @param shares The amount of shares to redeem
     * @param recipient The address of the recipient
     * @param minOut The minimum amount of IBTs to receive
     */
    function redeemPTForIBT(address pt, uint256 shares, address recipient, uint256 minOut) external payable {
        recipient = RouterCommandsUtilities._resolveAddress(recipient);
        shares = RouterCommandsUtilities._resolveTokenValue(pt, shares);
        uint256 redeemShares = block.timestamp < IPrincipalToken(pt).maturity()
            ? Math.min(shares, IERC20(IPrincipalToken(pt).getYT()).balanceOf(address(this)))
            : shares;
        IPrincipalToken(pt).redeemForIBT(redeemShares, recipient, address(this), minOut);
    }

    //PREVIEW COMMANDS

    // Common helper function to calculate exchange rate
    function _calculateExchangeRate(
        uint256 inputAmount,
        uint256 outputAmount,
        address outputToken,
        address recipient,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) internal view returns (uint256) {
        recipient = RouterCommandsUtilities._resolveAddress(recipient);
        if (recipient == address(this)) {
            RouterCommandsUtilities._increasePreviewTokenValue(outputAmount, outputToken, balances);
        }
        // rate : outputAmount * rayUnit / inputAmount
        return outputAmount.mulDiv(RayMath.RAY_UNIT, inputAmount);
    }

    // View function for DEPOSIT_ASSET_IN_IBT command
    function previewDepositAssetInIBT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory) {
        // Decode the input parameters
        (address ibt, uint256 assets, address recipient) = abi.decode(_inputs, (address, uint256, address));

        address asset = IERC4626(ibt).asset();

        if (_spot) {
            assets = RouterUtil(LibPreviewCommandsManagerModule.getRouterUtil()).getUnit(asset);
        } else {
            assets = RouterCommandsUtilities._decreasePreviewTokenValue(assets, asset, balances);
        }

        uint256 _expectedShares = IERC4626(ibt).previewDeposit(assets);

        return (_calculateExchangeRate(assets, _expectedShares, ibt, recipient, balances), balances);
    }

    // View function for DEPOSIT_ASSET_IN_PT command
    function previewDepositAssetInPT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory) {
        // Decode the input parameters
        (address pt, uint256 assets, address ptRecipient, address ytRecipient) =
            abi.decode(_inputs, (address, uint256, address, address));

        if (_spot) {
            assets = RouterUtil(LibPreviewCommandsManagerModule.getRouterUtil()).getPTUnderlyingUnit(pt);
        } else {
            assets =
                RouterCommandsUtilities._decreasePreviewTokenValue(assets, IPrincipalToken(pt).underlying(), balances);
        }

        uint256 _expectedShares = IPrincipalToken(pt).previewDeposit(assets);

        ptRecipient = RouterCommandsUtilities._resolveAddress(ptRecipient);
        if (ptRecipient == address(this)) {
            RouterCommandsUtilities._increasePreviewTokenValue(_expectedShares, pt, balances);
        }

        ytRecipient = RouterCommandsUtilities._resolveAddress(ytRecipient);
        if (ytRecipient == address(this)) {
            RouterCommandsUtilities._increasePreviewTokenValue(_expectedShares, IPrincipalToken(pt).getYT(), balances);
        }

        // rate : shares * rayUnit / assets
        return (_expectedShares.mulDiv(RayMath.RAY_UNIT, assets), balances);
    }

    function previewDepositIBTInPT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory) {
        // Decode the input parameters
        (address pt, uint256 ibts, address ptRecipient, address ytRecipient) =
            abi.decode(_inputs, (address, uint256, address, address));

        if (_spot) {
            ibts = RouterUtil(LibPreviewCommandsManagerModule.getRouterUtil()).getUnit(pt);
        } else {
            ibts = RouterCommandsUtilities._decreasePreviewTokenValue(ibts, IPrincipalToken(pt).getIBT(), balances);
        }

        uint256 _expectedShares = IPrincipalToken(pt).previewDepositIBT(ibts);

        ptRecipient = RouterCommandsUtilities._resolveAddress(ptRecipient);
        if (ptRecipient == address(this)) {
            RouterCommandsUtilities._increasePreviewTokenValue(_expectedShares, pt, balances);
        }

        ytRecipient = RouterCommandsUtilities._resolveAddress(ytRecipient);
        if (ytRecipient == address(this)) {
            RouterCommandsUtilities._increasePreviewTokenValue(_expectedShares, IPrincipalToken(pt).getYT(), balances);
        }

        // rate : shares * rayUnit / ibts
        return (_expectedShares.mulDiv(RayMath.RAY_UNIT, ibts), balances);
    }

    // View function for REDEEM_IBT_FOR_ASSET command
    function previewRedeemIBTForAsset(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory) {
        (address ibt, uint256 shares, address recipient) = abi.decode(_inputs, (address, uint256, address));

        if (_spot) {
            shares = RouterUtil(LibPreviewCommandsManagerModule.getRouterUtil()).getUnit(ibt);
        } else {
            shares = RouterCommandsUtilities._decreasePreviewTokenValue(shares, ibt, balances);
        }

        uint256 _expectedAssets = IERC4626(ibt).previewRedeem(shares);

        return (_calculateExchangeRate(shares, _expectedAssets, IERC4626(ibt).asset(), recipient, balances), balances);
    }

    function previewRedeemPTForAsset(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory) {
        // Decode the input parameters
        (address pt, uint256 shares, address recipient) = abi.decode(_inputs, (address, uint256, address));

        if (_spot) {
            shares = RouterUtil(LibPreviewCommandsManagerModule.getRouterUtil()).getUnit(pt);
        } else {
            shares = RouterCommandsUtilities._decreasePreviewTokenValue(shares, pt, balances);
            if (block.timestamp < IPrincipalToken(pt).maturity()) {
                RouterCommandsUtilities._decreasePreviewTokenValue(shares, IPrincipalToken(pt).getYT(), balances);
            }
        }

        uint256 _expectedAssets = IPrincipalToken(pt).previewRedeem(shares);

        return (
            _calculateExchangeRate(shares, _expectedAssets, IPrincipalToken(pt).underlying(), recipient, balances),
            balances
        );
    }

    // View function for REDEEM_PT_FOR_IBT command
    function previewRedeemPTForIBT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory) {
        // Decode the input parameters
        (address pt, uint256 shares, address recipient) = abi.decode(_inputs, (address, uint256, address));

        if (_spot) {
            shares = RouterUtil(LibPreviewCommandsManagerModule.getRouterUtil()).getUnit(pt);
        } else {
            shares = RouterCommandsUtilities._decreasePreviewTokenValue(shares, pt, balances);
            if (block.timestamp < IPrincipalToken(pt).maturity()) {
                RouterCommandsUtilities._decreasePreviewTokenValue(shares, IPrincipalToken(pt).getYT(), balances);
            }
        }

        uint256 _expectedIBTs = IPrincipalToken(pt).previewRedeemForIBT(shares);

        return
            (_calculateExchangeRate(shares, _expectedIBTs, IPrincipalToken(pt).getIBT(), recipient, balances), balances);
    }
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC3156FlashBorrower.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC3156FlashBorrower.sol)

pragma solidity >=0.5.0;

/**
 * @dev Interface of the ERC-3156 FlashBorrower, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 */
interface IERC3156FlashBorrower {
    /**
     * @dev Receive a flash loan.
     * @param initiator The initiator of the loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param fee The additional amount of tokens to repay.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
     */
    function onFlashLoan(
        address initiator,
        address token,
        uint256 amount,
        uint256 fee,
        bytes calldata data
    ) external returns (bytes32);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC3156FlashLender.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC3156FlashLender.sol)

pragma solidity >=0.5.0;

import {IERC3156FlashBorrower} from "./IERC3156FlashBorrower.sol";

/**
 * @dev Interface of the ERC-3156 FlashLender, as defined in
 * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
 */
interface IERC3156FlashLender {
    /**
     * @dev The amount of currency available to be lended.
     * @param token The loan currency.
     * @return The amount of `token` that can be borrowed.
     */
    function maxFlashLoan(address token) external view returns (uint256);

    /**
     * @dev The fee to be charged for a given loan.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @return The amount of `token` to be charged for the loan, on top of the returned principal.
     */
    function flashFee(address token, uint256 amount) external view returns (uint256);

    /**
     * @dev Initiate a flash loan.
     * @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
     * @param token The loan currency.
     * @param amount The amount of tokens lent.
     * @param data Arbitrary data structure, intended to contain user-defined parameters.
     */
    function flashLoan(
        IERC3156FlashBorrower receiver,
        address token,
        uint256 amount,
        bytes calldata data
    ) external returns (bool);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/interfaces/IERC4626.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (interfaces/IERC4626.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/token/ERC20/utils/SafeERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/utils/Panic.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0-rc.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * 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
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // 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).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}

dependencies/@openzeppelin-contracts-5.4.0-rc.1/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in an uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev An uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

dependencies/core-v2-staging/src/interfaces/ICurveNGPool.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface for Curve TwoCrypto-NG pool
 */
interface ICurveNGPool is IERC20Metadata {
    function coins(uint256 index) external view returns (address);

    function balances(uint256 index) external view returns (uint256);

    function A() external view returns (uint256);

    function gamma() external view returns (uint256);

    function D() external view returns (uint256);

    function token() external view returns (address);

    function price_scale() external view returns (uint256);

    function price_oracle() external view returns (uint256);

    function future_A_gamma_time() external view returns (uint256);

    function future_A_gamma() external view returns (uint256);

    function initial_A_gamma_time() external view returns (uint256);

    function initial_A_gamma() external view returns (uint256);

    function fee_gamma() external view returns (uint256);

    function mid_fee() external view returns (uint256);

    function out_fee() external view returns (uint256);

    function allowed_extra_profit() external view returns (uint256);

    function adjustment_step() external view returns (uint256);

    function admin_fee() external view returns (uint256);

    function ma_time() external view returns (uint256);

    function get_virtual_price() external view returns (uint256);

    function fee() external view returns (uint256);

    function get_dy(uint256 i, uint256 j, uint256 dx) external view returns (uint256);

    function get_dx(uint256 i, uint256 j, uint256 dy) external view returns (uint256);

    function last_prices() external view returns (uint256);

    function calc_token_amount(
        uint256[2] calldata amounts,
        bool deposit
    ) external view returns (uint256);

    function calc_withdraw_one_coin(
        uint256 _token_amount,
        uint256 i
    ) external view returns (uint256);

    function exchange(uint256 i, uint256 j, uint256 dx, uint256 min_dy) external returns (uint256);

    function exchange(
        uint256 i,
        uint256 j,
        uint256 dx,
        uint256 min_dy,
        address receiver
    ) external returns (uint256);

    function add_liquidity(
        uint256[2] calldata amounts,
        uint256 min_mint_amount
    ) external returns (uint256);

    function add_liquidity(
        uint256[2] calldata amounts,
        uint256 min_mint_amount,
        address receiver
    ) external returns (uint256);

    function remove_liquidity(uint256 amount, uint256[2] calldata min_amounts) external;

    function remove_liquidity(
        uint256 amount,
        uint256[2] calldata min_amounts,
        address receiver
    ) external;

    function remove_liquidity_one_coin(
        uint256 token_amount,
        uint256 i,
        uint256 min_amount
    ) external;

    function remove_liquidity_one_coin(
        uint256 token_amount,
        uint256 i,
        uint256 min_amount,
        address receiver
    ) external;
}

dependencies/core-v2-staging/src/interfaces/ICurvePool.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

/**
 * @dev Interface for Curve CryptoSwap pool
 */
interface ICurvePool {
    function coins(uint256 index) external view returns (address);

    function balances(uint256 index) external view returns (uint256);

    function A() external view returns (uint256);

    function gamma() external view returns (uint256);

    function D() external view returns (uint256);

    function token() external view returns (address);

    function price_scale() external view returns (uint256);

    function future_A_gamma_time() external view returns (uint256);

    function future_A_gamma() external view returns (uint256);

    function initial_A_gamma_time() external view returns (uint256);

    function initial_A_gamma() external view returns (uint256);

    function fee_gamma() external view returns (uint256);

    function mid_fee() external view returns (uint256);

    function out_fee() external view returns (uint256);

    function allowed_extra_profit() external view returns (uint256);

    function adjustment_step() external view returns (uint256);

    function admin_fee() external view returns (uint256);

    function ma_half_time() external view returns (uint256);

    function get_virtual_price() external view returns (uint256);

    function fee() external view returns (uint256);

    function get_dy(uint256 i, uint256 j, uint256 dx) external view returns (uint256);

    function last_prices() external view returns (uint256);

    function calc_token_amount(uint256[2] calldata amounts) external view returns (uint256);

    function calc_withdraw_one_coin(
        uint256 _token_amount,
        uint256 i
    ) external view returns (uint256);

    function exchange(
        uint256 i,
        uint256 j,
        uint256 dx,
        uint256 min_dy,
        bool use_eth,
        address receiver
    ) external returns (uint256);

    function add_liquidity(
        uint256[2] calldata amounts,
        uint256 min_mint_amount
    ) external returns (uint256);

    function add_liquidity(
        uint256[2] calldata amounts,
        uint256 min_mint_amount,
        bool use_eth,
        address receiver
    ) external returns (uint256);

    function remove_liquidity(uint256 amount, uint256[2] calldata min_amounts) external;

    function remove_liquidity(
        uint256 amount,
        uint256[2] calldata min_amounts,
        bool use_eth,
        address receiver
    ) external;

    function remove_liquidity_one_coin(
        uint256 token_amount,
        uint256 i,
        uint256 min_amount
    ) external;

    function remove_liquidity_one_coin(
        uint256 token_amount,
        uint256 i,
        uint256 min_amount,
        bool use_eth,
        address receiver
    ) external;
}

dependencies/core-v2-staging/src/interfaces/IPrincipalToken.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import "openzeppelin-contracts/interfaces/IERC20.sol";
import {IERC20Metadata} from "openzeppelin-contracts/interfaces/IERC20Metadata.sol";
import "openzeppelin-contracts/interfaces/IERC3156FlashLender.sol";

interface IPrincipalToken is IERC20, IERC20Metadata, IERC3156FlashLender {
    /* ERRORS
     *****************************************************************************************************************/

    error InvalidDecimals();
    error BeaconNotSet();
    error PTExpired();
    error PTNotExpired();
    error RateError();
    error AddressError();
    error UnauthorizedCaller();
    error RatesAtExpiryAlreadyStored();
    error ERC5143SlippageProtectionFailed();
    error InsufficientBalance();
    error FlashLoanExceedsMaxAmount();
    error FlashLoanCallbackFailed();
    error NoRewardsProxy();
    error ClaimRewardsFailed();

    /* Functions
     *****************************************************************************************************************/

    function initialize(address _ibt, uint256 _duration, address initialAuthority) external;

    /**
     * @notice Toggle Pause
     * @dev Should only be called in extraordinary situations by the admin of the contract
     */
    function pause() external;

    /**
     * @notice Toggle UnPause
     * @dev Should only be called in extraordinary situations by the admin of the contract
     */
    function unPause() external;

    /**
     * @notice Deposits amount of assets in the PT vault
     * @param assets The amount of assets being deposited
     * @param receiver The receiver address of the shares
     * @return shares The amount of shares minted (same amount for PT & yt)
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @notice Deposits amount of assets in the PT vault
     * @param assets The amount of assets being deposited
     * @param ptReceiver The receiver address of the PTs
     * @param ytReceiver the receiver address of the YTs
     * @return shares The amount of shares minted (same amount for PT & yt)
     */
    function deposit(
        uint256 assets,
        address ptReceiver,
        address ytReceiver
    ) external returns (uint256 shares);

    /**
     * @notice Deposits amount of assets with a lower bound on shares received
     * @param assets The amount of assets being deposited
     * @param ptReceiver The receiver address of the PTs
     * @param ytReceiver The receiver address of the YTs
     * @param minShares The minimum allowed shares from this deposit
     * @return shares The amount of shares actually minted to the receiver
     */
    function deposit(
        uint256 assets,
        address ptReceiver,
        address ytReceiver,
        uint256 minShares
    ) external returns (uint256 shares);

    /**
     * @notice Same as normal deposit but with IBTs
     * @param ibts The amount of IBT being deposited
     * @param receiver The receiver address of the shares
     * @return shares The amount of shares minted to the receiver
     */
    function depositIBT(uint256 ibts, address receiver) external returns (uint256 shares);

    /**
     * @notice Same as normal deposit but with IBTs
     * @param ibts The amount of IBT being deposited
     * @param ptReceiver The receiver address of the PTs
     * @param ytReceiver the receiver address of the YTs
     * @return shares The amount of shares minted to the receiver
     */
    function depositIBT(
        uint256 ibts,
        address ptReceiver,
        address ytReceiver
    ) external returns (uint256 shares);

    /**
     * @notice Same as normal deposit but with IBTs
     * @param ibts The amount of IBT being deposited
     * @param ptReceiver The receiver address of the PTs
     * @param ytReceiver The receiver address of the YTs
     * @param minShares The minimum allowed shares from this deposit
     * @return shares The amount of shares minted to the receiver
     */
    function depositIBT(
        uint256 ibts,
        address ptReceiver,
        address ytReceiver,
        uint256 minShares
    ) external returns (uint256 shares);

    /**
     * @notice Burns owner's shares (PTs and YTs before expiry, PTs after expiry)
     * and sends assets to receiver
     * @param shares The amount of shares to burn
     * @param receiver The address that will receive the assets
     * @param owner The owner of the shares
     * @return assets The actual amount of assets received for burning the shares
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 assets);

    /**
     * @notice Burns owner's shares (PTs and YTs before expiry, PTs after expiry)
     * and sends assets to receiver
     * @param shares The amount of shares to burn
     * @param receiver The address that will receive the assets
     * @param owner The owner of the shares
     * @param minAssets The minimum assets that should be returned to user
     * @return assets The actual amount of assets received for burning the shares
     */
    function redeem(
        uint256 shares,
        address receiver,
        address owner,
        uint256 minAssets
    ) external returns (uint256 assets);

    /**
     * @notice Burns owner's shares (PTs and YTs before expiry, PTs after expiry)
     * and sends IBTs to receiver
     * @param shares The amount of shares to burn
     * @param receiver The address that will receive the IBTs
     * @param owner The owner of the shares
     * @return ibts The actual amount of IBT received for burning the shares
     */
    function redeemForIBT(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (uint256 ibts);

    /**
     * @notice Burns owner's shares (PTs and YTs before expiry, PTs after expiry)
     * and sends IBTs to receiver
     * @param shares The amount of shares to burn
     * @param receiver The address that will receive the IBTs
     * @param owner The owner of the shares
     * @param minIbts The minimum IBTs that should be returned to user
     * @return ibts The actual amount of IBT received for burning the shares
     */
    function redeemForIBT(
        uint256 shares,
        address receiver,
        address owner,
        uint256 minIbts
    ) external returns (uint256 ibts);

    /**
     * @notice Burns owner's shares (before expiry : PTs and YTs) and sends assets to receiver
     * @param assets The amount of assets to be received
     * @param receiver The address that will receive the assets
     * @param owner The owner of the shares (PTs and YTs)
     * @return shares The actual amount of shares burnt for receiving the assets
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    /**
     * @notice Burns owner's shares (before expiry : PTs and YTs) and sends assets to receiver
     * @param assets The amount of assets to be received
     * @param receiver The address that will receive the assets
     * @param owner The owner of the shares (PTs and YTs)
     * @param maxShares The maximum shares allowed to be burnt
     * @return shares The actual amount of shares burnt for receiving the assets
     */
    function withdraw(
        uint256 assets,
        address receiver,
        address owner,
        uint256 maxShares
    ) external returns (uint256 shares);

    /**
     * @notice Burns owner's shares (before expiry : PTs and YTs) and sends IBTs to receiver
     * @param ibts The amount of IBT to be received
     * @param receiver The address that will receive the IBTs
     * @param owner The owner of the shares (PTs and YTs)
     * @return shares The actual amount of shares burnt for receiving the IBTs
     */
    function withdrawIBT(
        uint256 ibts,
        address receiver,
        address owner
    ) external returns (uint256 shares);

    /**
     * @notice Burns owner's shares (before expiry : PTs and YTs) and sends IBTs to receiver
     * @param ibts The amount of IBT to be received
     * @param receiver The address that will receive the IBTs
     * @param owner The owner of the shares (PTs and YTs)
     * @param maxShares The maximum shares allowed to be burnt
     * @return shares The actual amount of shares burnt for receiving the IBTs
     */
    function withdrawIBT(
        uint256 ibts,
        address receiver,
        address owner,
        uint256 maxShares
    ) external returns (uint256 shares);

    /**
     * @notice Updates _user's yield since last update
     * @param _user The user whose yield will be updated
     * @return updatedUserYieldInIBT The unclaimed yield of the user in IBT (not just the updated yield)
     */
    function updateYield(address _user) external returns (uint256 updatedUserYieldInIBT);

    /**
     * @notice Claims caller's unclaimed yield in asset
     * @param _receiver The receiver of yield
     * @param _minAssets The minimum amount of assets that should be received
     * @return yieldInAsset The amount of yield claimed in asset
     */
    function claimYield(
        address _receiver,
        uint256 _minAssets
    ) external returns (uint256 yieldInAsset);

    /**
     * @notice Claims caller's unclaimed yield in IBT
     * @param _receiver The receiver of yield
     * @param _minIBT The minimum amount of IBT that should be received
     * @return yieldInIBT The amount of yield claimed in IBT
     */
    function claimYieldInIBT(
        address _receiver,
        uint256 _minIBT
    ) external returns (uint256 yieldInIBT);

    /**
     * @notice Claims the collected ibt fees and redeems them to the fee collector
     * @return ibts The amount of IBTs sent to the fee collector
     */
    function claimFees() external returns (uint256 ibts);

    /**
     * @notice Updates yield of both sender and receiver of YTs
     * @param _from the sender of YTs
     * @param _to the receiver of YTs
     */
    function beforeYtTransfer(address _from, address _to) external;

    /**
     * Call the claimRewards function of the rewards contract
     * @param data The optional data to be passed to the rewards contract
     */
    function claimRewards(bytes memory data) external;

    /* SETTERS
     *****************************************************************************************************************/

    /**
     * @notice Stores PT and IBT rates at expiry. Ideally, it should be called the day of expiry
     */
    function storeRatesAtExpiry() external;

    /** Set a new Rewards Proxy
     * @param _rewardsProxy The address of the new reward proxy
     */
    function setRewardsProxy(address _rewardsProxy) external;

    /* GETTERS
     *****************************************************************************************************************/

    /**
     * @notice Returns the amount of shares minted for the theorical deposited amount of assets
     * @param assets The amount of assets deposited
     * @return The amount of shares minted
     */
    function previewDeposit(uint256 assets) external view returns (uint256);

    /**
     * @notice Returns the amount of shares minted for the theorical deposited amount of IBT
     * @param ibts The amount of IBT deposited
     * @return The amount of shares minted
     */
    function previewDepositIBT(uint256 ibts) external view returns (uint256);

    /**
     * @notice Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     * @param receiver The receiver of the shares
     * @return The maximum amount of assets that can be deposited
     */
    function maxDeposit(address receiver) external view returns (uint256);

    /**
     * @notice Returns the theorical amount of shares that need to be burnt to receive assets of underlying
     * @param assets The amount of assets to receive
     * @return The amount of shares burnt
     */
    function previewWithdraw(uint256 assets) external view returns (uint256);

    /**
     * @notice Returns the theorical amount of shares that need to be burnt to receive amount of IBT
     * @param ibts The amount of IBT to receive
     * @return The amount of shares burnt
     */
    function previewWithdrawIBT(uint256 ibts) external view returns (uint256);

    /**
     * @notice Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     * @param owner The owner of the Vault shares
     * @return The maximum amount of assets that can be withdrawn
     */
    function maxWithdraw(address owner) external view returns (uint256);

    /**
     * @notice Returns the maximum amount of the IBT that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     * @param owner The owner of the Vault shares
     * @return The maximum amount of IBT that can be withdrawn
     */
    function maxWithdrawIBT(address owner) external view returns (uint256);

    /**
     * @notice Returns the amount of assets received for the theorical amount of burnt shares
     * @param shares The amount of shares to burn
     * @return The amount of assets received
     */
    function previewRedeem(uint256 shares) external view returns (uint256);

    /**
     * @notice Returns the amount of IBT received for the theorical amount of burnt shares
     * @param shares The amount of shares to burn
     * @return The amount of IBT received
     */
    function previewRedeemForIBT(uint256 shares) external view returns (uint256);

    /**
     * @notice Returns the maximum amount of Vault shares that can be redeemed by the owner
     * @notice This function behaves differently before and after expiry. Before expiry an equal amount of PT and YT
     * needs to be burnt, while after expiry only PTs are burnt.
     * @param owner The owner of the shares
     * @return The maximum amount of shares that can be redeemed
     */
    function maxRedeem(address owner) external view returns (uint256);

    /**
     * Returns the total amount of the underlying asset that is owned by the Vault in the form of IBT.
     */
    function totalAssets() external view returns (uint256);

    /**
     * @notice Converts an underlying amount in principal. Equivalent to ERC-4626's convertToShares method.
     * @param underlyingAmount The amount of underlying (or assets) to convert
     * @return The resulting amount of principal (or shares)
     */
    function convertToPrincipal(uint256 underlyingAmount) external view returns (uint256);

    /**
     * @notice Converts a principal amount in underlying. Equivalent to ERC-4626's convertToAssets method.
     * @param principalAmount The amount of principal (or shares) to convert
     * @return The resulting amount of underlying (or assets)
     */
    function convertToUnderlying(uint256 principalAmount) external view returns (uint256);

    /**
     * @notice Returns whether or not the contract is paused.
     * @return true if the contract is paused, and false otherwise
     */
    function paused() external view returns (bool);

    /**
     * @notice Returns the unix timestamp (uint256) at which the PT contract expires
     * @return The unix timestamp (uint256) when PTs become redeemable
     */
    function maturity() external view returns (uint256);

    /**
     * @notice Returns the duration of the PT contract
     * @return The duration (in s) to expiry/maturity of the PT contract
     */
    function getDuration() external view returns (uint256);

    /**
     * @notice Returns the address of the underlying token (or asset). Equivalent to ERC-4626's asset method.
     * @return The address of the underlying token (or asset)
     */
    function underlying() external view returns (address);

    /**
     * @notice Returns the IBT address of the PT contract
     * @return ibt The address of the IBT
     */
    function getIBT() external view returns (address ibt);

    /**
     * @notice Returns the yt address of the PT contract
     * @return yt The address of the yt
     */
    function getYT() external view returns (address yt);

    /**
     * @notice Returns the current ibtRate
     * @return The current ibtRate
     */
    function getIBTRate() external view returns (uint256);

    /**
     * @notice Returns the current ptRate
     * @return The current ptRate
     */
    function getPTRate() external view returns (uint256);

    /**
     * @notice Returns 1 unit of IBT
     * @return The IBT unit
     */
    function getIBTUnit() external view returns (uint256);

    /**
     * @notice Get the unclaimed fees in IBT
     * @return The unclaimed fees in IBT
     */
    function getUnclaimedFeesInIBT() external view returns (uint256);

    /**
     * @notice Get the total collected fees in IBT (claimed and unclaimed)
     * @return The total fees in IBT
     */
    function getTotalFeesInIBT() external view returns (uint256);

    /**
     * @notice Get the tokenization fee of the PT
     * @return The tokenization fee
     */
    function getTokenizationFee() external view returns (uint256);

    /**
     * @notice Get the current IBT yield of the user
     * @param _user The address of the user to get the current yield from
     * @return The yield of the user in IBT
     */
    function getCurrentYieldOfUserInIBT(address _user) external view returns (uint256);
}

dependencies/core-v2-staging/src/interfaces/IRegistry.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

interface IRegistry {
    /* Errors
     *****************************************************************************************************************/
    error FeeGreaterThanMaxValue();
    error PTListUpdateFailed();
    error ReductionTooBig();
    error AddressError();

    /* GETTERS
     *****************************************************************************************************************/

    /**
     * @notice Getter for the factory address
     * @return The address of token factory
     */
    function getFactory() external view returns (address);

    /**
     * @notice Get the address of the router
     * @return The address of the router
     */
    function getRouter() external view returns (address);

    /**
     * @notice Get the address of the routerUtil
     * @return The address of the routerUtil
     */
    function getRouterUtil() external view returns (address);

    /**
     * @notice Get the address of the pt beacon
     * @return The address of PT beacon
     */
    function getPTBeacon() external view returns (address);

    /**
     * @notice Get the address of the yt beacon
     * @return The address of yt beacon
     */
    function getYTBeacon() external view returns (address);

    /**
     * @notice Get the value of tokenization fee
     * @return The value of tokenization fee
     */
    function getTokenizationFee() external view returns (uint256);

    /**
     * @notice Get the value of yield fee
     * @return The value of yield fee
     */
    function getYieldFee() external view returns (uint256);

    /**
     * @notice Get the value of limit order fee
     * @return The value of limit order fee
     */
    function getLimitOrderFee() external view returns (uint256);

    /**
     * @notice Get the value of PT flash loan fee
     * @return The value of PT flash loan fee
     */
    function getPTFlashLoanFee() external view returns (uint256);

    /**
     * @notice Get the address of the fee collector
     * @return The address of fee collector
     */
    function getFeeCollector() external view returns (address);

    /**
     * @notice Get the fee reduction of the given user for the given pt
     * @param _pt The address of the pt
     * @param _user The address of the user
     * @return The fee reduction of the given user for the given pt
     */
    function getFeeReduction(address _pt, address _user) external view returns (uint256);

    /**
     * @notice Getter to check if a pt is registered
     * @param _pt the address of the pt to check the registration of
     * @return true if it is, false otherwise
     */
    function isRegisteredPT(address _pt) external view returns (bool);

    /**
     * @notice Getter for the pt registered at an index
     * @param _index the index of the pt to return
     * @return The address of the corresponding pt
     */
    function getPTAt(uint256 _index) external view returns (address);

    /**
     * @notice Getter for number of PT registered
     * @return The number of PT registered
     */
    function pTCount() external view returns (uint256);

    /* SETTERS
     *****************************************************************************************************************/

    /**
     * @notice Setter for the tokens factory address
     * @param _newFactory The address of the new factory
     */
    function setFactory(address _newFactory) external;

    /**
     * @notice set the router
     * @param _router The address of the router
     */
    function setRouter(address _router) external;

    /**
     * @notice set the routerUtil
     * @param _routerUtil The address of the routerUtil
     */
    function setRouterUtil(address _routerUtil) external;

    /**
     * @notice set the tokenization fee
     * @param _tokenizationFee The value of tokenization fee
     */
    function setTokenizationFee(uint256 _tokenizationFee) external;

    /**
     * @notice set the yield fee
     * @param _yieldFee The value of yield fee
     */
    function setYieldFee(uint256 _yieldFee) external;

    /**
     * @notice set the limit order fee
     * @param _limitOrderFee The value of limit order fee
     */
    function setLimitOrderFee(uint256 _limitOrderFee) external;

    /**
     * @notice set the PT flash loan fee
     * @param _ptFlashLoanFee The value of PT flash loan fee
     */
    function setPTFlashLoanFee(uint256 _ptFlashLoanFee) external;

    /**
     * @notice set the fee collector
     * @param _feeCollector The address of fee collector
     */
    function setFeeCollector(address _feeCollector) external;

    /**
     * @notice Set the fee reduction of the given pt for the given user
     * @param _pt The address of the pt
     * @param _user The address of the user
     * @param _reduction The fee reduction
     */
    function reduceFee(address _pt, address _user, uint256 _reduction) external;

    /**
     * @notice set the pt beacon
     * @param _ptBeacon The address of PT beacon
     */
    function setPTBeacon(address _ptBeacon) external;

    /**
     * @notice set the yt beacon
     * @param _ytBeacon The address of yt beacon
     */
    function setYTBeacon(address _ytBeacon) external;

    /**
     * @notice Add a pt to the registry
     * @param _pt The address of the pt to add to the registry
     */
    function addPT(address _pt) external;

    /**
     * @notice Remove a pt from the registry
     * @param _pt The address of the pt to remove from the registry
     */
    function removePT(address _pt) external;
}

dependencies/core-v2-staging/src/interfaces/IStableSwapNG.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;

interface IStableSwapNG {
    function A() external view returns (uint256);
    function A_precise() external view returns (uint256);
    function DOMAIN_SEPARATOR() external view returns (bytes32);
    function D_ma_time() external view returns (uint256);
    function D_oracle() external view returns (uint256);
    function N_COINS() external view returns (uint256);
    function add_liquidity(
        uint256[] memory _amounts,
        uint256 _min_mint_amount,
        address _receiver
    ) external returns (uint256);
    function admin_balances(uint256 arg0) external view returns (uint256);
    function admin_fee() external view returns (uint256);
    function allowance(address arg0, address arg1) external view returns (uint256);
    function approve(address _spender, uint256 _value) external returns (bool);
    function balanceOf(address arg0) external view returns (uint256);
    function balances(uint256 i) external view returns (uint256);
    function calc_token_amount(
        uint256[] memory _amounts,
        bool _is_deposit
    ) external view returns (uint256);
    function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256);
    function coins(uint256 arg0) external view returns (address);
    function decimals() external view returns (uint8);
    function dynamic_fee(int128 i, int128 j) external view returns (uint256);
    function ema_price(uint256 i) external view returns (uint256);
    function exchange(int128 i, int128 j, uint256 _dx, uint256 _min_dy) external returns (uint256);
    function exchange(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy,
        address _receiver
    ) external returns (uint256);
    function exchange_received(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy
    ) external returns (uint256);
    function exchange_received(
        int128 i,
        int128 j,
        uint256 _dx,
        uint256 _min_dy,
        address _receiver
    ) external returns (uint256);
    function fee() external view returns (uint256);
    function future_A() external view returns (uint256);
    function future_A_time() external view returns (uint256);
    function get_balances() external view returns (uint256[] memory);
    function get_dx(int128 i, int128 j, uint256 dy) external view returns (uint256);
    function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
    function get_p(uint256 i) external view returns (uint256);
    function get_virtual_price() external view returns (uint256);
    function initial_A() external view returns (uint256);
    function initial_A_time() external view returns (uint256);
    function last_price(uint256 i) external view returns (uint256);
    function ma_exp_time() external view returns (uint256);
    function ma_last_time() external view returns (uint256);
    function name() external view returns (string memory);
    function nonces(address arg0) external view returns (uint256);
    function offpeg_fee_multiplier() external view returns (uint256);
    function permit(
        address _owner,
        address _spender,
        uint256 _value,
        uint256 _deadline,
        uint8 _v,
        bytes32 _r,
        bytes32 _s
    ) external returns (bool);
    function price_oracle(uint256 i) external view returns (uint256);
    function ramp_A(uint256 _future_A, uint256 _future_time) external;
    function remove_liquidity(
        uint256 _burn_amount,
        uint256[] memory _min_amounts
    ) external returns (uint256[] memory);
    function remove_liquidity(
        uint256 _burn_amount,
        uint256[] memory _min_amounts,
        address _receiver
    ) external returns (uint256[] memory);
    function remove_liquidity(
        uint256 _burn_amount,
        uint256[] memory _min_amounts,
        address _receiver,
        bool _claim_admin_fees
    ) external returns (uint256[] memory);
    function remove_liquidity_imbalance(
        uint256[] memory _amounts,
        uint256 _max_burn_amount
    ) external returns (uint256);
    function remove_liquidity_imbalance(
        uint256[] memory _amounts,
        uint256 _max_burn_amount,
        address _receiver
    ) external returns (uint256);
    function remove_liquidity_one_coin(
        uint256 _burn_amount,
        int128 i,
        uint256 _min_received
    ) external returns (uint256);
    function remove_liquidity_one_coin(
        uint256 _burn_amount,
        int128 i,
        uint256 _min_received,
        address _receiver
    ) external returns (uint256);
    function salt() external view returns (bytes32);
    function set_ma_exp_time(uint256 _ma_exp_time, uint256 _D_ma_time) external;
    function set_new_fee(uint256 _new_fee, uint256 _new_offpeg_fee_multiplier) external;
    function stop_ramp_A() external;
    function stored_rates() external view returns (uint256[] memory);
    function symbol() external view returns (string memory);
    function totalSupply() external view returns (uint256);
    function transfer(address _to, uint256 _value) external returns (bool);
    function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
    function version() external view returns (string memory);
    function withdraw_admin_fees() external;
}

dependencies/core-v2-staging/src/libraries/CurvePoolUtil.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import "../interfaces/ICurvePool.sol";
import "../interfaces/ICurveNGPool.sol";
import "../interfaces/IStableSwapNG.sol";
import "../interfaces/IPrincipalToken.sol";
import "./RayMath.sol";
import "openzeppelin-contracts/utils/math/Math.sol";

/**
 * @title CurvePoolUtil library
 * @author Spectra Finance
 * @notice Provides miscellaneous utils for computations related to Curve CryptoSwap pools.
 */
library CurvePoolUtil {
    using Math for uint256;
    using RayMath for uint256;

    error SolutionNotFound();
    error FailedToFetchExpectedLPTokenAmount();
    error FailedToFetchExpectedCoinAmount();

    /// @notice Decimal precision used internally in the Curve AMM
    uint256 public constant CURVE_DECIMALS = 18;
    /// @notice Base unit for Curve AMM calculations
    uint256 public constant CURVE_UNIT = 1e18;
    /// @notice Make rounding errors favoring other LPs a tiny bit
    uint256 private constant APPROXIMATION_DECREMENT = 1;
    /// @notice Maximal number of iterations in the binary search algorithm
    uint256 private constant MAX_ITERATIONS_BINSEARCH = 255;

    /**
     * @notice Returns the expected LP token amount received for depositing given amounts of IBT and PT
     * @notice Method to be used with legacy Curve Cryptoswap pools
     * @param _curvePool The address of the Curve Pool in which liquidity will be deposited
     * @param _amounts Array containing the amounts of IBT and PT to deposit in the Curve Pool
     * @return minMintAmount The amount of expected LP tokens received for depositing the liquidity in the pool
     */
    function previewAddLiquidity(
        address _curvePool,
        uint256[2] memory _amounts
    ) external view returns (uint256 minMintAmount) {
        (bool success, bytes memory responseData) = _curvePool.staticcall(
            abi.encodeCall(ICurvePool(address(0)).calc_token_amount, (_amounts))
        );
        if (!success) {
            revert FailedToFetchExpectedLPTokenAmount();
        }
        minMintAmount = abi.decode(responseData, (uint256));
    }

    /**
     * @notice Returns the expected LP token amount received for depositing given amounts of IBT and PT
     * @notice Method to be used with legacy Curve Cryptoswap NG pools
     * @param _curvePool The address of the Curve Pool in which liquidity will be deposited
     * @param _amounts Array containing the amounts of IBT and PT to deposit in the Curve Pool
     * @return minMintAmount The amount of expected LP tokens received for depositing the liquidity in the pool
     */
    function previewAddLiquidityNG(
        address _curvePool,
        uint256[2] memory _amounts
    ) external view returns (uint256 minMintAmount) {
        (bool success, bytes memory responseData) = _curvePool.staticcall(
            abi.encodeCall(ICurveNGPool(address(0)).calc_token_amount, (_amounts, true))
        );
        if (!success) {
            revert FailedToFetchExpectedLPTokenAmount();
        }
        minMintAmount = abi.decode(responseData, (uint256));
    }

    /**
     * @notice Returns the expected LP token amount received for depositing given amounts of IBT and PT
     * @notice Method to be used with StableSwap NG pools
     * @param _curvePool The address of the Curve Pool in which liquidity will be deposited
     * @param _amounts Array containing the amounts of IBT and PT to deposit in the Curve Pool
     * @return minMintAmount The amount of expected LP tokens received for depositing the liquidity in the pool
     */
    function previewAddLiquiditySNG(
        address _curvePool,
        uint256[] memory _amounts
    ) external view returns (uint256 minMintAmount) {
        // @dev set the is_deposit to true
        (bool success, bytes memory responseData) = _curvePool.staticcall(
            abi.encodeCall(IStableSwapNG(address(0)).calc_token_amount, (_amounts, true))
        );
        if (!success) {
            revert FailedToFetchExpectedLPTokenAmount();
        }
        minMintAmount = abi.decode(responseData, (uint256));
    }

    /**
     * @notice Returns the IBT and PT amounts received for burning a given amount of LP tokens
     * @notice Method to be used with legacy Curve Cryptoswap pools
     * @param _curvePool The address of the curve pool
     * @param _lpTokenAmount The amount of the lp token to burn
     * @return minAmounts The expected respective amounts of IBT and PT withdrawn from the curve pool
     */
    function previewRemoveLiquidity(
        address _curvePool,
        uint256 _lpTokenAmount
    ) external view returns (uint256[2] memory minAmounts) {
        address lpToken = ICurvePool(_curvePool).token();
        uint256 totalSupply = IERC20(lpToken).totalSupply();
        (uint256 ibtBalance, uint256 ptBalance) = _getCurvePoolBalances(_curvePool);
        // decrement following what Curve is doing
        if (_lpTokenAmount > APPROXIMATION_DECREMENT && totalSupply != 0) {
            _lpTokenAmount -= APPROXIMATION_DECREMENT;
            minAmounts = [
                (ibtBalance * _lpTokenAmount) / totalSupply,
                (ptBalance * _lpTokenAmount) / totalSupply
            ];
        } else {
            minAmounts = [uint256(0), uint256(0)];
        }
    }

    /**
     * @notice Returns the IBT and PT amounts received for burning a given amount of LP tokens
     * @notice Method to be used with Curve Cryptoswap NG pools
     * @param _curvePool The address of the curve pool
     * @param _lpTokenAmount The amount of the lp token to burn
     * @return minAmounts The expected respective amounts of IBT and PT withdrawn from the curve pool
     */
    function previewRemoveLiquidityNG(
        address _curvePool,
        uint256 _lpTokenAmount
    ) external view returns (uint256[2] memory minAmounts) {
        uint256 totalSupply = ICurveNGPool(_curvePool).totalSupply();
        (uint256 ibtBalance, uint256 ptBalance) = _getCurvePoolBalances(_curvePool);
        // reproduces Curve implementation
        if (_lpTokenAmount == totalSupply) {
            minAmounts = [ibtBalance, ptBalance];
        } else if (_lpTokenAmount > APPROXIMATION_DECREMENT && totalSupply != 0) {
            _lpTokenAmount -= APPROXIMATION_DECREMENT;
            minAmounts = [
                ibtBalance.mulDiv(_lpTokenAmount, totalSupply),
                ptBalance.mulDiv(_lpTokenAmount, totalSupply)
            ];
        } else {
            minAmounts = [uint256(0), uint256(0)];
        }
    }

    /**
     * @notice Returns the IBT and PT amounts received for burning a given amount of LP tokens
     * @notice Method to be used with StableSwap NG pools
     * @param _curvePool The address of the curve pool
     * @param _lpTokenAmount The amount of the lp token to burn
     * @return minAmounts The expected respective amounts of IBT and PT withdrawn from the curve pool
     */
    function previewRemoveLiquiditySNG(
        address _curvePool,
        uint256 _lpTokenAmount
    ) external view returns (uint256[] memory) {
        uint256 totalSupply = IERC20(_curvePool).totalSupply();
        (uint256 ibtBalance, uint256 ptBalance) = _getCurvePoolBalances(_curvePool);
        // decrement following what Curve is doing
        uint256[] memory minAmounts = new uint256[](2);
        if (_lpTokenAmount > APPROXIMATION_DECREMENT && totalSupply != 0) {
            _lpTokenAmount -= APPROXIMATION_DECREMENT;
            minAmounts[0] = (ibtBalance * _lpTokenAmount) / totalSupply;
            minAmounts[1] = (ptBalance * _lpTokenAmount) / totalSupply;
        } else {
            minAmounts[0] = 0;
            minAmounts[1] = 0;
        }
        return minAmounts;
    }

    /**
     * @notice Returns the amount of coin i received for burning a given amount of LP tokens
     * @notice Method to be used with legacy Curve CryptoSwap pools
     * @param _curvePool The address of the curve pool
     * @param _lpTokenAmount The amount of the LP tokens to burn
     * @param _i The index of the unique coin to withdraw
     * @return minAmount The expected amount of coin i withdrawn from the curve pool
     */
    function previewRemoveLiquidityOneCoin(
        address _curvePool,
        uint256 _lpTokenAmount,
        uint256 _i
    ) external view returns (uint256 minAmount) {
        (bool success, bytes memory responseData) = _curvePool.staticcall(
            abi.encodeCall(ICurvePool(address(0)).calc_withdraw_one_coin, (_lpTokenAmount, _i))
        );
        if (!success) {
            revert FailedToFetchExpectedCoinAmount();
        }
        minAmount = abi.decode(responseData, (uint256));
    }

    /**
     * @notice Returns the amount of coin i received for burning a given amount of LP tokens
     * @notice Method to be used with Curve NG pools
     * @param _curvePool The address of the curve pool
     * @param _lpTokenAmount The amount of the LP tokens to burn
     * @param _i The index of the unique coin to withdraw
     * @return minAmount The expected amount of coin i withdrawn from the curve pool
     */
    function previewRemoveLiquidityOneCoinNG(
        address _curvePool,
        uint256 _lpTokenAmount,
        uint256 _i
    ) external view returns (uint256 minAmount) {
        (bool success, bytes memory responseData) = _curvePool.staticcall(
            abi.encodeCall(ICurveNGPool(address(0)).calc_withdraw_one_coin, (_lpTokenAmount, _i))
        );
        if (!success) {
            revert FailedToFetchExpectedCoinAmount();
        }
        minAmount = abi.decode(responseData, (uint256));
    }

    /**
     * @notice Returns the amount of coin i received for burning a given amount of LP tokens
     * @notice Method to be used with StableSwap NG pools
     * @param _curvePool The address of the curve pool
     * @param _lpTokenAmount The amount of the LP tokens to burn
     * @param _i The index of the unique coin to withdraw
     * @return minAmount The expected amount of coin i withdrawn from the curve pool
     */
    function previewRemoveLiquidityOneCoinSNG(
        address _curvePool,
        uint256 _lpTokenAmount,
        int128 _i
    ) external view returns (uint256 minAmount) {
        (bool success, bytes memory responseData) = _curvePool.staticcall(
            abi.encodeCall(IStableSwapNG(address(0)).calc_withdraw_one_coin, (_lpTokenAmount, _i))
        );
        if (!success) {
            revert FailedToFetchExpectedCoinAmount();
        }
        minAmount = abi.decode(responseData, (uint256));
    }

    /**
     * @notice Return the amount of IBT to deposit in the curve pool, given the total amount of IBT available for deposit
     * @param _amount The total amount of IBT available for deposit
     * @param _curvePool The address of the pool to deposit the amounts
     * @param _pt The address of the PT
     * @return ibts The amount of IBT which will be deposited in the curve pool
     */
    function calcIBTsToTokenizeForCurvePool(
        uint256 _amount,
        address _curvePool,
        address _pt
    ) external view returns (uint256 ibts) {
        (uint256 ibtBalance, uint256 ptBalance) = _getCurvePoolBalances(_curvePool);
        uint256 ibtBalanceInPT = IPrincipalToken(_pt).previewDepositIBT(ibtBalance);
        // Liquidity added in a ratio that (closely) matches the existing pool's ratio
        ibts = _amount.mulDiv(ptBalance, ibtBalanceInPT + ptBalance);
    }

    /**
     * @notice Return the amount of IBT to deposit in the curve pool given the proportion in which we want to deposit, given the total amount of IBT available for deposit
     * @param _amount The total amount of IBT available for deposit
     * @param _prop The proportion in which we want to make the deposit: _prop = nIBT / (nIBT + nPT)
     * @param _pt The address of the PT
     * @return ibts The amount of IBT which will be deposited in the curve pool
     */
    function calcIBTsToTokenizeForCurvePoolCustomProp(
        uint256 _amount,
        uint256 _prop,
        address _pt
    ) external view returns (uint256 ibts) {
        uint256 rate = IPrincipalToken(_pt).previewDepositIBT(_amount).mulDiv(CURVE_UNIT, _amount);
        ibts = _amount.mulDiv(CURVE_UNIT, CURVE_UNIT + _prop.mulDiv(rate, CURVE_UNIT));
    }

    /**
     * @param _curvePool : PT/IBT curve pool
     * @param _i token index
     * @param _j token index
     * @param _targetDy amount out desired
     * @return dx The amount of token to provide in order to obtain _targetDy after swap
     */
    function getDx(
        address _curvePool,
        uint256 _i,
        uint256 _j,
        uint256 _targetDy
    ) external view returns (uint256 dx) {
        // Initial guesses
        uint256 _minGuess = type(uint256).max;
        uint256 _maxGuess = type(uint256).max;
        uint256 _factor100;
        uint256 _guess = ICurvePool(_curvePool).get_dy(_i, _j, _targetDy);

        if (_guess > _targetDy) {
            _maxGuess = _targetDy;
            _factor100 = 10;
        } else {
            _minGuess = _targetDy;
            _factor100 = 1000;
        }
        uint256 loops;
        _guess = _targetDy;
        while (!_dxSolved(_curvePool, _i, _j, _guess, _targetDy, _minGuess, _maxGuess)) {
            loops++;

            (_minGuess, _maxGuess, _guess) = _runLoop(
                _minGuess,
                _maxGuess,
                _factor100,
                _guess,
                _targetDy,
                _curvePool,
                _i,
                _j
            );

            if (loops >= MAX_ITERATIONS_BINSEARCH) {
                revert SolutionNotFound();
            }
        }
        dx = _guess;
    }

    /**
     * @dev Runs bisection search
     * @param _minGuess lower bound on searched value
     * @param _maxGuess upper bound on searched value
     * @param _factor100 search interval scaling factor
     * @param _guess The previous guess for the `dx` value that is being refined through the search process
     * @param _targetDy The target output of the `get_dy` function, which the search aims to achieve by adjusting `dx`.
     * @param _curvePool PT/IBT curve pool
     * @param _i token index, either 0 or 1
     * @param _j token index, either 0 or 1, must be different than _i
     * @return The lower bound on _guess, upper bound on _guess and next _guess
     */
    function _runLoop(
        uint256 _minGuess,
        uint256 _maxGuess,
        uint256 _factor100,
        uint256 _guess,
        uint256 _targetDy,
        address _curvePool,
        uint256 _i,
        uint256 _j
    ) internal view returns (uint256, uint256, uint256) {
        if (_minGuess == type(uint256).max || _maxGuess == type(uint256).max) {
            _guess = (_guess * _factor100) / 100;
        } else {
            _guess = (_maxGuess + _minGuess) >> 1;
        }
        uint256 dy = ICurvePool(_curvePool).get_dy(_i, _j, _guess);
        if (dy < _targetDy) {
            _minGuess = _guess;
        } else if (dy > _targetDy) {
            _maxGuess = _guess;
        }
        return (_minGuess, _maxGuess, _guess);
    }

    /**
     * @dev Returns true if algorithm converged
     * @param _curvePool PT/IBT curve pool
     * @param _i token index, either 0 or 1
     * @param _j token index, either 0 or 1, must be different than _i
     * @param _dx The current guess for the `dx` value that is being refined through the search process.
     * @param _targetDy The target output of the `get_dy` function, which the search aims to achieve by adjusting `dx`.
     * @param _minGuess lower bound on searched value
     * @param _maxGuess upper bound on searched value
     * @return true if the solution to the search problem was found, false otherwise
     */
    function _dxSolved(
        address _curvePool,
        uint256 _i,
        uint256 _j,
        uint256 _dx,
        uint256 _targetDy,
        uint256 _minGuess,
        uint256 _maxGuess
    ) internal view returns (bool) {
        if (_minGuess == type(uint256).max || _maxGuess == type(uint256).max) {
            return false;
        }
        uint256 dy = ICurvePool(_curvePool).get_dy(_i, _j, _dx);
        if (dy == _targetDy) {
            return true;
        }
        uint256 dy1 = ICurvePool(_curvePool).get_dy(_i, _j, _dx + 1);
        if (dy < _targetDy && _targetDy < dy1) {
            return true;
        }
        return false;
    }

    /**
     * @notice Returns the balances of the two tokens in provided curve pool
     * @param _curvePool address of the curve pool
     * @return The IBT and PT balances of the curve pool
     */
    function _getCurvePoolBalances(address _curvePool) internal view returns (uint256, uint256) {
        return (ICurvePool(_curvePool).balances(0), ICurvePool(_curvePool).balances(1));
    }
}

dependencies/core-v2-staging/src/libraries/RayMath.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.20;

/**
 * @title RayMath library
 * @author Spectra Finance
 * @notice Provides conversions for/to any decimal tokens to/from ray.
 * @dev Conversions from Ray are rounded down.
 */
library RayMath {
    /// @dev 27 decimal unit
    uint256 public constant RAY_UNIT = 1e27;
    uint256 public constant RAY_DECIMALS = 27;

    /**
     * @dev Converts a value from Ray (27-decimal precision) to a representation with a specified number of decimals.
     * @param _a The amount in Ray to be converted. Ray is a fixed-point representation with 27 decimals.
     * @param _decimals The target decimal precision for the converted amount.
     * @return b The amount converted from Ray to the specified decimal precision.
     */
    function fromRay(uint256 _a, uint256 _decimals) internal pure returns (uint256 b) {
        uint256 decimals_ratio = 10 ** (RAY_DECIMALS - _decimals);
        assembly {
            b := div(_a, decimals_ratio)
        }
    }

    /**
     * @dev Converts a value from Ray (27-decimal precision) to a representation with a specified number of decimals.
     * @param _a The amount in Ray to be converted. Ray is a fixed-point representation with 27 decimals.
     * @param _decimals The target decimal precision for the converted amount.
     * @param _roundUp If true, the function rounds up the result to the nearest integer value.
     *                If false, it truncates (rounds down) to the nearest integer.
     * @return b The amount converted from Ray to the specified decimal precision, rounded as specified.
     */
    function fromRay(
        uint256 _a,
        uint256 _decimals,
        bool _roundUp
    ) internal pure returns (uint256 b) {
        uint256 decimals_ratio = 10 ** (RAY_DECIMALS - _decimals);
        assembly {
            b := div(_a, decimals_ratio)

            if and(eq(_roundUp, 1), gt(mod(_a, decimals_ratio), 0)) {
                b := add(b, 1)
            }
        }
    }

    /**
     * @dev Converts a value with a specified number of decimals to Ray (27-decimal precision).
     * @param _a The amount to be converted, specified in a decimal format.
     * @param _decimals The number of decimals in the representation of 'a'.
     * @return b The amount in Ray, converted from the specified decimal precision.
     *           Ensures that the conversion maintains the value's integrity (no overflow).
     */
    function toRay(uint256 _a, uint256 _decimals) internal pure returns (uint256 b) {
        uint256 decimals_ratio = 10 ** (RAY_DECIMALS - _decimals);
        // to avoid overflow, b/decimals_ratio == _a
        assembly {
            b := mul(_a, decimals_ratio)

            if iszero(eq(div(b, decimals_ratio), _a)) {
                revert(0, 0)
            }
        }
    }
}

dependencies/diamond-router-V1/src/interfaces/ICommand.sol

pragma solidity ^0.8.22;

interface ICommand {
        enum ImplementationAction {
        Add,
        Replace,
        Remove
    }
    // Add=0, Replace=1, Remove=2

    struct CommandModification {
        address implementation; // implementation address
        ImplementationAction action; // action to realize
        bytes commands; // command IDs to associate with function selectors
        bytes4[] functionSelectors; // one command is associated to one function selector
    }

    event CommandModifications(
        CommandModification[] _commandModifications, address _init, bytes _calldata
    );

}

dependencies/diamond-router-V1/src/modules/libraries/LibExecutionModule.sol

pragma solidity ^0.8.20;

library LibExecutionModule {
    // EIP-7201: keccak256(abi.encode(uint256(keccak256("native.execution.storage")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 constant EXECUTION_STORAGE_POSITION = keccak256(abi.encode(uint256(keccak256("native.execution.storage")) - 1)) & ~bytes32(uint256(0xff));

    struct ExecutionStorage {
        address msgSender;
        uint256 msgValue;
    }

    function executionStorage() internal pure returns (ExecutionStorage storage es) {
        bytes32 position = EXECUTION_STORAGE_POSITION;
        assembly {
            es.slot := position
        }
    }

    function getMsgSender() internal view returns(address) {
        return executionStorage().msgSender;
    }

    function getMsgValue() internal view returns(uint256) {
        return executionStorage().msgValue;
    }
}

src/libraries/RouterCommandsUtilities.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {RayMath} from "core-v2/src/libraries/RayMath.sol";
import {Constants} from "src/router/Constants.sol";
import {LibExecutionModule} from "diamond-router/src/modules/libraries/LibExecutionModule.sol";
import {SafeERC20, IERC20} from "openzeppelin-contracts/token/ERC20/utils/SafeERC20.sol";

/**
 * @title RouterCommandsUtilities
 * @author Spectra Finance
 * @notice Library of utility functions for preview commands
 */
library RouterCommandsUtilities {
    using Math for uint256;
    using RayMath for uint256;
    using SafeERC20 for IERC20;

    error AddressError();
    error BalanceUnderflow();
    error MaxInvolvedTokensExceeded();

    /**
     * @dev Maximum amount of tokens for which balance can be tracked in _previewRate().
     */
    uint256 internal constant MAX_INVOLVED_TOKENS = 30;

    // used for tracking balance changes in _previewRate
    struct TokenBalance {
        address token;
        uint256 balance;
    }

    /**
     * @dev Returns either the input address as is, or replaced with its corresponding behaviour in Constants.sol
     * @param _addr The address to resolve
     * @return resolved The resolved address
     */
    function _resolveAddress(address _addr) internal view returns (address resolved) {
        if (_addr == Constants.ADDRESS_THIS) {
            resolved = address(this);
        } else if (_addr == Constants.MSG_SENDER) {
            resolved = LibExecutionModule.executionStorage().msgSender;
        } else {
            resolved = _addr;
        }
        if (resolved == address(0)) revert AddressError();
    }

    /**
     * @dev Returns either the input token value as is, or replaced with its corresponding behaviour in Constants.sol
     * @param _token The address of the token
     * @param _value The token amount
     * @return The amount stored previously if current amount used for detecting contract balance, else current value
     */
    function _resolveTokenValue(address _token, uint256 _value) internal view returns (uint256) {
        return (_value == Constants.CONTRACT_BALANCE) ? IERC20(_token).balanceOf(address(this)) : _value;
    }

    /**
     * @dev Increase balance for given token by given value in provided balances array
     * @param _value The value to subtract from token balance
     * @param _token The token address
     * @param _balances The TokenBalance array
     * @return The token balance AFTER increase
     */
    function _increasePreviewTokenValue(uint256 _value, address _token, TokenBalance[] memory _balances)
        internal
        pure
        returns (uint256)
    {
        if (_token == address(0)) {
            revert AddressError();
        }
        uint256 _length = _balances.length;
        for (uint256 i = 0; i < _length; ++i) {
            if (_balances[i].token == address(0)) {
                _balances[i] = TokenBalance(_token, _value);
                return _value;
            } else if (_balances[i].token == _token) {
                _balances[i].balance += _value;
                return _balances[i].balance;
            }
        }
        revert MaxInvolvedTokensExceeded();
    }

    /**
     * @dev Decrease balance for given token by given value in provided balances array
     * @param _value The value to subtract from token balance
     * @param _token The token address
     * @param _balances The TokenBalance array
     * @return The actual value to subtract from token balance
     */
    function _decreasePreviewTokenValue(uint256 _value, address _token, TokenBalance[] memory _balances)
        internal
        pure
        returns (uint256)
    {
        if (_token == address(0)) {
            revert AddressError();
        }
        uint256 _length = _balances.length;
        for (uint256 i = 0; i < _length; ++i) {
            if (_balances[i].token == address(0)) {
                break;
            } else if (_balances[i].token == _token) {
                if (_value == Constants.CONTRACT_BALANCE) {
                    uint256 _res = _balances[i].balance;
                    _balances[i].balance = 0;
                    return _res;
                } else {
                    if (_balances[i].balance < _value) {
                        break;
                    }
                    _balances[i].balance -= _value;
                    return _value;
                }
            }
        }
        revert BalanceUnderflow();
    }

    /**
     * @dev Checks the allowance of a token and approves the spender if necessary
     * @param _token address of the token to be approved
     * @param _spender address of the spender
     * @param _value token amount
     */
    function _ensureApproved(address _token, address _spender, uint256 _value) internal {
        uint256 allowance = IERC20(_token).allowance(address(this), _spender);
        if (allowance < _value) {
            // This approval will only be executed the first time to save gas for subsequent operations
            IERC20(_token).forceApprove(_spender, type(uint256).max);
        }
    }
}

src/router/Constants.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

library Constants {
    /// @dev 18 decimal unit
    uint256 internal constant UNIT = 1e18;

    /// @dev identifier for native ETH
    address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /// @dev maximal number of iterations in the secant method algorithm
    uint256 internal constant MAX_ITERATIONS_SECANT = 255;

    /// @dev maximal number of iterations in the linear search following secant method algorithm
    uint256 internal constant MAX_ITERATIONS_LINEAR_SEARCH = 255;

    /// @dev determines the rate at which an input value is scaled in each iteration of linear search
    uint256 internal constant SCALING_FACTOR_LINEAR_SEARCH = 1e6;

    /// @dev precision divisor for the secant method
    uint256 internal constant PRECISION_DIVISOR = 1000;

    /// @dev Used for identifying cases when this contract's balance of a token is to be used as an input
    /// This value is equivalent to 1<<255, i.e. a singular 1 in the most significant bit.
    uint256 internal constant CONTRACT_BALANCE = 0x8000000000000000000000000000000000000000000000000000000000000000;

    /// @dev Used as a flag for identifying that msg.sender should be used, saves gas by sending more 0 bytes
    address internal constant MSG_SENDER = address(0xc0);

    /// @dev Used as a flag for identifying address(this) should be used, saves gas by sending more 0 bytes
    address internal constant ADDRESS_THIS = address(0xe0);
}

src/router/modules/interfaces/IPreviewCommandsModule.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import {LibPreviewCommandsManagerModule} from "src/router/modules/libraries/LibPreviewCommandsManagerModule.sol";
import {ICommand} from "diamond-router/src/interfaces/ICommand.sol";

/**
 * @title IPreviewCommandsModule
 * @author Spectra Finance
 * @notice Interface for the PreviewCommandsModule contract
 */
interface IPreviewCommandsModule is ICommand {
    event RouterUtilChange(address indexed previousRouterUtil, address indexed newRouterUtil);

    error EmptyAddress();
    error NotRouter();

    /**
     * @notice Add/replace/remove any number of functions and optionally execute
     *         a function with delegatecall
     * @param _commandsModifications Array of implementation addresses, actions, commands,
     *                                     and function selectors
     * @param _init The address of the contract or facet to execute _calldata
     * @param _calldata A function call executed with delegatecall on _init
     */
    function managePreviewCommands(
        CommandModification[] memory _commandsModifications,
        address _init,
        bytes memory _calldata
    ) external;

    /*
     * --------------------- Preview Execution ---------------------
    */

    /**
     * @dev Error thrown when length of inputs doesn't match length of commands
     */
    error LengthMismatch();

    /**
     * @dev Error thrown when an invalid command type is provided
     */
    error InvalidCommandType(uint256 command);

    /**
     * @dev Error thrown when a command is not found
     */
    error CommandNotFound(bytes1 command);

    /**
     * @dev Error thrown when a delegate call fails
     */
    error DelegateCallFailed();

    /**
     * @dev Struct to track token balances during preview operations
     */
    struct TokenBalance {
        address token;
        uint256 balance;
    }

    /**
     * @notice Gets the router util address from storage
     * @return The router util address
     */
    function getRouterUtil() external view returns (address);

    /**
     * @notice Sets the router util address
     * @param _routerUtil The new router util address
     */
    function setRouterUtil(address _routerUtil) external;

    /**
     * @dev Simulates the execution of a command and returns the expected resulting rate
     */
    function _dispatchPreviewRate(bytes memory _inputCallData) external returns (uint256 rate);

    /**
     * @dev Simulates the execution of a sequence of commands and returns the expected resulting rate
     * @param _commands Encoded instructions passed to the dispatcher
     * @param _inputs An array of byte strings containing ABI-encoded inputs for each command
     * @param _spot If true, spot exchange rates and unit amounts are used
     * @return The preview rate value representing final output/input ratio in ray units
     */
    function _previewRate(bytes calldata _commands, bytes[] calldata _inputs, bool _spot)
        external
        view
        returns (uint256);

    /**
     * @notice Previews the effective exchange rate including price impact and fees
     * @param _commands Encoded instructions passed to the dispatcher
     * @param _inputs An array of byte strings containing ABI-encoded inputs for each command
     * @return The effective exchange rate in ray units
     */
    function previewRate(bytes calldata _commands, bytes[] calldata _inputs) external view returns (uint256);

    /**
     * @notice Previews the spot exchange rate without price impact or fees
     * @param _commands Encoded instructions passed to the dispatcher
     * @param _inputs An array of byte strings containing ABI-encoded inputs for each command
     * @return The spot exchange rate in ray units
     */
    function previewSpotRate(bytes calldata _commands, bytes[] calldata _inputs) external view returns (uint256);
}

src/router/modules/interfaces/IPrincipalTokenModule.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {RouterCommandsUtilities} from "src/libraries/RouterCommandsUtilities.sol";

/**
 * @title IPrincipalTokenModule
 * @notice Interface for PrincipalTokenModule - handles Principal Token and IBT operations for the router
 */
interface IPrincipalTokenModule {
    /**
     * @notice Deposits assets into IBT
     * @param ibt The address of the IBT
     * @param assets The amount of assets to deposit
     * @param recipient The address of the recipient
     */
    function depositAssetInIBT(address ibt, uint256 assets, address recipient) external payable;

    /**
     * @notice Deposits assets into PT
     * @param pt The address of the PT
     * @param assets The amount of assets to deposit
     * @param ptRecipient The address of the PT recipient
     * @param ytRecipient The address of the YT recipient
     * @param minShares The minimum amount of shares to receive
     */
    function depositAssetInPT(address pt, uint256 assets, address ptRecipient, address ytRecipient, uint256 minShares)
        external
        payable;

    /**
     * @notice Deposits IBT into PT
     * @param pt The address of the PT
     * @param ibts The amount of IBTs to deposit
     * @param ptRecipient The address of the PT recipient
     * @param ytRecipient The address of the YT recipient
     * @param minShares The minimum amount of shares to receive
     */
    function depositIBTInPT(address pt, uint256 ibts, address ptRecipient, address ytRecipient, uint256 minShares)
        external
        payable;

    /**
     * @notice Redeems IBT for underlying assets
     * @param ibt The address of the IBT
     * @param shares The amount of shares to redeem
     * @param recipient The address of the recipient
     */
    function redeemIBTForAsset(address ibt, uint256 shares, address recipient) external payable;

    /**
     * @notice Redeems PT for underlying assets
     * @param pt The address of the PT
     * @param shares The amount of shares to redeem
     * @param recipient The address of the recipient
     * @param minOut The minimum amount of assets to receive
     */
    function redeemPTForAsset(address pt, uint256 shares, address recipient, uint256 minOut) external payable;

    /**
     * @notice Redeems PT for IBT
     * @param pt The address of the PT
     * @param shares The amount of shares to redeem
     * @param recipient The address of the recipient
     * @param minOut The minimum amount of IBTs to receive
     */
    function redeemPTForIBT(address pt, uint256 shares, address recipient, uint256 minOut) external payable;

    // PREVIEW FUNCTIONS

    /**
     * @notice Previews depositing assets into IBT
     * @param _inputs Encoded input parameters
     * @param _spot Whether to use spot pricing
     * @param balances Array of token balances
     * @return Exchange rate and updated balances
     */
    function previewDepositAssetInIBT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory);

    /**
     * @notice Previews depositing assets into PT
     * @param _inputs Encoded input parameters
     * @param _spot Whether to use spot pricing
     * @param balances Array of token balances
     * @return Exchange rate and updated balances
     */
    function previewDepositAssetInPT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory);

    /**
     * @notice Previews depositing IBT into PT
     * @param _inputs Encoded input parameters
     * @param _spot Whether to use spot pricing
     * @param balances Array of token balances
     * @return Exchange rate and updated balances
     */
    function previewDepositIBTInPT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory);

    /**
     * @notice Previews redeeming IBT for assets
     * @param _inputs Encoded input parameters
     * @param _spot Whether to use spot pricing
     * @param balances Array of token balances
     * @return Exchange rate and updated balances
     */
    function previewRedeemIBTForAsset(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory);

    /**
     * @notice Previews redeeming PT for assets
     * @param _inputs Encoded input parameters
     * @param _spot Whether to use spot pricing
     * @param balances Array of token balances
     * @return Exchange rate and updated balances
     */
    function previewRedeemPTForAsset(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory);

    /**
     * @notice Previews redeeming PT for IBT
     * @param _inputs Encoded input parameters
     * @param _spot Whether to use spot pricing
     * @param balances Array of token balances
     * @return Exchange rate and updated balances
     */
    function previewRedeemPTForIBT(
        bytes memory _inputs,
        bool _spot,
        RouterCommandsUtilities.TokenBalance[] memory balances
    ) external view returns (uint256, RouterCommandsUtilities.TokenBalance[] memory);
}

src/router/modules/libraries/LibPreviewCommandsManagerModule.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import {IPreviewCommandsModule, ICommand} from "src/router/modules/interfaces/IPreviewCommandsModule.sol";
import {RouterCommandsUtilities} from "src/libraries/RouterCommandsUtilities.sol";

/**
 * @title LibPreviewCommandsManagerModule
 * @author Spectra Finance
 * @notice Library for PreviewCommandsModule command storage management
 */
library LibPreviewCommandsManagerModule {
    // EIP-7201: keccak256(abi.encode(uint256(keccak256("spectra.manager.preview")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 constant PREVIEW_COMMANDS_STORAGE_POSITION =
        keccak256(abi.encode(uint256(keccak256("spectra.manager.preview")) - 1)) & ~bytes32(uint256(0xff));

    struct ImplementationAndFunction {
        address implementation;
        bytes4 functionSelector;
    }

    struct PreviewCommandsStorage {
        address routerUtil;
        // Map command byte to implementation address and function selector
        mapping(bytes1 => ImplementationAndFunction) implementationAndFunction;
        bytes1[] supportedCommands;
    }

    // Custom errors
    error MissmatchLength();
    error EmptyCommandList();
    error IncorrectManagementAction(uint8 action);
    error CannotAddSelectorsToZeroAddress(bytes4[] selectors);
    error CommandAlreadyRegistered(bytes1 command);
    error CannotReplaceFunctionsFromFacetWithZeroAddress(bytes4[] selectors);
    error CannotReplaceImmutableFunction(bytes4 selector);
    error CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet(bytes4 selector);
    error CannotReplaceFunctionThatDoesNotExists(bytes4 selector);
    error RemoveFacetAddressMustBeZeroAddress(address facetAddress);
    error CannotRemoveFunctionThatDoesNotExist(bytes4 selector);
    error CannotRemoveImmutableFunction(bytes4 selector);
    error InitializationFunctionReverted(address init, bytes callData);
    error NoBytecodeAtAddress(address contractAddress);

    // Events
    event CommandsModifications(ICommand.CommandModification[] _commandsModifications, address _init, bytes _calldata);

    event RouterUtilChange(address indexed previousRouterUtil, address indexed newRouterUtil);

    /**
     * @dev Get the storage struct for preview commands
     */
    function previewCommandsStorage() internal pure returns (PreviewCommandsStorage storage pcs) {
        bytes32 position = PREVIEW_COMMANDS_STORAGE_POSITION;
        assembly {
            pcs.slot := position
        }
    }

    function getRouterUtil() public view returns (address) {
        return previewCommandsStorage().routerUtil;
    }

    /**
     * @notice Sets the router util address in storage
     * @param _routerUtil The new router util address
     */
    function setRouterUtil(address _routerUtil) internal {
        emit RouterUtilChange(previewCommandsStorage().routerUtil, _routerUtil);
        previewCommandsStorage().routerUtil = _routerUtil;
    }

    function manageCommands(
        ICommand.CommandModification[] memory _commandsModifications,
        address _init,
        bytes memory _calldata
    ) internal {
        for (uint256 implementationIndex; implementationIndex < _commandsModifications.length; implementationIndex++) {
            bytes memory commands = _commandsModifications[implementationIndex].commands;
            bytes4[] memory selectors = _commandsModifications[implementationIndex].functionSelectors;
            address implementation = _commandsModifications[implementationIndex].implementation;
            if (commands.length != selectors.length) {
                revert MissmatchLength();
            }
            if (commands.length == 0) {
                revert EmptyCommandList();
            }
            ICommand.ImplementationAction action = _commandsModifications[implementationIndex].action;
            if (action == ICommand.ImplementationAction.Add) {
                addFunctions(implementation, commands, selectors);
            } else if (action == ICommand.ImplementationAction.Replace) {
                replaceFunctions(implementation, commands, selectors);
            } else if (action == ICommand.ImplementationAction.Remove) {
                removeFunctions(implementation, commands, selectors);
            } else {
                revert IncorrectManagementAction(uint8(action));
            }
        }
        emit CommandsModifications(_commandsModifications, _init, _calldata);
        initializeImplementation(_init, _calldata);
    }

    function addFunctions(address _implementationAddress, bytes memory _commands, bytes4[] memory _functionSelectors)
        internal
    {
        if (_implementationAddress == address(0)) {
            revert CannotAddSelectorsToZeroAddress(_functionSelectors);
        }
        PreviewCommandsStorage storage pcs = previewCommandsStorage();
        enforceHasContractCode(_implementationAddress);
        for (uint256 commandIndex; commandIndex < _commands.length; commandIndex++) {
            bytes1 command = _commands[commandIndex];
            bytes4 selector = _functionSelectors[commandIndex];
            // Check if command is already registered by searching for implementation
            address oldImplementationAddress = pcs.implementationAndFunction[command].implementation;
            if (oldImplementationAddress != address(0)) {
                revert CommandAlreadyRegistered(command);
            }

            // Add to supportedCommands array for enumeration
            pcs.supportedCommands.push(command);
            pcs.implementationAndFunction[command] = ImplementationAndFunction(_implementationAddress, selector);
        }
    }

    /**
     * @notice Replace the current address & selector associated with a command
     * @param _implementationAddress New implementation address
     * @param _commands Commands to be replaced
     * @param _functionSelectors New function selectors for the commands
     */
    function replaceFunctions(
        address _implementationAddress,
        bytes memory _commands,
        bytes4[] memory _functionSelectors
    ) internal {
        PreviewCommandsStorage storage pcs = previewCommandsStorage();
        if (_implementationAddress == address(0)) {
            revert CannotReplaceFunctionsFromFacetWithZeroAddress(_functionSelectors);
        }
        enforceHasContractCode(_implementationAddress);
        for (uint256 commandIndex; commandIndex < _commands.length; commandIndex++) {
            bytes1 command = _commands[commandIndex];
            bytes4 selector = _functionSelectors[commandIndex];
            address oldImplementationAddress = pcs.implementationAndFunction[command].implementation;
            // can't replace immutable functions -- functions defined directly in the contract
            if (oldImplementationAddress == address(this)) {
                revert CannotReplaceImmutableFunction(selector);
            }
            if (oldImplementationAddress == _implementationAddress) {
                revert CannotReplaceFunctionWithTheSameFunctionFromTheSameFacet(selector);
            }
            if (oldImplementationAddress == address(0)) {
                revert CannotReplaceFunctionThatDoesNotExists(selector);
            }
            // replace old implementation address and selector
            pcs.implementationAndFunction[command].implementation = _implementationAddress;
            pcs.implementationAndFunction[command].functionSelector = selector;
        }
    }

    /**
     * @notice Remove functions but keep the storage of the implementation
     * @param _facetAddress Must be zero address for removal operations
     * @param commands Commands to be removed
     * @param _functionSelectors Function selectors associated with commands to be removed
     */
    function removeFunctions(address _facetAddress, bytes memory commands, bytes4[] memory _functionSelectors)
        internal
    {
        PreviewCommandsStorage storage pcs = previewCommandsStorage();
        if (_facetAddress != address(0)) {
            revert RemoveFacetAddressMustBeZeroAddress(_facetAddress);
        }
        for (uint256 commandIndex; commandIndex < commands.length; commandIndex++) {
            bytes1 command = commands[commandIndex];
            bytes4 selector = _functionSelectors[commandIndex];

            ImplementationAndFunction memory implementationAndFunction = pcs.implementationAndFunction[command];
            if (implementationAndFunction.implementation == address(0)) {
                revert CannotRemoveFunctionThatDoesNotExist(selector);
            }

            // can't remove immutable functions -- functions defined directly in the contract
            if (implementationAndFunction.implementation == address(this)) {
                revert CannotRemoveImmutableFunction(selector);
            }

            // Remove command from supportedCommands array
            for (uint256 i = 0; i < pcs.supportedCommands.length; i++) {
                if (pcs.supportedCommands[i] == command) {
                    // Replace with the last element and pop
                    pcs.supportedCommands[i] = pcs.supportedCommands[pcs.supportedCommands.length - 1];
                    pcs.supportedCommands.pop();
                    break;
                }
            }

            // delete command mapping
            delete pcs.implementationAndFunction[command];
        }
    }

    /**
     * @notice Initialize implementation with delegatecall if _init is not zero address
     * @param _init Implementation address to initialize
     * @param _calldata Calldata to pass to the implementation
     */
    function initializeImplementation(address _init, bytes memory _calldata) internal {
        if (_init == address(0)) {
            return;
        }
        enforceHasContractCode(_init);
        (bool success, bytes memory error) = _init.delegatecall(_calldata);
        if (!success) {
            if (error.length > 0) {
                // bubble up error
                /// @solidity memory-safe-assembly
                assembly {
                    let returndata_size := mload(error)
                    revert(add(32, error), returndata_size)
                }
            } else {
                revert InitializationFunctionReverted(_init, _calldata);
            }
        }
    }

    /**
     * @notice Ensure the provided address contains contract code
     * @param _contract Address to check for code
     */
    function enforceHasContractCode(address _contract) internal view {
        uint256 contractSize;
        assembly {
            contractSize := extcodesize(_contract)
        }
        if (contractSize == 0) {
            revert NoBytecodeAtAddress(_contract);
        }
    }
}

src/router/modules/libraries/LibRegistryStorage.sol

pragma solidity ^0.8.20;

library LibRegistryStorage {
    event RegistryChange(address indexed previousRegistry, address indexed newRegistry);

    // EIP-7201: keccak256(abi.encode(uint256(keccak256("spectra.storage.registry")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 constant REGISTRY_STORAGE_POSITION =
        keccak256(abi.encode(uint256(keccak256("spectra.storage.registry")) - 1)) & ~bytes32(uint256(0xff));

    struct RegistryStorage {
        // @dev: address of the registry
        address registry;
    }

    function registryStorage() internal pure returns (RegistryStorage storage rs) {
        bytes32 position = REGISTRY_STORAGE_POSITION;
        assembly {
            rs.slot := position
        }
    }

    function setRegistry(address _registry) internal {
        emit RegistryChange(registryStorage().registry, _registry);
        registryStorage().registry = _registry;
    }

    function getRegistry() internal view returns (address) {
        return registryStorage().registry;
    }
}

src/router/util/RouterUtil.sol

// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import {Math} from "openzeppelin-contracts/utils/math/Math.sol";
import {IERC20Metadata} from "openzeppelin-contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IERC4626} from "openzeppelin-contracts/interfaces/IERC4626.sol";
import {IERC3156FlashLender} from "openzeppelin-contracts/interfaces/IERC3156FlashLender.sol";
import {SafeCast} from "openzeppelin-contracts/utils/math/SafeCast.sol";
import {RayMath} from "core-v2/src/libraries/RayMath.sol";
import {CurvePoolUtil} from "core-v2/src/libraries/CurvePoolUtil.sol";
import {ICurvePool} from "core-v2/src/interfaces/ICurvePool.sol";
import {IStableSwapNG} from "core-v2/src/interfaces/IStableSwapNG.sol";
import {ICurveNGPool} from "core-v2/src/interfaces/ICurveNGPool.sol";
import {IPrincipalToken} from "core-v2/src/interfaces/IPrincipalToken.sol";
import {Constants} from "../Constants.sol";

/**
 * @title Router Util contract
 * @author Spectra Finance
 * @notice Provides miscellaneous utils and preview functions related to Router executions.
 */
contract RouterUtil {
    using Math for uint256;
    using SafeCast for uint256;
    using SafeCast for int256;

    error InvalidTokenIndex(uint256 i, uint256 j);
    error PoolLiquidityError();
    error UnsufficientAmountForFlashFee();
    error ResultNotFound();

    /**
     * @dev Gives the spot exchange rate of token i in terms of token j. Exchange rate is in 18 decimals
     * @dev To be used with Curve Cryptoswap pools
     * @param _curvePool PT/IBT curve pool
     * @param _i token index, either 0 or 1
     * @param _j token index, either 0 or 1, must be different than _i
     * @return The spot exchange rate of _i in terms of _j
     */

    function spotExchangeRate(address _curvePool, uint256 _i, uint256 _j) public view returns (uint256) {
        if (_i == 0 && _j == 1) {
            return CurvePoolUtil.CURVE_UNIT.mulDiv(CurvePoolUtil.CURVE_UNIT, ICurvePool(_curvePool).last_prices());
        } else if (_i == 1 && _j == 0) {
            return ICurvePool(_curvePool).last_prices();
        } else {
            revert InvalidTokenIndex(_i, _j);
        }
    }

    /**
     * @dev Gives the spot exchange rate of token i in terms of token j. Exchange rate is in 18 decimals
     * @dev To be used with Curve Stableswap pools
     * @param _curvePool PT/IBT curve pool
     * @param _i token index, either 0 or 1
     * @param _j token index, either 0 or 1, must be different than _i
     * @return The spot exchange rate of _i in terms of _j
     */
    function spotExchangeRateSNG(address _curvePool, int128 _i, int128 _j) public view returns (uint256) {
        uint256 last_prices = IStableSwapNG(_curvePool).last_price(0);
        uint256[] memory stored_rates = IStableSwapNG(_curvePool).stored_rates();

        if (_i == 0 && _j == 1) {
            last_prices = stored_rates[0].mulDiv(CurvePoolUtil.CURVE_UNIT, stored_rates[1])
                .mulDiv(CurvePoolUtil.CURVE_UNIT, last_prices);
            return last_prices;
        } else if (_i == 1 && _j == 0) {
            last_prices = last_prices.mulDiv(stored_rates[1], stored_rates[0]);
            return last_prices;
        } else {
            revert InvalidTokenIndex(uint256(uint128(_i)), uint256(uint128(_j)));
        }
    }

    /**
     * @dev To be used with Curve Cryptoswap pools
     * @dev Gives the upper bound of the interval to perform bisection search in previewFlashSwapExactIBTForYT().
     * @param _inputIBTAmount amount of IBT exchanged for YT
     * @param _curvePool PT/IBT curve pool
     * @return The upper bound for search interval in root finding algorithms
     */
    function convertIBTToYTSpot(uint256 _inputIBTAmount, address _curvePool) public view returns (uint256) {
        // The spot exchange rate between IBT and YT is evaluated using the tokenization equation without fees.
        // This equation reads: ptRate = 1 PT + 1 YT .

        address pt = ICurvePool(_curvePool).coins(1);
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray

        uint256 ptInUnderlyingRay = spotExchangeRate(_curvePool, 1, 0).mulDiv(ibtRate, CurvePoolUtil.CURVE_UNIT);
        if (ptInUnderlyingRay > ptRate) {
            revert PoolLiquidityError();
        }
        uint256 ytInUnderlyingRay = ptRate - ptInUnderlyingRay;

        return _inputIBTAmount.mulDiv(ibtRate, ytInUnderlyingRay);
    }

    /**
     * @dev Returns the maximal amount of YT one can obtain with a given amount of IBT (i.e without fees or slippage).
     * @dev To be used with Curve Stableswap NG pools
     * @dev Gives the upper bound of the interval to perform bisection search in previewFlashSwapExactIBTForYT().
     * @param _inputIBTAmount amount of IBT exchanged for YT
     * @param _curvePool PT/IBT curve pool
     * @return The upper bound for search interval in root finding algorithms
     */
    function convertIBTToYTSpotSNG(uint256 _inputIBTAmount, address _curvePool) public view returns (uint256) {
        // The spot exchange rate between IBT and YT is evaluated using the tokenization equation without fees.
        // This equation reads: ptRate = 1 PT + 1 YT .

        address pt = ICurvePool(_curvePool).coins(1);
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray

        uint256 ptInUnderlyingRay = spotExchangeRateSNG(_curvePool, 1, 0).mulDiv(ibtRate, CurvePoolUtil.CURVE_UNIT);
        if (ptInUnderlyingRay > ptRate) {
            revert PoolLiquidityError();
        }
        uint256 ytInUnderlyingRay = ptRate - ptInUnderlyingRay;

        return _inputIBTAmount.mulDiv(ibtRate, ytInUnderlyingRay);
    }

    /* PREVIEW FUNCTIONS FOR CURVE CRYPTOSWAP POOLS
     *****************************************************************************************************************/

    /**
     * @dev Computes the amount of IBT required to buy a given output amount of YT.
     * @dev Works for both Cryptoswap
     * @param _curvePool PT/IBT curve pool
     * @param _outputYTAmount desired output YT token amount
     * @return inputIBTAmount The amount of IBT needed for obtaining the defined amount of YT
     * @return borrowedIBTAmount the quantity of IBT borrowed to execute that swap
     */
    function previewFlashSwapIBTToExactYT(address _curvePool, uint256 _outputYTAmount)
        public
        view
        returns (uint256 inputIBTAmount, uint256 borrowedIBTAmount)
    {
        // Tokens
        address pt = ICurvePool(_curvePool).coins(1);
        address ibt = IPrincipalToken(pt).getIBT();

        // Units and rates
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray

        // Outputs
        uint256 swapPTForIBT = ICurvePool(_curvePool).get_dy(1, 0, _outputYTAmount);

        // y PT:YT = (x IBT * ((UNIT - tokenizationFee) / UNIT) * ibtRate) / ptRate
        // <=> x IBT = (y PT:YT * ptRate * UNIT) / (ibtRate * (UNIT - tokenizationFee))
        borrowedIBTAmount = (_outputYTAmount * ptRate * Constants.UNIT)
        .ceilDiv(ibtRate * (Constants.UNIT - IPrincipalToken(pt).getTokenizationFee()));
        if (swapPTForIBT > borrowedIBTAmount) {
            revert PoolLiquidityError();
        }
        inputIBTAmount = borrowedIBTAmount + _getFlashFee(pt, ibt, borrowedIBTAmount) - swapPTForIBT;
    }

    /**
     * @dev Computes the amount of IBT required to buy a given output amount of YT.
     * @dev Works for both Stableswap NG pools
     * @param _curvePool PT/IBT curve pool
     * @param _outputYTAmount desired output YT token amount
     * @return inputIBTAmount The amount of IBT needed for obtaining the defined amount of YT
     * @return borrowedIBTAmount the quantity of IBT borrowed to execute that swap
     */
    function previewFlashSwapIBTToExactYTSNG(address _curvePool, uint256 _outputYTAmount)
        public
        view
        returns (uint256 inputIBTAmount, uint256 borrowedIBTAmount)
    {
        // Tokens
        address pt = ICurvePool(_curvePool).coins(1);
        address ibt = IPrincipalToken(pt).getIBT();

        // Units and rates
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray

        // Outputs
        uint256 swapPTForIBT = IStableSwapNG(_curvePool).get_dy(1, 0, _outputYTAmount);

        // y PT:YT = (x IBT * ((UNIT - tokenizationFee) / UNIT) * ibtRate) / ptRate
        // <=> x IBT = (y PT:YT * ptRate * UNIT) / (ibtRate * (UNIT - tokenizationFee))
        borrowedIBTAmount = (_outputYTAmount * ptRate * Constants.UNIT)
        .ceilDiv(ibtRate * (Constants.UNIT - IPrincipalToken(pt).getTokenizationFee()));
        if (swapPTForIBT > borrowedIBTAmount) {
            revert PoolLiquidityError();
        }
        inputIBTAmount = borrowedIBTAmount + _getFlashFee(pt, ibt, borrowedIBTAmount) - swapPTForIBT;
    }

    /**
     * @dev Approximates the expected output amount of YT corresponding to a given input amount of IBT.
     * @dev To be used with Curve Cryptoswap pools
     * @dev May return an output YT amount that corresponds to an input IBT amount lower than the given _inputIBTAmount.
     * @dev This function can be expensive to execute and should only be called off-chain. Avoid using it within a transaction.
     * @param _curvePool PT/IBT curve pool
     * @param _inputIBTAmount amount of IBT exchanged for YT
     * @return ytAmount The guess of YT obtained for the given amount of IBT
     * @return borrowedIBTAmount The quantity of IBT borrowed to execute that swap.
     */
    function previewFlashSwapExactIBTToYT(address _curvePool, uint256 _inputIBTAmount)
        public
        view
        returns (uint256 ytAmount, uint256 borrowedIBTAmount)
    {
        // initial guesses
        address pt = ICurvePool(_curvePool).coins(1);
        uint256 x0 = IPrincipalToken(pt).previewDepositIBT(_inputIBTAmount);
        uint256 x1 = convertIBTToYTSpot(_inputIBTAmount, _curvePool);
        uint256 ibtUnit = getUnit(ICurvePool(_curvePool).coins(0));

        // Use secant method to approximate ytAmount
        for (uint256 i = 0; i < Constants.MAX_ITERATIONS_SECANT; ++i) {
            if (_delta(x0, x1).mulDiv(ibtUnit, Math.max(x0, x1)) < ibtUnit / Constants.PRECISION_DIVISOR) {
                break;
            }

            (uint256 inputIBTAmount0,) = previewFlashSwapIBTToExactYT(_curvePool, x0);
            (uint256 inputIBTAmount1,) = previewFlashSwapIBTToExactYT(_curvePool, x1);
            int256 answer0 = inputIBTAmount0.toInt256() - _inputIBTAmount.toInt256();
            int256 answer1 = inputIBTAmount1.toInt256() - _inputIBTAmount.toInt256();

            if (answer0 == answer1) {
                break;
            }

            // x2 = x1 - (f(x1) * (x1 - x0) / (f(x1) - f(x0)))
            // x0, x1 = x1, x2
            uint256 x2 =
                (x1.toInt256() - ((answer1 * (x1.toInt256() - x0.toInt256())) / (answer1 - answer0))).toUint256();
            x0 = x1;
            x1 = x2;
        }
        ytAmount = Math.min(x0, x1);

        uint256 resInputIBTAmount;
        (resInputIBTAmount, borrowedIBTAmount) = previewFlashSwapIBTToExactYT(_curvePool, ytAmount);

        // Run linear search if inputIBTAmount corresponding to ytAmount is higher than requested
        if (resInputIBTAmount > _inputIBTAmount) {
            // linear search
            uint256 sf = Constants.SCALING_FACTOR_LINEAR_SEARCH;
            for (uint256 i = 0; i < Constants.MAX_ITERATIONS_LINEAR_SEARCH; ++i) {
                ytAmount = ytAmount.mulDiv(sf - 1, sf);
                (resInputIBTAmount, borrowedIBTAmount) = previewFlashSwapIBTToExactYT(_curvePool, ytAmount);
                if (resInputIBTAmount <= _inputIBTAmount) {
                    break;
                }
            }
        }

        // if result is still higher or too far from requested value
        if (
            resInputIBTAmount > _inputIBTAmount
                || _delta(_inputIBTAmount, resInputIBTAmount).mulDiv(ibtUnit, _inputIBTAmount)
                    > ibtUnit / Constants.PRECISION_DIVISOR
        ) {
            revert ResultNotFound();
        }
    }

    /**
     * @dev Approximates the expected output amount of YT corresponding to a given input amount of IBT.
     * @dev To be used with Curve Stableswap NG pools
     * @dev May return an output YT amount that corresponds to an input IBT amount lower than the given _inputIBTAmount.
     * @dev This function can be expensive to execute and should only be called off-chain. Avoid using it within a transaction.
     * @param _curvePool PT/IBT curve pool
     * @param _inputIBTAmount amount of IBT exchanged for YT
     * @return ytAmount The guess of YT obtained for the given amount of IBT
     * @return borrowedIBTAmount The quantity of IBT borrowed to execute that swap.
     */
    function previewFlashSwapExactIBTToYTSNG(address _curvePool, uint256 _inputIBTAmount)
        public
        view
        returns (uint256 ytAmount, uint256 borrowedIBTAmount)
    {
        // initial guesses
        address pt = IStableSwapNG(_curvePool).coins(1);
        uint256 x0 = IPrincipalToken(pt).previewDepositIBT(_inputIBTAmount);
        uint256 x1 = convertIBTToYTSpotSNG(_inputIBTAmount, _curvePool);
        uint256 ibtUnit = getUnit(ICurvePool(_curvePool).coins(0));

        // Use secant method to approximate ytAmount
        for (uint256 i = 0; i < Constants.MAX_ITERATIONS_SECANT; ++i) {
            if (_delta(x0, x1).mulDiv(ibtUnit, Math.max(x0, x1)) < ibtUnit / Constants.PRECISION_DIVISOR) {
                break;
            }

            (uint256 inputIBTAmount0,) = previewFlashSwapIBTToExactYTSNG(_curvePool, x0);
            (uint256 inputIBTAmount1,) = previewFlashSwapIBTToExactYTSNG(_curvePool, x1);
            int256 answer0 = inputIBTAmount0.toInt256() - _inputIBTAmount.toInt256();
            int256 answer1 = inputIBTAmount1.toInt256() - _inputIBTAmount.toInt256();

            if (answer0 == answer1) {
                break;
            }

            // x2 = x1 - (f(x1) * (x1 - x0) / (f(x1) - f(x0)))
            // x0, x1 = x1, x2
            uint256 x2 =
                (x1.toInt256() - ((answer1 * (x1.toInt256() - x0.toInt256())) / (answer1 - answer0))).toUint256();
            x0 = x1;
            x1 = x2;
        }
        ytAmount = Math.min(x0, x1);

        uint256 resInputIBTAmount;
        (resInputIBTAmount, borrowedIBTAmount) = previewFlashSwapIBTToExactYTSNG(_curvePool, ytAmount);

        // Run linear search if inputIBTAmount corresponding to ytAmount is higher than requested
        if (resInputIBTAmount > _inputIBTAmount) {
            // linear search
            uint256 sf = Constants.SCALING_FACTOR_LINEAR_SEARCH;
            for (uint256 i = 0; i < Constants.MAX_ITERATIONS_LINEAR_SEARCH; ++i) {
                ytAmount = ytAmount.mulDiv(sf - 1, sf);
                (resInputIBTAmount, borrowedIBTAmount) = previewFlashSwapIBTToExactYTSNG(_curvePool, ytAmount);
                if (resInputIBTAmount <= _inputIBTAmount) {
                    break;
                }
            }
        }

        // if result is still higher or too far from requested value
        if (
            resInputIBTAmount > _inputIBTAmount
                || _delta(_inputIBTAmount, resInputIBTAmount).mulDiv(ibtUnit, _inputIBTAmount)
                    > ibtUnit / Constants.PRECISION_DIVISOR
        ) {
            revert ResultNotFound();
        }
    }

    /**
     * @dev Given an amount of YT, previews the amount of IBT received after exchange
     * @dev To be used with Curve Cryptoswap pools
     * @param _curvePool PT/IBT curve pool
     * @param inputYTAmount amount of YT exchanged for IBT
     * @return The amount of IBT obtained for the given amount of YT
     * @return The amount of IBT borrowed to execute that swap.
     */
    function previewFlashSwapExactYTToIBT(address _curvePool, uint256 inputYTAmount)
        public
        view
        returns (uint256, uint256)
    {
        // Tokens
        address pt = ICurvePool(_curvePool).coins(1);
        address ibt = IPrincipalToken(pt).getIBT();
        // Units and Rates
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray
        // Outputs
        uint256 borrowedIBTAmount = CurvePoolUtil.getDx(_curvePool, 0, 1, inputYTAmount);
        uint256 inputYTAmountInIBT = inputYTAmount.mulDiv(ptRate, ibtRate);
        uint256 flashFee = _getFlashFee(pt, ibt, borrowedIBTAmount);
        if (borrowedIBTAmount > inputYTAmountInIBT) {
            revert PoolLiquidityError();
        } else if (borrowedIBTAmount + flashFee > inputYTAmountInIBT) {
            revert UnsufficientAmountForFlashFee();
        }
        uint256 outputIBTAmount = inputYTAmountInIBT - borrowedIBTAmount - flashFee;

        return (outputIBTAmount, borrowedIBTAmount);
    }

    /**
     * @dev Given an amount of YT, previews the amount of IBT received after exchange
     * @dev To be used with Curve StableSwap NG pools
     * @param _curvePool PT/IBT curve pool
     * @param inputYTAmount amount of YT exchanged for IBT
     * @return The amount of IBT obtained for the given amount of YT
     * @return The amount of IBT borrowed to execute that swap.
     */
    function previewFlashSwapExactYTToIBTSNG(address _curvePool, uint256 inputYTAmount)
        public
        view
        returns (uint256, uint256)
    {
        // Tokens
        address pt = ICurvePool(_curvePool).coins(1);
        address ibt = IPrincipalToken(pt).getIBT();
        // Units and Rates
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray
        // Outputs
        uint256 borrowedIBTAmount = IStableSwapNG(_curvePool).get_dx(0, 1, inputYTAmount);
        uint256 inputYTAmountInIBT = inputYTAmount.mulDiv(ptRate, ibtRate);
        uint256 flashFee = _getFlashFee(pt, ibt, borrowedIBTAmount);
        if (borrowedIBTAmount > inputYTAmountInIBT) {
            revert PoolLiquidityError();
        } else if (borrowedIBTAmount + flashFee > inputYTAmountInIBT) {
            revert UnsufficientAmountForFlashFee();
        }
        uint256 outputIBTAmount = inputYTAmountInIBT - borrowedIBTAmount - flashFee;

        return (outputIBTAmount, borrowedIBTAmount);
    }

    /**
     * @notice Given an amount of asset, previews the amount of lp tokens received after depositing in the curve pool
     * @notice To be used with Curve Cryptoswap pools
     * @param _curvePool address of the curve pool
     * @param _assets amount of assets to deposit into the curve pool
     * @return minMintAmount amount of lp tokens received
     */
    function previewAddLiquidityWithAsset(address _curvePool, uint256 _assets)
        public
        view
        returns (uint256 minMintAmount)
    {
        address ibt = ICurvePool(_curvePool).coins(0);
        uint256 ibts = IERC4626(ibt).previewDeposit(_assets);
        minMintAmount = previewAddLiquidityWithIBT(_curvePool, ibts);
    }

    /**
     * @notice Given an amount of asset, previews the amount of lp tokens received after depositing in the curve pool
     * @notice To be used with Curve Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _assets amount of assets to deposit into the curve pool
     * @return minMintAmount amount of lp tokens received
     */
    function previewAddLiquidityWithAssetSNG(address _curvePool, uint256 _assets)
        public
        view
        returns (uint256 minMintAmount)
    {
        address ibt = ICurvePool(_curvePool).coins(0);
        uint256 ibts = IERC4626(ibt).previewDeposit(_assets);
        minMintAmount = previewAddLiquidityWithIBTSNG(_curvePool, ibts);
    }

    /**
     * @notice Given an amount of ibt, previews the amount of lp tokens received after depositing in the curve pool
     * @notice To be used with Curve Cryptoswap pools
     * @param _curvePool address of the curve pool
     * @param _ibts amount of ibt to deposit into the curve pool
     * @return minMintAmount amount of lp tokens received
     */
    function previewAddLiquidityWithIBT(address _curvePool, uint256 _ibts) public view returns (uint256 minMintAmount) {
        address pt = ICurvePool(_curvePool).coins(1);
        uint256 ibtToDepositInPT = CurvePoolUtil.calcIBTsToTokenizeForCurvePool(_ibts, _curvePool, pt);
        uint256 amount0 = _ibts - ibtToDepositInPT;
        uint256 amount1 = IPrincipalToken(pt).previewDepositIBT(ibtToDepositInPT);
        minMintAmount = previewAddLiquidity(_curvePool, [amount0, amount1]);
    }

    /**
     * @notice Given an amount of ibt, previews the amount of lp tokens received after depositing in the curve pool
     * @notice To be used with Curve Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _ibts amount of ibt to deposit into the curve pool
     * @return minMintAmount amount of lp tokens received
     */
    function previewAddLiquidityWithIBTSNG(address _curvePool, uint256 _ibts)
        public
        view
        returns (uint256 minMintAmount)
    {
        address pt = IStableSwapNG(_curvePool).coins(1);
        uint256 ibtToDepositInPT = CurvePoolUtil.calcIBTsToTokenizeForCurvePool(_ibts, _curvePool, pt);
        uint256 amount0 = _ibts - ibtToDepositInPT;
        uint256 amount1 = IPrincipalToken(pt).previewDepositIBT(ibtToDepositInPT);
        uint256[] memory amounts = new uint256[](2);
        amounts[0] = amount0;
        amounts[1] = amount1;
        minMintAmount = previewAddLiquiditySNG(_curvePool, amounts);
    }

    /**
     * @notice Given an amount of ibts and pts, previews the amount of lp tokens received after depositing in the curve pool
     * @notice To be used with Curve Cryptoswap pools
     * @param _curvePool address of the curve pool
     * @param _amounts array of length two containing the amount of ibt and pt to deposit into the pool respectively
     * @return minMintAmount amount of lp tokens received
     */
    function previewAddLiquidity(address _curvePool, uint256[2] memory _amounts)
        public
        view
        returns (uint256 minMintAmount)
    {
        minMintAmount = CurvePoolUtil.previewAddLiquidity(_curvePool, _amounts);
    }

    /**
     * @notice Given an amount of ibts and pts, previews the amount of lp tokens received after depositing in the curve pool
     * @notice To be used with Curve Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _amounts array of length two containing the amount of ibt and pt to deposit into the pool respectively
     * @return minMintAmount amount of lp tokens received
     */
    function previewAddLiquiditySNG(address _curvePool, uint256[] memory _amounts)
        public
        view
        returns (uint256 minMintAmount)
    {
        minMintAmount = CurvePoolUtil.previewAddLiquiditySNG(_curvePool, _amounts);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of asset received after withdrawing from the curve pool
     * @notice To be used with Curve Cryptoswap and Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @return assets amount of asset received
     */
    function previewRemoveLiquidityForAsset(address _curvePool, uint256 _lpAmount)
        public
        view
        returns (uint256 assets)
    {
        uint256[2] memory minAmounts = CurvePoolUtil.previewRemoveLiquidity(_curvePool, _lpAmount);
        assets = IERC4626(ICurvePool(_curvePool).coins(0)).previewRedeem(minAmounts[0])
            + IPrincipalToken(ICurvePool(_curvePool).coins(1)).previewRedeem(minAmounts[1]);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of asset received after withdrawing from the curve pool
     * @notice To be used with Curve Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @return assets amount of asset received
     */
    function previewRemoveLiquidityForAssetSNG(address _curvePool, uint256 _lpAmount)
        public
        view
        returns (uint256 assets)
    {
        uint256[] memory minAmounts = CurvePoolUtil.previewRemoveLiquiditySNG(_curvePool, _lpAmount);
        assets = IERC4626(ICurvePool(_curvePool).coins(0)).previewRedeem(minAmounts[0])
            + IPrincipalToken(ICurvePool(_curvePool).coins(1)).previewRedeem(minAmounts[1]);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of ibt received after withdrawing from the curve pool
     * @notice To be used with Curve Cryptoswap
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @return ibts amount of ibt received
     */
    function previewRemoveLiquidityForIBT(address _curvePool, uint256 _lpAmount) public view returns (uint256 ibts) {
        uint256[2] memory minAmounts = CurvePoolUtil.previewRemoveLiquidity(_curvePool, _lpAmount);
        ibts = minAmounts[0] + IPrincipalToken(ICurvePool(_curvePool).coins(1)).previewRedeemForIBT(minAmounts[1]);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of ibt received after withdrawing from the curve pool
     * @notice To be used with Curve Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @return ibts amount of ibt received
     */
    function previewRemoveLiquidityForIBTSNG(address _curvePool, uint256 _lpAmount) public view returns (uint256 ibts) {
        uint256[] memory minAmounts = CurvePoolUtil.previewRemoveLiquiditySNG(_curvePool, _lpAmount);
        ibts = minAmounts[0] + IPrincipalToken(ICurvePool(_curvePool).coins(1)).previewRedeemForIBT(minAmounts[1]);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of ibt and pt received after withdrawing from the curve pool
     * @notice To be used with Curve Cryptoswap and Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @return minAmounts array of length two cointaining the amount of ibt and pt received after withdrawing from the curve pool
     */
    function previewRemoveLiquidity(address _curvePool, uint256 _lpAmount)
        public
        view
        returns (uint256[2] memory minAmounts)
    {
        minAmounts = CurvePoolUtil.previewRemoveLiquidity(_curvePool, _lpAmount);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of ibt and pt received after withdrawing from the curve pool
     * @notice To be used with Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @return minAmounts array of length two cointaining the amount of ibt and pt received after withdrawing from the curve pool
     */
    function previewRemoveLiquiditySNG(address _curvePool, uint256 _lpAmount)
        public
        view
        returns (uint256[] memory minAmounts)
    {
        minAmounts = CurvePoolUtil.previewRemoveLiquiditySNG(_curvePool, _lpAmount);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of token at index _i received after withdrawing from the curve pool
     * @notice To be used with Curve Cryptoswap and  pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @param _i Index of the token to withdraw in
     * @return minAmount amount of token at index _i after withdrawing from the curve pool
     */
    function previewRemoveLiquidityOneCoin(address _curvePool, uint256 _lpAmount, uint256 _i)
        public
        view
        returns (uint256 minAmount)
    {
        minAmount = CurvePoolUtil.previewRemoveLiquidityOneCoin(_curvePool, _lpAmount, _i);
    }

    /**
     * @notice Given an amount of lp tokens, previews the amount of token at index _i received after withdrawing from the curve pool
     * @notice To be used with Curve  Stableswap NG pools
     * @param _curvePool address of the curve pool
     * @param _lpAmount amount of lp tokens to withdraw from the curve pool
     * @param _i Index of the token to withdraw in
     * @return minAmount amount of token at index _i after withdrawing from the curve pool
     */
    function previewRemoveLiquidityOneCoinSNG(address _curvePool, uint256 _lpAmount, int128 _i)
        public
        view
        returns (uint256 minAmount)
    {
        minAmount = CurvePoolUtil.previewRemoveLiquidityOneCoinSNG(_curvePool, _lpAmount, _i);
    }

    /* PREVIEW FUNCTIONS FOR CURVE TWOCRYPTO-NG POOLS
     *****************************************************************************************************************/

    /**
     * @dev Computes the amount of IBT required to buy a given output amount of YT.
     * @param _curvePool PT/IBT curve pool
     * @param _outputYTAmount desired output YT token amount
     * @return inputIBTAmount The amount of IBT needed for obtaining the defined amount of YT
     * @return borrowedIBTAmount the quantity of IBT borrowed to execute that swap
     */
    function previewNGFlashSwapIBTToExactYT(address _curvePool, uint256 _outputYTAmount)
        public
        view
        returns (uint256 inputIBTAmount, uint256 borrowedIBTAmount)
    {
        return previewFlashSwapIBTToExactYT(_curvePool, _outputYTAmount);
    }

    /**
     * @dev Approximates the expected output amount of YT corresponding to a given input amount of IBT.
     * @dev May return an output YT amount that corresponds to an input IBT amount lower than the given _inputIBTAmount.
     * @dev This function can be expensive to execute and should only be called off-chain. Avoid using it within a transaction.
     * @param _curvePool PT/IBT curve pool
     * @param _inputIBTAmount amount of IBT exchanged for YT
     * @return ytAmount The guess of YT obtained for the given amount of IBT
     * @return borrowedIBTAmount The quantity of IBT borrowed to execute that swap.
     */
    function previewNGFlashSwapExactIBTToYT(address _curvePool, uint256 _inputIBTAmount)
        public
        view
        returns (uint256 ytAmount, uint256 borrowedIBTAmount)
    {
        return previewFlashSwapExactIBTToYT(_curvePool, _inputIBTAmount);
    }

    /**
     * @dev Given an amount of YT, previews the amount of IBT received after exchange
     * @param _curvePool PT/IBT curve pool
     * @param inputYTAmount amount of YT exchanged for IBT
     * @return The amount of IBT obtained for the given amount of YT
     * @return The amount of IBT borrowed to execute that swap.
     */
    function previewNGFlashSwapExactYTToIBT(address _curvePool, uint256 inputYTAmount)
        public
        view
        returns (uint256, uint256)
    {
        // Tokens
        address pt = ICurvePool(_curvePool).coins(1);
        address ibt = IPrincipalToken(pt).getIBT();
        // Units and Rates
        uint256 ibtRate = IPrincipalToken(pt).getIBTRate(); // Ray
        uint256 ptRateInUnderlying = IPrincipalToken(pt).convertToUnderlying(10 ** IPrincipalToken(pt).decimals());
        uint256 ptRate = RayMath.toRay(ptRateInUnderlying, IERC20Metadata(IPrincipalToken(pt).underlying()).decimals()); // Ray
        // Outputs
        uint256 borrowedIBTAmount = ICurveNGPool(_curvePool).get_dx(0, 1, inputYTAmount);
        uint256 inputYTAmountInIBT = inputYTAmount.mulDiv(ptRate, ibtRate);
        uint256 flashFee = _getFlashFee(pt, ibt, borrowedIBTAmount);
        if (borrowedIBTAmount > inputYTAmountInIBT) {
            revert PoolLiquidityError();
        } else if (borrowedIBTAmount + flashFee > inputYTAmountInIBT) {
            revert UnsufficientAmountForFlashFee();
        }
        uint256 outputIBTAmount = inputYTAmountInIBT - borrowedIBTAmount - flashFee;

        return (outputIBTAmount, borrowedIBTAmount);
    }

    function previewNGAddLiquidityWithAsset(address _curvePool, uint256 _assets)
        public
        view
        returns (uint256 minMintAmount)
    {
        address ibt = ICurveNGPool(_curvePool).coins(0);
        uint256 ibts = IERC4626(ibt).previewDeposit(_assets);
        minMintAmount = previewNGAddLiquidityWithIBT(_curvePool, ibts);
    }

    function previewNGAddLiquidityWithIBT(address _curvePool, uint256 _ibts)
        public
        view
        returns (uint256 minMintAmount)
    {
        address pt = ICurveNGPool(_curvePool).coins(1);
        uint256 ibtToDepositInPT = CurvePoolUtil.calcIBTsToTokenizeForCurvePool(_ibts, _curvePool, pt);
        uint256 amount0 = _ibts - ibtToDepositInPT;
        uint256 amount1 = IPrincipalToken(pt).previewDepositIBT(ibtToDepositInPT);
        minMintAmount = CurvePoolUtil.previewAddLiquidityNG(_curvePool, [amount0, amount1]);
    }

    function previewNGAddLiquidity(address _curvePool, uint256[2] memory _amounts)
        public
        view
        returns (uint256 minMintAmount)
    {
        minMintAmount = CurvePoolUtil.previewAddLiquidityNG(_curvePool, _amounts);
    }

    function previewNGRemoveLiquidityForAsset(address _curvePool, uint256 _lpAmount)
        public
        view
        returns (uint256 assets)
    {
        uint256[2] memory minAmounts = CurvePoolUtil.previewRemoveLiquidityNG(_curvePool, _lpAmount);
        assets = IERC4626(ICurveNGPool(_curvePool).coins(0)).previewRedeem(minAmounts[0])
            + IPrincipalToken(ICurveNGPool(_curvePool).coins(1)).previewRedeem(minAmounts[1]);
    }

    function previewNGRemoveLiquidityForIBT(address _curvePool, uint256 _lpAmount) public view returns (uint256 ibts) {
        uint256[2] memory minAmounts = CurvePoolUtil.previewRemoveLiquidityNG(_curvePool, _lpAmount);
        ibts = minAmounts[0] + IPrincipalToken(ICurvePool(_curvePool).coins(1)).previewRedeemForIBT(minAmounts[1]);
    }

    function previewNGRemoveLiquidity(address _curvePool, uint256 _lpAmount)
        public
        view
        returns (uint256[2] memory minAmounts)
    {
        minAmounts = CurvePoolUtil.previewRemoveLiquidityNG(_curvePool, _lpAmount);
    }

    function previewNGRemoveLiquidityOneCoin(address _curvePool, uint256 _lpAmount, uint256 _i)
        public
        view
        returns (uint256 minAmount)
    {
        minAmount = CurvePoolUtil.previewRemoveLiquidityOneCoinNG(_curvePool, _lpAmount, _i);
    }

    /* PUBLIC UTILS
     *****************************************************************************************************************/

    /**
     * @dev Returns the unit element of the underlying asset of a PT
     * @param _pt address of Principal Token
     * @return The unit of underlying asset
     */
    function getPTUnderlyingUnit(address _pt) external view returns (uint256) {
        return getUnit(IPrincipalToken(_pt).underlying());
    }

    /**
     * @dev Returns the unit element of the token
     * @param _token address of token
     * @return The unit of asset
     */
    function getUnit(address _token) public view returns (uint256) {
        return 10 ** IERC20Metadata(_token).decimals();
    }

    /* INTERNAL FUNCTIONS
     *****************************************************************************************************************/

    /**
     * @dev Calculates the flash loan fee for borrowing a given quantity of IBT
     * @param _pt address of Principal Token
     * @param _ibt address of Interest Bearing Token
     * @param _borrowedIBTAmount amount of Interest Bearing Tokens that have been borrowed in the flash loan
     * @return The amount of fees charged for flash loan
     */
    function _getFlashFee(address _pt, address _ibt, uint256 _borrowedIBTAmount) internal view returns (uint256) {
        return IERC3156FlashLender(_pt).flashFee(_ibt, _borrowedIBTAmount);
    }

    /**
     * @dev abs(a, b)
     * @param a some integer
     * @param b some integer
     * @return The absolute value of a - b
     */
    function _delta(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a - b : b - a;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {
    "src/router/modules/PrincipalTokenModule.sol": {
      "LibPreviewCommandsManagerModule": "0x78f37268db9e7601848a1647e01986c695801c82"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "config/=dependencies/spectra-contracts-configs-main/script/",
    "core-v2/=dependencies/core-v2-staging/",
    "dependencies/@openzeppelin-contracts-upgradeable-5.4.0-rc.1/:@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.4.0-rc.1/",
    "dependencies/core-v2-staging:script/=dependencies/core-v2-staging/script/",
    "dependencies/core-v2-staging:src/=dependencies/core-v2-staging/src/",
    "dependencies/diamond-router-V1/:src/=dependencies/diamond-router-V1/src/",
    "dependencies/limit-orders-beta:script/=dependencies/limit-orders-beta/script/",
    "dependencies/limit-orders-beta:src/=dependencies/limit-orders-beta/src/",
    "dependencies/spectra-bridge-stellar-main/:@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.4.0-rc.1/",
    "dependencies/spectra-bridge-stellar-main/:@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.4.0-rc.1/",
    "dependencies/spectra-bridge-stellar-main:src/=dependencies/spectra-bridge-stellar-main/contracts/evm/src/",
    "diamond-router/=dependencies/diamond-router-V1/",
    "forge-std/=dependencies/forge-std-1.9.7/src/",
    "limit-orders/=dependencies/limit-orders-beta/",
    "openzeppelin-contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.4.0-rc.1/",
    "openzeppelin-contracts/=dependencies/@openzeppelin-contracts-5.4.0-rc.1/",
    "roles/=dependencies/spectra-contracts-configs-main/access/",
    "spectra-bridge-stellar/=dependencies/spectra-bridge-stellar-main/contracts/evm/",
    "@openzeppelin-contracts-5.4.0-rc.1/=dependencies/@openzeppelin-contracts-5.4.0-rc.1/",
    "@openzeppelin-contracts-upgradeable-5.4.0-rc.1/=dependencies/@openzeppelin-contracts-upgradeable-5.4.0-rc.1/",
    "core-v2-staging/=dependencies/core-v2-staging/src/",
    "diamond-router-V1/=dependencies/diamond-router-V1/",
    "ds-test/=dependencies/diamond-router-V1/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=dependencies/diamond-router-V1/lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std-1.9.7/=dependencies/forge-std-1.9.7/src/",
    "halmos-cheatcodes/=dependencies/diamond-router-V1/lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "limit-orders-beta/=dependencies/limit-orders-beta/src/",
    "openzeppelin-erc20-basic/=dependencies/core-v2-staging/dependencies/diamond-router-V1/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/",
    "openzeppelin-math/=dependencies/core-v2-staging/dependencies/diamond-router-V1/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/",
    "solidity-stringutils/=dependencies/core-v2-staging/dependencies/diamond-router-V1/lib/solidity-stringutils/",
    "spectra-bridge-stellar-main/=dependencies/spectra-bridge-stellar-main/contracts/evm/src/",
    "spectra-contracts-configs-main/=dependencies/spectra-contracts-configs-main/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.