S Price: $0.572004 (-3.65%)

Contract

0xe3288E82F3B8a380f77990979656C316fF68bcAF

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Parent Transaction Hash Block From To
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
RouterUtil

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
shanghai EvmVersion
File 1 of 14 : RouterUtil.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.20;

import {Math} from "openzeppelin-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 {CurvePoolUtil} from "../../libraries/CurvePoolUtil.sol";
import {ICurvePool} from "../../interfaces/ICurvePool.sol";
import {IPrincipalToken} from "../../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
     * @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 Returns the maximal amount of YT one can obtain with a given amount of IBT (i.e without fees or slippage).
     * @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 ptRate = IPrincipalToken(pt).getPTRate(); // 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 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 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 ptRate = IPrincipalToken(pt).getPTRate(); // 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 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 previewFlashSwapExactIBTToYT(
        address _curvePool,
        uint256 _inputIBTAmount
    ) public view returns (uint256 ytAmount, uint256 borrowedIBTAmount) {
        uint256 ibtUnit = getUnit(ICurvePool(_curvePool).coins(0));
        address pt = ICurvePool(_curvePool).coins(1);

        // initial guesses
        uint256 x0 = IPrincipalToken(pt).previewDepositIBT(_inputIBTAmount);
        uint256 x1 = convertIBTToYTSpot(_inputIBTAmount, _curvePool);

        // 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 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 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();
        uint256 ptRate = IPrincipalToken(pt).getPTRate();
        // 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);
    }

    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);
    }

    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]);
    }

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

    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]);
    }

    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]);
    }

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

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

    /**
     * @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) public 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;
    }
}

File 2 of 14 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Muldiv operation overflow.
     */
    error MathOverflowedMulDiv();

    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an overflow flag.
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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.
            return a / b;
        }

        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     * @dev 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 {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 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 prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            if (denominator <= prod1) {
                revert MathOverflowedMulDiv();
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, 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 {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

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

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // 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^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
        }
    }

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

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @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 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
        }
    }

    /**
     * @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;
    }
}

File 3 of 14 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC20 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);
}

File 4 of 14 : IERC4626.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface of the ERC4626 "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 redeemption 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);
}

File 5 of 14 : IERC3156FlashLender.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC3156FlashLender.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface of the ERC3156 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);
}

File 6 of 14 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 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);
    }
}

File 7 of 14 : CurvePoolUtil.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity 0.8.20;

import "../interfaces/ICurvePool.sol";
import "../interfaces/IPrincipalToken.sol";
import "openzeppelin-math/Math.sol";

/**
 * @title CurvePoolUtil library
 * @author Spectra Finance
 * @notice Provides miscellaneous utils for computations related to Curve protocol.
 */
library CurvePoolUtil {
    using Math 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
     * @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 IBT and PT amounts received for burning a given amount of LP tokens
     * @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 amount of coin i received for burning a given amount of LP tokens
     * @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 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);
    }

    /**
     * @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));
    }
}

File 8 of 14 : ICurvePool.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

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;
}

File 9 of 14 : IPrincipalToken.sol
// SPDX-License-Identifier: BUSL-1.1

pragma solidity ^0.8.20;

import "openzeppelin-contracts/interfaces/IERC20.sol";
import "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
     * @param _minAssets The minimum amount of assets that should be received
     * @return assets The amount of assets sent to the fee collector
     */
    function claimFees(uint256 _minAssets) external returns (uint256 assets);

    /**
     * @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);
}

File 10 of 14 : 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);
}

File 11 of 14 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
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);
}

File 12 of 14 : IERC3156FlashBorrower.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC3156FlashBorrower.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC3156 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);
}

File 13 of 14 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

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

File 14 of 14 : IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

Settings
{
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/contracts/",
    "openzeppelin-erc20-basic/=lib/openzeppelin-contracts/contracts/token/ERC20/",
    "openzeppelin-erc20-extensions/=lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/",
    "openzeppelin-erc20/=lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/",
    "openzeppelin-math/=lib/openzeppelin-contracts/contracts/utils/math/",
    "openzeppelin-proxy/=lib/openzeppelin-contracts-upgradeable/contracts/proxy/utils/",
    "openzeppelin-utils/=lib/openzeppelin-contracts/contracts/utils/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "viaIR": false,
  "libraries": {
    "src/libraries/CurvePoolUtil.sol": {
      "CurvePoolUtil": "0xe6c69Dd9c450406c3E4383431bAe36B7B6aE018c"
    },
    "src/libraries/PrincipalTokenUtil.sol": {
      "PrincipalTokenUtil": "0x335408Ca7f0258427F99eF2457291583B55d757c"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"uint256","name":"i","type":"uint256"},{"internalType":"uint256","name":"j","type":"uint256"}],"name":"InvalidTokenIndex","type":"error"},{"inputs":[],"name":"MathOverflowedMulDiv","type":"error"},{"inputs":[],"name":"PoolLiquidityError","type":"error"},{"inputs":[],"name":"ResultNotFound","type":"error"},{"inputs":[{"internalType":"int256","name":"value","type":"int256"}],"name":"SafeCastOverflowedIntToUint","type":"error"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintToInt","type":"error"},{"inputs":[],"name":"UnsufficientAmountForFlashFee","type":"error"},{"inputs":[{"internalType":"uint256","name":"_inputIBTAmount","type":"uint256"},{"internalType":"address","name":"_curvePool","type":"address"}],"name":"convertIBTToYTSpot","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_pt","type":"address"}],"name":"getPTUnderlyingUnit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"getUnit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256[2]","name":"_amounts","type":"uint256[2]"}],"name":"previewAddLiquidity","outputs":[{"internalType":"uint256","name":"minMintAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_assets","type":"uint256"}],"name":"previewAddLiquidityWithAsset","outputs":[{"internalType":"uint256","name":"minMintAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_ibts","type":"uint256"}],"name":"previewAddLiquidityWithIBT","outputs":[{"internalType":"uint256","name":"minMintAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_inputIBTAmount","type":"uint256"}],"name":"previewFlashSwapExactIBTToYT","outputs":[{"internalType":"uint256","name":"ytAmount","type":"uint256"},{"internalType":"uint256","name":"borrowedIBTAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"inputYTAmount","type":"uint256"}],"name":"previewFlashSwapExactYTToIBT","outputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_outputYTAmount","type":"uint256"}],"name":"previewFlashSwapIBTToExactYT","outputs":[{"internalType":"uint256","name":"inputIBTAmount","type":"uint256"},{"internalType":"uint256","name":"borrowedIBTAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_lpAmount","type":"uint256"}],"name":"previewRemoveLiquidity","outputs":[{"internalType":"uint256[2]","name":"minAmounts","type":"uint256[2]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_lpAmount","type":"uint256"}],"name":"previewRemoveLiquidityForAsset","outputs":[{"internalType":"uint256","name":"assets","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_lpAmount","type":"uint256"}],"name":"previewRemoveLiquidityForIBT","outputs":[{"internalType":"uint256","name":"ibts","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_lpAmount","type":"uint256"},{"internalType":"uint256","name":"_i","type":"uint256"}],"name":"previewRemoveLiquidityOneCoin","outputs":[{"internalType":"uint256","name":"minAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_curvePool","type":"address"},{"internalType":"uint256","name":"_i","type":"uint256"},{"internalType":"uint256","name":"_j","type":"uint256"}],"name":"spotExchangeRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

608060405234801561000f575f80fd5b50611d1c8061001d5f395ff3fe608060405234801561000f575f80fd5b50600436106100e5575f3560e01c80636b0426cb11610088578063a3284ec811610063578063a3284ec8146101dc578063b03ae381146101ef578063d0a3fcb414610202578063f8fc815c14610215575f80fd5b80636b0426cb146101a35780637441de6a146101b6578063794b4044146101c9575f80fd5b80632fee2f09116100c35780632fee2f09146101355780635fa5a49714610148578063625aefd21461015b5780636525e5f114610183575f80fd5b80630d029aa5146100e95780630f9c83281461010f5780632271e1f814610122575b5f80fd5b6100fc6100f736600461187f565b610228565b6040519081526020015b60405180910390f35b6100fc61011d3660046118de565b61046d565b6100fc61013036600461194e565b6104ee565b6100fc610143366004611980565b610620565b6100fc6101563660046119ae565b6107bd565b61016e61016936600461187f565b610829565b60408051928352602083019190915201610106565b61019661019136600461187f565b610b2d565b60405161010691906119c9565b6100fc6101b136600461187f565b610bb5565b61016e6101c436600461187f565b610ca1565b6100fc6101d736600461194e565b610f5b565b6100fc6101ea36600461187f565b610fe5565b61016e6101fd36600461187f565b611152565b6100fc61021036600461187f565b61147f565b6100fc6102233660046119ae565b61161c565b604051636525e5f160e01b81526001600160a01b0383166004820152602481018290525f90819073e6c69dd9c450406c3e4383431bae36b7b6ae018c90636525e5f1906044016040805180830381865af4158015610288573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102ac91906119f9565b60405163c661065760e01b8152600160048201529091506001600160a01b0385169063c661065790602401602060405180830381865afa1580156102f2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103169190611a55565b6001600160a01b0316634cdad50682600160200201516040518263ffffffff1660e01b815260040161034a91815260200190565b602060405180830381865afa158015610365573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103899190611a70565b60405163c661065760e01b81525f60048201526001600160a01b0386169063c661065790602401602060405180830381865afa1580156103cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103ef9190611a55565b825160405163266d6a8360e11b815260048101919091526001600160a01b039190911690634cdad50690602401602060405180830381865afa158015610437573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061045b9190611a70565b6104659190611a9b565b949350505050565b6040516301f3906560e31b81525f9073e6c69dd9c450406c3e4383431bae36b7b6ae018c90630f9c8328906104a89086908690600401611aae565b602060405180830381865af41580156104c3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104e79190611a70565b9392505050565b5f821580156104fd5750816001145b156105855761057e670de0b6b3a7640000856001600160a01b031663c146bf946040518163ffffffff1660e01b8152600401602060405180830381865afa15801561054a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061056e9190611a70565b670de0b6b3a7640000919061165c565b90506104e7565b826001148015610593575081155b156105f857836001600160a01b031663c146bf946040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105d4573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061057e9190611a70565b60405163175ebd2b60e11b815260048101849052602481018390526044015b60405180910390fd5b60405163c661065760e01b8152600160048201525f9081906001600160a01b0384169063c661065790602401602060405180830381865afa158015610667573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068b9190611a55565b90505f816001600160a01b031663efd98dc26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106ca573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106ee9190611a70565b90505f826001600160a01b031663a1c5b3e16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561072d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107519190611a70565b90505f61077483670de0b6b3a764000061076d8960015f6104ee565b919061165c565b9050818111156107975760405163202f312b60e21b815260040160405180910390fd5b5f6107a28284611aee565b90506107af88858361165c565b955050505050505b92915050565b5f816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107fa573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061081e9190611b01565b6107b790600a611c01565b60405163c661065760e01b8152600160048201525f90819081906001600160a01b0386169063c661065790602401602060405180830381865afa158015610872573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108969190611a55565b90505f816001600160a01b031663c644fe946040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108f99190611a55565b90505f826001600160a01b031663efd98dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610938573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061095c9190611a70565b90505f836001600160a01b031663a1c5b3e16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561099b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109bf9190611a70565b60405163556d6e9f60e01b8152600160048201525f60248201819052604482018a90529192506001600160a01b038a169063556d6e9f90606401602060405180830381865afa158015610a14573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a389190611a70565b9050610adc856001600160a01b031663abfa94466040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a9d9190611a70565b610aaf90670de0b6b3a7640000611aee565b610ab99085611c0f565b670de0b6b3a7640000610acc858c611c0f565b610ad69190611c0f565b9061171b565b955085811115610aff5760405163202f312b60e21b815260040160405180910390fd5b80610b0b868689611768565b610b159088611a9b565b610b1f9190611aee565b965050505050509250929050565b610b3561184a565b604051636525e5f160e01b81526001600160a01b03841660048201526024810183905273e6c69dd9c450406c3e4383431bae36b7b6ae018c90636525e5f1906044016040805180830381865af4158015610b91573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104e791906119f9565b60405163c661065760e01b81525f600482018190529081906001600160a01b0385169063c661065790602401602060405180830381865afa158015610bfc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c209190611a55565b60405163ef8b30f760e01b8152600481018590529091505f906001600160a01b0383169063ef8b30f790602401602060405180830381865afa158015610c68573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c8c9190611a70565b9050610c98858261147f565b95945050505050565b60405163c661065760e01b8152600160048201525f90819081906001600160a01b0386169063c661065790602401602060405180830381865afa158015610cea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0e9190611a55565b90505f816001600160a01b031663c644fe946040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d4d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d719190611a55565b90505f826001600160a01b031663efd98dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610db0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610dd49190611a70565b90505f836001600160a01b031663a1c5b3e16040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e13573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e379190611a70565b604051631990812560e31b81526001600160a01b038a1660048201525f6024820181905260016044830152606482018a905291925073e6c69dd9c450406c3e4383431bae36b7b6ae018c9063cc84092890608401602060405180830381865af4158015610ea6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610eca9190611a70565b90505f610ed889848661165c565b90505f610ee6878785611768565b905081831115610f095760405163202f312b60e21b815260040160405180910390fd5b81610f148285611a9b565b1115610f3357604051638a7ceb6f60e01b815260040160405180910390fd5b5f81610f3f8585611aee565b610f499190611aee565b9c939b50929950505050505050505050565b604051631e52d01160e21b81526001600160a01b038416600482015260248101839052604481018290525f9073e6c69dd9c450406c3e4383431bae36b7b6ae018c9063794b404490606401602060405180830381865af4158015610fc1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104659190611a70565b604051636525e5f160e01b81526001600160a01b0383166004820152602481018290525f90819073e6c69dd9c450406c3e4383431bae36b7b6ae018c90636525e5f1906044016040805180830381865af4158015611045573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061106991906119f9565b60405163c661065760e01b8152600160048201529091506001600160a01b0385169063c661065790602401602060405180830381865afa1580156110af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110d39190611a55565b6001600160a01b03166368c1f7f682600160200201516040518263ffffffff1660e01b815260040161110791815260200190565b602060405180830381865afa158015611122573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111469190611a70565b81516104659190611a9b565b5f805f6111c5856001600160a01b031663c66106575f6040518263ffffffff1660e01b815260040161118691815260200190565b602060405180830381865afa1580156111a1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101569190611a55565b60405163c661065760e01b8152600160048201529091505f906001600160a01b0387169063c661065790602401602060405180830381865afa15801561120d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112319190611a55565b6040516302f6fa9560e11b8152600481018790529091505f906001600160a01b038316906305edf52a90602401602060405180830381865afa158015611279573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061129d9190611a70565b90505f6112aa8789610620565b90505f5b60ff8110156113bb576112c36103e886611c3a565b6112db866112d186866117b6565b61076d87876117cb565b106113bb575f6112eb8a85610829565b5090505f6112f98b85610829565b5090505f6113068b6117e7565b61130f846117e7565b6113199190611c4d565b90505f6113258c6117e7565b61132e846117e7565b6113389190611c4d565b905080820361134a57505050506113bb565b5f6113a06113588484611c4d565b6113618a6117e7565b61136a8a6117e7565b6113749190611c4d565b61137e9085611c73565b6113889190611ca2565b611391896117e7565b61139b9190611c4d565b611817565b9697506113b49450859350611cce92505050565b90506112ae565b506113c6828261183c565b95505f6113d38988610829565b965090508781111561142f57620f42405f5b60ff81101561142c576114046113fc600184611aee565b8a908461165c565b98506114108b8a610829565b985092508983111561142c5761142581611cce565b90506113e5565b50505b8781118061145557506114446103e886611c3a565b611453868a61076d8c866117cb565b115b1561147357604051635aae0c9960e11b815260040160405180910390fd5b50505050509250929050565b60405163c661065760e01b8152600160048201525f9081906001600160a01b0385169063c661065790602401602060405180830381865afa1580156114c6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114ea9190611a55565b60405163fbfc779760e01b8152600481018590526001600160a01b038087166024830152821660448201529091505f9073e6c69dd9c450406c3e4383431bae36b7b6ae018c9063fbfc779790606401602060405180830381865af4158015611554573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115789190611a70565b90505f6115858286611aee565b6040516302f6fa9560e11b8152600481018490529091505f906001600160a01b038516906305edf52a90602401602060405180830381865afa1580156115cd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115f19190611a70565b90506116118760405180604001604052808581526020018481525061046d565b979650505050505050565b5f6107b7826001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111a1573d5f803e3d5ffd5b5f838302815f1985870982811083820303915050805f036116905783828161168657611686611c26565b04925050506104e7565b8084116116b05760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f815f036117345761172d8284611c3a565b90506107b7565b82156117605781611746600185611aee565b6117509190611c3a565b61175b906001611a9b565b6104e7565b505f92915050565b604051633676633960e21b81526001600160a01b038381166004830152602482018390525f919085169063d9d98ce490604401602060405180830381865afa158015610fc1573d5f803e3d5ffd5b5f8183116117c457816104e7565b5090919050565b5f8183116117dd5761175b8383611aee565b6104e78284611aee565b5f6001600160ff1b038211156118135760405163123baf0360e11b815260048101839052602401610617565b5090565b5f8082121561181357604051635467221960e11b815260048101839052602401610617565b5f8183106117c457816104e7565b60405180604001604052806002906020820280368337509192915050565b6001600160a01b038116811461187c575f80fd5b50565b5f8060408385031215611890575f80fd5b823561189b81611868565b946020939093013593505050565b6040805190810167ffffffffffffffff811182821017156118d857634e487b7160e01b5f52604160045260245ffd5b60405290565b5f80606083850312156118ef575f80fd5b82356118fa81611868565b91506020603f8401851361190c575f80fd5b6119146118a9565b806060860187811115611925575f80fd5b8387015b818110156119405780358452928401928401611929565b509497909650945050505050565b5f805f60608486031215611960575f80fd5b833561196b81611868565b95602085013595506040909401359392505050565b5f8060408385031215611991575f80fd5b8235915060208301356119a381611868565b809150509250929050565b5f602082840312156119be575f80fd5b81356104e781611868565b6040810181835f5b60028110156119f05781518352602092830192909101906001016119d1565b50505092915050565b5f60408284031215611a09575f80fd5b82601f830112611a17575f80fd5b611a1f6118a9565b806040840185811115611a30575f80fd5b845b81811015611a4a578051845260209384019301611a32565b509095945050505050565b5f60208284031215611a65575f80fd5b81516104e781611868565b5f60208284031215611a80575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b808201808211156107b7576107b7611a87565b6001600160a01b0383168152606081016020808301845f5b6002811015611ae357815183529183019190830190600101611ac6565b505050509392505050565b818103818111156107b7576107b7611a87565b5f60208284031215611b11575f80fd5b815160ff811681146104e7575f80fd5b600181815b80851115611b5b57815f1904821115611b4157611b41611a87565b80851615611b4e57918102915b93841c9390800290611b26565b509250929050565b5f82611b71575060016107b7565b81611b7d57505f6107b7565b8160018114611b935760028114611b9d57611bb9565b60019150506107b7565b60ff841115611bae57611bae611a87565b50506001821b6107b7565b5060208310610133831016604e8410600b8410161715611bdc575081810a6107b7565b611be68383611b21565b805f1904821115611bf957611bf9611a87565b029392505050565b5f6104e760ff841683611b63565b80820281158282048414176107b7576107b7611a87565b634e487b7160e01b5f52601260045260245ffd5b5f82611c4857611c48611c26565b500490565b8181035f831280158383131683831282161715611c6c57611c6c611a87565b5092915050565b8082025f8212600160ff1b84141615611c8e57611c8e611a87565b81810583148215176107b7576107b7611a87565b5f82611cb057611cb0611c26565b600160ff1b82145f1984141615611cc957611cc9611a87565b500590565b5f60018201611cdf57611cdf611a87565b506001019056fea2646970667358221220e3dccd06ff5c344a7cb060b7bda21547dd8d9dc8f3b9737b6e42497f907ee0fa64736f6c63430008140033

Deployed Bytecode

0x608060405234801561000f575f80fd5b50600436106100e5575f3560e01c80636b0426cb11610088578063a3284ec811610063578063a3284ec8146101dc578063b03ae381146101ef578063d0a3fcb414610202578063f8fc815c14610215575f80fd5b80636b0426cb146101a35780637441de6a146101b6578063794b4044146101c9575f80fd5b80632fee2f09116100c35780632fee2f09146101355780635fa5a49714610148578063625aefd21461015b5780636525e5f114610183575f80fd5b80630d029aa5146100e95780630f9c83281461010f5780632271e1f814610122575b5f80fd5b6100fc6100f736600461187f565b610228565b6040519081526020015b60405180910390f35b6100fc61011d3660046118de565b61046d565b6100fc61013036600461194e565b6104ee565b6100fc610143366004611980565b610620565b6100fc6101563660046119ae565b6107bd565b61016e61016936600461187f565b610829565b60408051928352602083019190915201610106565b61019661019136600461187f565b610b2d565b60405161010691906119c9565b6100fc6101b136600461187f565b610bb5565b61016e6101c436600461187f565b610ca1565b6100fc6101d736600461194e565b610f5b565b6100fc6101ea36600461187f565b610fe5565b61016e6101fd36600461187f565b611152565b6100fc61021036600461187f565b61147f565b6100fc6102233660046119ae565b61161c565b604051636525e5f160e01b81526001600160a01b0383166004820152602481018290525f90819073e6c69dd9c450406c3e4383431bae36b7b6ae018c90636525e5f1906044016040805180830381865af4158015610288573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906102ac91906119f9565b60405163c661065760e01b8152600160048201529091506001600160a01b0385169063c661065790602401602060405180830381865afa1580156102f2573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103169190611a55565b6001600160a01b0316634cdad50682600160200201516040518263ffffffff1660e01b815260040161034a91815260200190565b602060405180830381865afa158015610365573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103899190611a70565b60405163c661065760e01b81525f60048201526001600160a01b0386169063c661065790602401602060405180830381865afa1580156103cb573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103ef9190611a55565b825160405163266d6a8360e11b815260048101919091526001600160a01b039190911690634cdad50690602401602060405180830381865afa158015610437573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061045b9190611a70565b6104659190611a9b565b949350505050565b6040516301f3906560e31b81525f9073e6c69dd9c450406c3e4383431bae36b7b6ae018c90630f9c8328906104a89086908690600401611aae565b602060405180830381865af41580156104c3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104e79190611a70565b9392505050565b5f821580156104fd5750816001145b156105855761057e670de0b6b3a7640000856001600160a01b031663c146bf946040518163ffffffff1660e01b8152600401602060405180830381865afa15801561054a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061056e9190611a70565b670de0b6b3a7640000919061165c565b90506104e7565b826001148015610593575081155b156105f857836001600160a01b031663c146bf946040518163ffffffff1660e01b8152600401602060405180830381865afa1580156105d4573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061057e9190611a70565b60405163175ebd2b60e11b815260048101849052602481018390526044015b60405180910390fd5b60405163c661065760e01b8152600160048201525f9081906001600160a01b0384169063c661065790602401602060405180830381865afa158015610667573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061068b9190611a55565b90505f816001600160a01b031663efd98dc26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106ca573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106ee9190611a70565b90505f826001600160a01b031663a1c5b3e16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561072d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107519190611a70565b90505f61077483670de0b6b3a764000061076d8960015f6104ee565b919061165c565b9050818111156107975760405163202f312b60e21b815260040160405180910390fd5b5f6107a28284611aee565b90506107af88858361165c565b955050505050505b92915050565b5f816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156107fa573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061081e9190611b01565b6107b790600a611c01565b60405163c661065760e01b8152600160048201525f90819081906001600160a01b0386169063c661065790602401602060405180830381865afa158015610872573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108969190611a55565b90505f816001600160a01b031663c644fe946040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108d5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108f99190611a55565b90505f826001600160a01b031663efd98dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610938573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061095c9190611a70565b90505f836001600160a01b031663a1c5b3e16040518163ffffffff1660e01b8152600401602060405180830381865afa15801561099b573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109bf9190611a70565b60405163556d6e9f60e01b8152600160048201525f60248201819052604482018a90529192506001600160a01b038a169063556d6e9f90606401602060405180830381865afa158015610a14573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a389190611a70565b9050610adc856001600160a01b031663abfa94466040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a79573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a9d9190611a70565b610aaf90670de0b6b3a7640000611aee565b610ab99085611c0f565b670de0b6b3a7640000610acc858c611c0f565b610ad69190611c0f565b9061171b565b955085811115610aff5760405163202f312b60e21b815260040160405180910390fd5b80610b0b868689611768565b610b159088611a9b565b610b1f9190611aee565b965050505050509250929050565b610b3561184a565b604051636525e5f160e01b81526001600160a01b03841660048201526024810183905273e6c69dd9c450406c3e4383431bae36b7b6ae018c90636525e5f1906044016040805180830381865af4158015610b91573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104e791906119f9565b60405163c661065760e01b81525f600482018190529081906001600160a01b0385169063c661065790602401602060405180830381865afa158015610bfc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c209190611a55565b60405163ef8b30f760e01b8152600481018590529091505f906001600160a01b0383169063ef8b30f790602401602060405180830381865afa158015610c68573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610c8c9190611a70565b9050610c98858261147f565b95945050505050565b60405163c661065760e01b8152600160048201525f90819081906001600160a01b0386169063c661065790602401602060405180830381865afa158015610cea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0e9190611a55565b90505f816001600160a01b031663c644fe946040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d4d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d719190611a55565b90505f826001600160a01b031663efd98dc26040518163ffffffff1660e01b8152600401602060405180830381865afa158015610db0573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610dd49190611a70565b90505f836001600160a01b031663a1c5b3e16040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e13573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e379190611a70565b604051631990812560e31b81526001600160a01b038a1660048201525f6024820181905260016044830152606482018a905291925073e6c69dd9c450406c3e4383431bae36b7b6ae018c9063cc84092890608401602060405180830381865af4158015610ea6573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610eca9190611a70565b90505f610ed889848661165c565b90505f610ee6878785611768565b905081831115610f095760405163202f312b60e21b815260040160405180910390fd5b81610f148285611a9b565b1115610f3357604051638a7ceb6f60e01b815260040160405180910390fd5b5f81610f3f8585611aee565b610f499190611aee565b9c939b50929950505050505050505050565b604051631e52d01160e21b81526001600160a01b038416600482015260248101839052604481018290525f9073e6c69dd9c450406c3e4383431bae36b7b6ae018c9063794b404490606401602060405180830381865af4158015610fc1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104659190611a70565b604051636525e5f160e01b81526001600160a01b0383166004820152602481018290525f90819073e6c69dd9c450406c3e4383431bae36b7b6ae018c90636525e5f1906044016040805180830381865af4158015611045573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061106991906119f9565b60405163c661065760e01b8152600160048201529091506001600160a01b0385169063c661065790602401602060405180830381865afa1580156110af573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110d39190611a55565b6001600160a01b03166368c1f7f682600160200201516040518263ffffffff1660e01b815260040161110791815260200190565b602060405180830381865afa158015611122573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111469190611a70565b81516104659190611a9b565b5f805f6111c5856001600160a01b031663c66106575f6040518263ffffffff1660e01b815260040161118691815260200190565b602060405180830381865afa1580156111a1573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101569190611a55565b60405163c661065760e01b8152600160048201529091505f906001600160a01b0387169063c661065790602401602060405180830381865afa15801561120d573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112319190611a55565b6040516302f6fa9560e11b8152600481018790529091505f906001600160a01b038316906305edf52a90602401602060405180830381865afa158015611279573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061129d9190611a70565b90505f6112aa8789610620565b90505f5b60ff8110156113bb576112c36103e886611c3a565b6112db866112d186866117b6565b61076d87876117cb565b106113bb575f6112eb8a85610829565b5090505f6112f98b85610829565b5090505f6113068b6117e7565b61130f846117e7565b6113199190611c4d565b90505f6113258c6117e7565b61132e846117e7565b6113389190611c4d565b905080820361134a57505050506113bb565b5f6113a06113588484611c4d565b6113618a6117e7565b61136a8a6117e7565b6113749190611c4d565b61137e9085611c73565b6113889190611ca2565b611391896117e7565b61139b9190611c4d565b611817565b9697506113b49450859350611cce92505050565b90506112ae565b506113c6828261183c565b95505f6113d38988610829565b965090508781111561142f57620f42405f5b60ff81101561142c576114046113fc600184611aee565b8a908461165c565b98506114108b8a610829565b985092508983111561142c5761142581611cce565b90506113e5565b50505b8781118061145557506114446103e886611c3a565b611453868a61076d8c866117cb565b115b1561147357604051635aae0c9960e11b815260040160405180910390fd5b50505050509250929050565b60405163c661065760e01b8152600160048201525f9081906001600160a01b0385169063c661065790602401602060405180830381865afa1580156114c6573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114ea9190611a55565b60405163fbfc779760e01b8152600481018590526001600160a01b038087166024830152821660448201529091505f9073e6c69dd9c450406c3e4383431bae36b7b6ae018c9063fbfc779790606401602060405180830381865af4158015611554573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115789190611a70565b90505f6115858286611aee565b6040516302f6fa9560e11b8152600481018490529091505f906001600160a01b038516906305edf52a90602401602060405180830381865afa1580156115cd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115f19190611a70565b90506116118760405180604001604052808581526020018481525061046d565b979650505050505050565b5f6107b7826001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111a1573d5f803e3d5ffd5b5f838302815f1985870982811083820303915050805f036116905783828161168657611686611c26565b04925050506104e7565b8084116116b05760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f815f036117345761172d8284611c3a565b90506107b7565b82156117605781611746600185611aee565b6117509190611c3a565b61175b906001611a9b565b6104e7565b505f92915050565b604051633676633960e21b81526001600160a01b038381166004830152602482018390525f919085169063d9d98ce490604401602060405180830381865afa158015610fc1573d5f803e3d5ffd5b5f8183116117c457816104e7565b5090919050565b5f8183116117dd5761175b8383611aee565b6104e78284611aee565b5f6001600160ff1b038211156118135760405163123baf0360e11b815260048101839052602401610617565b5090565b5f8082121561181357604051635467221960e11b815260048101839052602401610617565b5f8183106117c457816104e7565b60405180604001604052806002906020820280368337509192915050565b6001600160a01b038116811461187c575f80fd5b50565b5f8060408385031215611890575f80fd5b823561189b81611868565b946020939093013593505050565b6040805190810167ffffffffffffffff811182821017156118d857634e487b7160e01b5f52604160045260245ffd5b60405290565b5f80606083850312156118ef575f80fd5b82356118fa81611868565b91506020603f8401851361190c575f80fd5b6119146118a9565b806060860187811115611925575f80fd5b8387015b818110156119405780358452928401928401611929565b509497909650945050505050565b5f805f60608486031215611960575f80fd5b833561196b81611868565b95602085013595506040909401359392505050565b5f8060408385031215611991575f80fd5b8235915060208301356119a381611868565b809150509250929050565b5f602082840312156119be575f80fd5b81356104e781611868565b6040810181835f5b60028110156119f05781518352602092830192909101906001016119d1565b50505092915050565b5f60408284031215611a09575f80fd5b82601f830112611a17575f80fd5b611a1f6118a9565b806040840185811115611a30575f80fd5b845b81811015611a4a578051845260209384019301611a32565b509095945050505050565b5f60208284031215611a65575f80fd5b81516104e781611868565b5f60208284031215611a80575f80fd5b5051919050565b634e487b7160e01b5f52601160045260245ffd5b808201808211156107b7576107b7611a87565b6001600160a01b0383168152606081016020808301845f5b6002811015611ae357815183529183019190830190600101611ac6565b505050509392505050565b818103818111156107b7576107b7611a87565b5f60208284031215611b11575f80fd5b815160ff811681146104e7575f80fd5b600181815b80851115611b5b57815f1904821115611b4157611b41611a87565b80851615611b4e57918102915b93841c9390800290611b26565b509250929050565b5f82611b71575060016107b7565b81611b7d57505f6107b7565b8160018114611b935760028114611b9d57611bb9565b60019150506107b7565b60ff841115611bae57611bae611a87565b50506001821b6107b7565b5060208310610133831016604e8410600b8410161715611bdc575081810a6107b7565b611be68383611b21565b805f1904821115611bf957611bf9611a87565b029392505050565b5f6104e760ff841683611b63565b80820281158282048414176107b7576107b7611a87565b634e487b7160e01b5f52601260045260245ffd5b5f82611c4857611c48611c26565b500490565b8181035f831280158383131683831282161715611c6c57611c6c611a87565b5092915050565b8082025f8212600160ff1b84141615611c8e57611c8e611a87565b81810583148215176107b7576107b7611a87565b5f82611cb057611cb0611c26565b600160ff1b82145f1984141615611cc957611cc9611a87565b500590565b5f60018201611cdf57611cdf611a87565b506001019056fea2646970667358221220e3dccd06ff5c344a7cb060b7bda21547dd8d9dc8f3b9737b6e42497f907ee0fa64736f6c63430008140033

Block Transaction Gas Used Reward
view all blocks produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.