ETH Price: $4,017.57 (+2.83%)

Contract

0xa5fC5A373D66C109f68006A60434D3e798EcF3c6

Overview

ETH Balance

0 ETH

ETH Value

$0.00

More Info

Private Name Tags

Multichain Info

N/A
Transaction Hash
Method
Block
From
To
Packed Transmit ...119851032025-09-24 15:31:542 days ago1758727914IN
0xa5fC5A37...798EcF3c6
0 ETH0.000001350.00000026
Burn To Withdraw71725992025-07-30 22:43:3057 days ago1753915410IN
0xa5fC5A37...798EcF3c6
0 ETH0.000001350.00000026
Unlock Deposit71725762025-07-30 22:43:0757 days ago1753915387IN
0xa5fC5A37...798EcF3c6
0 ETH0.000001350.00000026
Unlock Deposit56806772025-07-13 16:18:0875 days ago1752423488IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000207
Withdraw Single ...56806632025-07-13 16:17:5475 days ago1752423474IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000215
Withdraw Single ...56226082025-07-13 0:10:1975 days ago1752365419IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000719
Packed Transmit ...56225762025-07-13 0:09:4775 days ago1752365387IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000773
Unlock Deposit56084402025-07-12 20:14:1176 days ago1752351251IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000342
Transmit And Dep...56076532025-07-12 20:01:0476 days ago1752350464IN
0xa5fC5A37...798EcF3c6
0 ETH00.00001815
Burn To Withdraw56076042025-07-12 20:00:1576 days ago1752350415IN
0xa5fC5A37...798EcF3c6
0 ETH00.00001396
Burn To Withdraw56067902025-07-12 19:46:4176 days ago1752349601IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000268
Transmit And Dep...55492112025-07-12 3:47:0276 days ago1752292022IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000235
Unlock Deposit55491982025-07-12 3:46:4976 days ago1752292009IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000251
Transmit And Dep...54749212025-07-11 7:08:5277 days ago1752217732IN
0xa5fC5A37...798EcF3c6
0 ETH0.000000020.00000152
Unlock Deposit54749142025-07-11 7:08:4577 days ago1752217725IN
0xa5fC5A37...798EcF3c6
0 ETH0.000000010.00000155
Packed Transmit ...54548552025-07-11 1:34:2677 days ago1752197666IN
0xa5fC5A37...798EcF3c6
0.002 ETH0.000000010.00000775
Unlock Deposit45115472025-06-30 3:32:3888 days ago1751254358IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
Packed Transmit ...45108932025-06-30 3:21:4488 days ago1751253704IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
Unlock Deposit45107602025-06-30 3:19:3188 days ago1751253571IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
Packed Transmit ...45101132025-06-30 3:08:4488 days ago1751252924IN
0xa5fC5A37...798EcF3c6
0.01 ETH00.00000025
Burn To Withdraw45100492025-06-30 3:07:4088 days ago1751252860IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
Unlock Deposit45100142025-06-30 3:07:0588 days ago1751252825IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
Packed Transmit ...45067182025-06-30 2:12:0988 days ago1751249529IN
0xa5fC5A37...798EcF3c6
0 ETH0.000000210.00115028
Transmit And Dep...45038602025-06-30 1:24:3188 days ago1751246671IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
Burn To Withdraw45037092025-06-30 1:22:0088 days ago1751246520IN
0xa5fC5A37...798EcF3c6
0 ETH00.00000025
View all transactions

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
121707562025-09-26 19:06:072 hrs ago1758913567
0xa5fC5A37...798EcF3c6
0 ETH
121707562025-09-26 19:06:072 hrs ago1758913567
0xa5fC5A37...798EcF3c6
0 ETH
121707562025-09-26 19:06:072 hrs ago1758913567
0xa5fC5A37...798EcF3c6
0 ETH
121707562025-09-26 19:06:072 hrs ago1758913567
0xa5fC5A37...798EcF3c6
0 ETH
121707562025-09-26 19:06:072 hrs ago1758913567
0xa5fC5A37...798EcF3c6
0 ETH
121707562025-09-26 19:06:072 hrs ago1758913567
0xa5fC5A37...798EcF3c6
0 ETH
121678692025-09-26 18:18:003 hrs ago1758910680
0xa5fC5A37...798EcF3c6
0 ETH
121678692025-09-26 18:18:003 hrs ago1758910680
0xa5fC5A37...798EcF3c6
0 ETH
121678692025-09-26 18:18:003 hrs ago1758910680
0xa5fC5A37...798EcF3c6
0 ETH
121678692025-09-26 18:18:003 hrs ago1758910680
0xa5fC5A37...798EcF3c6
0 ETH
121678692025-09-26 18:18:003 hrs ago1758910680
0xa5fC5A37...798EcF3c6
0 ETH
121678692025-09-26 18:18:003 hrs ago1758910680
0xa5fC5A37...798EcF3c6
0 ETH
121664762025-09-26 17:54:473 hrs ago1758909287
0xa5fC5A37...798EcF3c6
0 ETH
121664762025-09-26 17:54:473 hrs ago1758909287
0xa5fC5A37...798EcF3c6
0 ETH
121664762025-09-26 17:54:473 hrs ago1758909287
0xa5fC5A37...798EcF3c6
0 ETH
121664762025-09-26 17:54:473 hrs ago1758909287
0xa5fC5A37...798EcF3c6
0 ETH
121664762025-09-26 17:54:473 hrs ago1758909287
0xa5fC5A37...798EcF3c6
0 ETH
121664762025-09-26 17:54:473 hrs ago1758909287
0xa5fC5A37...798EcF3c6
0 ETH
121661342025-09-26 17:49:053 hrs ago1758908945
0xa5fC5A37...798EcF3c6
0 ETH
121661342025-09-26 17:49:053 hrs ago1758908945
0xa5fC5A37...798EcF3c6
0 ETH
121661342025-09-26 17:49:053 hrs ago1758908945
0xa5fC5A37...798EcF3c6
0 ETH
121661342025-09-26 17:49:053 hrs ago1758908945
0xa5fC5A37...798EcF3c6
0 ETH
121661342025-09-26 17:49:053 hrs ago1758908945
0xa5fC5A37...798EcF3c6
0 ETH
121661342025-09-26 17:49:053 hrs ago1758908945
0xa5fC5A37...798EcF3c6
0 ETH
121646452025-09-26 17:24:164 hrs ago1758907456
0xa5fC5A37...798EcF3c6
0 ETH
View All Internal Transactions

Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
BladeVerifiedExchange

Compiler Version
v0.8.28+commit.7893614a

Optimization Enabled:
Yes with 800 runs

Other Settings:
paris EvmVersion
File 1 of 65 : BladeVerifiedExchange.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SD59x18, sd} from "@prb/math/src/SD59x18.sol";

import "../base/BladeErrors.sol";
import {Constants} from "../base/Constants.sol";
import {Signature, UtilStruct} from "../types/BladeTypes.sol";
import {BladeCommonExchange} from "../base/BladeCommonExchange.sol";
import {OracleManager} from "../variants/OracleManager.sol";
import {SafeAggregatorInterface, AggregatorV3Interface} from "../libraries/SafeAggregatorInterface.sol";
import {WrapperContractInterface} from "../interfaces/WrapperContractInterface.sol";
import {BladeSignatureLib} from "../libraries/BladeSignatureLib.sol";

contract BladeVerifiedExchange is BladeCommonExchange, OracleManager {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeCast for uint256;
    using SafeCast for int256;

    // For prevention of replay attacks
    mapping(bytes32 => bool) invalidatedDigests;

    error DigestAlreadyUsed();

    constructor(
        address theSigner,
        address theWrapper,
        address[] memory tokens,
        address[] memory _oracles,
        uint256[] memory minTimeTolerances,
        address initialOwner
    )
        BladeCommonExchange(theSigner, theWrapper, tokens, initialOwner)
        OracleManager(tokens, _oracles, minTimeTolerances)
    {}

    function _isToken(address token) internal view override returns (bool) {
        return isToken(token);
    }

    function _nTokens() internal view override returns (uint) {
        return nTokens();
    }

    function _tokenAt(uint index) internal view override returns (address) {
        return tokenAt(index);
    }

    function _getLastBalance(address token) internal view override returns (uint256) {
        return getLastBalance(token);
    }

    function _getTokenDecimals(address token) internal view override returns (uint8) {
        return tokenDecimals[token];
    }

    // Used to invalidate a signature digest
    function _checkAndInvalidateDigest(bytes32 theDigest) private {
        if (invalidatedDigests[theDigest]) {
            revert DigestAlreadyUsed();
        }

        invalidatedDigests[theDigest] = true;
    }

    function _unpackGoodUntil(
        uint256 packedGoodUntil
    )
        private pure
        returns (
            uint256 pX,
            uint256 pY,
            uint256 wX,
            uint256 wY,
            uint256 k
        )
    {
        /*
        * Input asset price in 8 decimals - uint64
        * Output asset price in 8 decimals - uint64
        * k value in 18 decimals - uint64
        * Input asset weight - uint16
        * Output asset weight - uint16
        * Current good until value - uint32 - can be taken as uint256(uint32(packedGoodUntil))
        */
        // goodUntil = uint256(uint32(packedGoodUntil));
        packedGoodUntil = packedGoodUntil >> 32;
        wY = uint256(uint16(packedGoodUntil));
        packedGoodUntil = packedGoodUntil >> 16;
        wX = uint256(uint16(packedGoodUntil));
        packedGoodUntil = packedGoodUntil >> 16;
        k = uint256(uint64(packedGoodUntil));
        packedGoodUntil = packedGoodUntil >> 64;
        pY = uint256(uint64(packedGoodUntil));
        packedGoodUntil = packedGoodUntil >> 64;
        pX = uint256(uint64(packedGoodUntil));
    }

    /*
    Before calling:
    Set qX = lastBalances[inAsset];
    Set qY = lastBalances[outAsset];

    Multiply all quantities (q and in/out) by 10**(18-asset.decimals()).
    This puts all quantities in 18 decimals.

    Assumed decimals:
    K: 18
    Quantities: 18 (ONE_IN_DEFAULT_DECIMALS = 1e18)
    Prices: 8 (ONE_IN_PRICE_DECIMALS = 1e8)
    Weights: 0 (100 = 100)
    */
    function _swapIncreasesInvariant(
        uint256 inX,
        uint256 pX,
        uint256 qX,
        uint256 wX,
        uint256 outY,
        uint256 pY,
        uint256 qY,
        uint256 wY,
        uint256 k
    )
        private pure
        returns (bool)
    {
        uint256 invariantBefore;
        uint256 invariantAfter;
        {
            uint256 pqX = pX * qX / ONE_IN_PRICE_DECIMALS;
            uint256 pqwXk = _fractionalPow(pqX * wX, k);
            if (pqwXk > 0) {
                invariantBefore += (Constants.ONE_IN_DEFAULT_DECIMALS * pqX) / pqwXk;
            }

            uint256 pqY = pY * qY / ONE_IN_PRICE_DECIMALS;
            uint256 pqwYk = _fractionalPow(pqY * wY, k);
            if (pqwYk > 0) {
                invariantBefore += (Constants.ONE_IN_DEFAULT_DECIMALS * pqY) / pqwYk;
            }
        }
        {
            uint256 pqXinX = (pX * (qX + inX)) / ONE_IN_PRICE_DECIMALS;
            uint256 pqwXinXk = _fractionalPow(pqXinX * wX, k);
            if (pqwXinXk > 0) {
                invariantAfter += (Constants.ONE_IN_DEFAULT_DECIMALS * pqXinX) / pqwXinXk;
            }

            uint256 pqYoutY = pY * (qY - outY) / ONE_IN_PRICE_DECIMALS;
            uint256 pqwYoutYk = _fractionalPow(pqYoutY * wY, k);
            if (pqwYoutYk > 0) {
                invariantAfter += (Constants.ONE_IN_DEFAULT_DECIMALS * pqYoutY) / pqwYoutYk;
            }
        }
        return invariantAfter > invariantBefore;
    }

    function _fractionalPow(
        uint256 input,
        uint256 pow
    )
        private pure
        returns (uint256)
    {
        if (input == 0) {
            return 0;
        } else {
            // input^(pow/1e18) -> exp2( (pow * log2( input ) / 1e18 ) )

            // Convert input to SD59x18 and compute log2(input)
            SD59x18 log2Input = sd(input.toInt256()).log2();

            // Multiply by pow and divide by 1e18 to scale properly
            SD59x18 exponent = sd(pow.toInt256()).mul(log2Input).div(sd(int256(Constants.ONE_IN_DEFAULT_DECIMALS)));

            // Compute exp2() and safely convert int256 to uint256
            int256 resultInt = exponent.exp2().unwrap();

            return resultInt.toUint256();
        }
    }

    function _currentDeltaOverLastBalance(address token) private view returns (uint256) {
        return IERC20(token).balanceOf(address(this)) - lastBalances[token];
    }

    function _sync(address token) internal override {
        lastBalances[token] = IERC20(token).balanceOf(address(this));
    }

    function _syncAll() private {
        uint i;
        uint n = assetSet.length();
        while (i < n) {
            _sync(tokenAt(i));
            i++;
        }
    }

    // _syncAndTransfer() and _unwrapAndForwardEth() are the two additional ways tokens leave the pool
    // Since they transfer assets, they are all marked as nonReentrant
    function _syncAndTransfer(
        address inputToken,
        address outputToken,
        address recipient,
        uint256 amount
    )
        private
        nonReentrant
    {
        _sync(inputToken);
        IERC20(outputToken).safeTransfer(recipient, amount);
        _sync(outputToken);
    }

    // Essentially transferAsset, but for raw ETH
    function _unwrapAndForwardEth(address recipient, uint256 amount) private nonReentrant {
        /* EFFECTS */
        WrapperContractInterface(WRAPPER_CONTRACT).withdraw(amount);
        _sync(WRAPPER_CONTRACT);
        /* INTERACTIONS */
        safeEthSend(recipient, amount);
    }

    function _verifyTokensAndGetAmounts(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount
    )
        private view
        returns (
            uint256 actualInput,
            uint256 fairOutput
        )
    {
        if (!isToken(inputToken)) revert TokenNotInPool();
        if (!isToken(outputToken)) revert TokenNotInPool();

        actualInput = _currentDeltaOverLastBalance(inputToken);
        fairOutput = calculateFairOutput(inputAmount, actualInput, outputAmount);
    }

    function _swapValidation(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature memory theSignature
    )
        private
        returns (
            uint256 actualInput,
            uint256 fairOutput
        )
    {
        bytes32 digest = _verifySwapSignature(
            inputToken,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature
        );

        // Validate digest already used
        _checkAndInvalidateDigest(digest);

        (actualInput, fairOutput) = _verifyTokensAndGetAmounts(
            inputToken,
            outputToken,
            inputAmount,
            outputAmount
        );
        _unpackAndCheckInvariantAndPrice(
            inputToken,
            actualInput,
            outputToken,
            fairOutput,
            goodUntil
        );
    }

    function sellTokenForEth(
        address inputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    )
        external
        marketIsRunning
        receivedInTime(uint256(uint32(goodUntil)))
    {
        _sellTokenForEth(
            inputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature,
            auxiliaryData
        );
    }

    function _sellTokenForEth(
        address inputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature memory theSignature,
        bytes memory auxiliaryData
    )
        private
    {
        (uint256 actualInput, uint256 fairOutput) = _swapValidation(
            inputToken,
            WRAPPER_CONTRACT,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature
        );

        // We have to _sync the input token manually here
        _sync(inputToken);
        _unwrapAndForwardEth(destinationAddress, fairOutput);

        emit Swapped(
            inputToken,
            WRAPPER_CONTRACT,
            destinationAddress,
            actualInput,
            fairOutput,
            auxiliaryData
        );
    }

    function swap(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    )
        external
        marketIsRunning
        receivedInTime(uint256(uint32(goodUntil)))
    {
        _swap(
            inputToken,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature,
            auxiliaryData
        );
    }

    function _swap(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature memory theSignature,
        bytes memory auxiliaryData
    )
        private
    {
        (uint256 actualInput, uint256 fairOutput) = _swapValidation(
            inputToken,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature
        );

        // OK, now we are safe to transfer
        _syncAndTransfer(inputToken, outputToken, destinationAddress, fairOutput);
        emit Swapped(
            inputToken,
            outputToken,
            destinationAddress,
            actualInput,
            fairOutput,
            auxiliaryData
        );
    }

    // Oracle verification integration
    function deposit(
        address depositor,
        uint256[] calldata depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    )
        public payable override
        marketIsRunning
        receivedInTime(goodUntil)
        validLockTime(lockTime)
    {
        _deposit(
            depositor,
            depositAmounts,
            lockTime,
            poolTokens,
            goodUntil,
            theSignature,
            extraData
        );
    }

    function _deposit(
        address depositor,
        uint256[] memory depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature memory theSignature,
        bytes memory extraData
    )
        private
    {
        // wraps msg.value if existent as it will be used in the following checks
        _wrapMsgValue();

        bytes32 digest = _depositChecks(
            depositor,
            depositAmounts,
            lockTime,
            poolTokens,
            goodUntil,
            theSignature,
            extraData
        );

        // Validate digest already used
        _checkAndInvalidateDigest(digest);

        // Did we actually deposit what we said we would? Revert otherwise
        _verifyDepositAmountsWithOracles(depositAmounts, poolTokens);

        // OK now we're good
        _syncAll();
        _finalizeDeposit(depositor, lockTime, poolTokens);
    }

    // Oracle verification integration
    function depositSingleAsset(
        address depositor,
        address inputToken,
        uint256 inputAmount,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    )
        external payable
        marketIsRunning
        receivedInTime(goodUntil)
        validLockTime(lockTime)
    {
        _depositSingleAsset(
            depositor,
            inputToken,
            inputAmount,
            lockTime,
            poolTokens,
            goodUntil,
            theSignature,
            extraData
        );
    }

    function _depositSingleAsset(
        address depositor,
        address inputToken,
        uint256 inputAmount,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature memory theSignature,
        bytes memory extraData
    )
        private
    {
        if (!isToken(inputToken)) revert TokenNotInPool();

        // wraps msg.value if existent as it will be used in the following checks
        _wrapMsgValue();

        bytes32 digest = _singleDepositChecks(
            depositor,
            inputToken,
            inputAmount,
            lockTime,
            poolTokens,
            goodUntil,
            theSignature,
            extraData
        );

        // Validate digest already used
        _checkAndInvalidateDigest(digest);

        // Did we actually deposit what we said we would? Revert otherwise
        _verifyDepositSingleAssetAmountWithOracles(inputToken, inputAmount, poolTokens);

        // sync the balance
        _sync(inputToken);

        _finalizeDeposit(depositor, lockTime, poolTokens);
    }

    function withdrawSingleAsset(
        address tokenHolder,
        uint256 poolTokenAmountToBurn,
        address assetAddress,
        uint256 assetAmount,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    )
        external override
        marketIsRunning
        onlyTokenHolder(tokenHolder)
        receivedInTime(goodUntil)
    {
        bool sendEthBack;
        if (assetAddress == ETH_SIGIL) {
            assetAddress = WRAPPER_CONTRACT;
            sendEthBack = true;
        }

        bytes32 digest = _singleWithdrawChecks(
            tokenHolder,
            poolTokenAmountToBurn,
            assetAddress,
            assetAmount,
            goodUntil,
            theSignature,
            extraData
        );

        // Validate digest already used
        _checkAndInvalidateDigest(digest);

        // Revert if oracle prices don't match amount withdrawn
        _verifyWithdrawSingleAssetAmountWithOracles(
            assetAddress,
            assetAmount,
            poolTokenAmountToBurn
        );

        // Reverts if balance is insufficient
        _burn(msg.sender, poolTokenAmountToBurn);

        // Reverts if balance is insufficient
        // syncs done automatically on transfer
        if (sendEthBack) {
            _unwrapAndForwardEth(msg.sender, assetAmount);
        } else {
            transferAsset(assetAddress, msg.sender, assetAmount);
        }

        emit AssetWithdrawn(
            tokenHolder,
            poolTokenAmountToBurn,
            assetAddress,
            assetAmount
        );
    }

    // Don't need a separate "transmit" function here since it's already payable
    function sellEthForToken(
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    )
        external payable
        marketIsRunning
        receivedInTime(uint256(uint32(goodUntil)))
    {
        _sellEthForToken(
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature,
            auxiliaryData
        );
    }

    function _sellEthForToken(
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature memory theSignature,
        bytes memory auxiliaryData
    )
        private
    {
        // Wrap ETH (as balance or value) as input
        safeEthSend(WRAPPER_CONTRACT, inputAmount);
        _swap(
            WRAPPER_CONTRACT,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature,
            auxiliaryData
        );
    }

    function transmitAndDepositSingleAsset(
        address inputToken,
        uint256 inputAmount,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    )
        external
        marketIsRunning
        receivedInTime(goodUntil)
        validLockTime(lockTime)
    {
        IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
        _depositSingleAsset(
            msg.sender,
            inputToken,
            inputAmount,
            lockTime,
            poolTokens,
            goodUntil,
            theSignature,
            extraData
        );
    }

    function transmitAndSellTokenForEth(
        address inputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    )
        external override
        marketIsRunning
        receivedInTime(uint256(uint32(goodUntil)))
    {
        IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
        _sellTokenForEth(
            inputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature,
            auxiliaryData
        );
    }

    // all-in-one transfer from msg.sender to destinationAddress.
    function transmitAndSwap(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    )
        external override
        marketIsRunning
        receivedInTime(uint256(uint32(goodUntil)))
    {
        IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
        _swap(
            inputToken,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress,
            theSignature,
            auxiliaryData
        );
    }

    function _unpackAndCheckInvariantAndPrice(
        address inputToken,
        uint256 inputAmount,
        address outputToken,
        uint256 outputAmount,
        uint256 goodUntil
    )
        private view
    {
        UtilStruct memory s;

        (
            uint256 pX,
            uint256 pY,
            uint256 wX,
            uint256 wY,
            uint256 k
        ) = _unpackGoodUntil(goodUntil);
        s.qX = lastBalances[inputToken];
        s.qY = lastBalances[outputToken];
        s.decimalMultiplierX = 10 ** (18 - tokenDecimals[inputToken]);
        s.decimalMultiplierY = 10 ** (18 - tokenDecimals[outputToken]);

        bool ok = _swapIncreasesInvariant(
            inputAmount * s.decimalMultiplierX,
            pX,
            s.qX * s.decimalMultiplierX,
            wX,
            outputAmount * s.decimalMultiplierY,
            pY,
            s.qY * s.decimalMultiplierY,
            wY,
            k
        );
        if (!ok) revert InvariantCheckFailed();

        // Only validate price if both tokens have an oracle set
        if (
            oracles[inputToken].oracleAddress != address(0) &&
            oracles[outputToken].oracleAddress != address(0)
        ) {
            // Revert if oracle price is out of boundaries
            validatePrice(inputAmount, outputAmount, inputToken, outputToken);
        }
    }

    /**
     * @notice Verifies that a multi-asset deposit matches the expected LP token value.
     * @dev Reverts if the USD value of the LP tokens exceeds the value of the deposited tokens plus tolerance.
     * @param depositAmounts The array of deposited token amounts, indexed by token order.
     * @param poolTokens The amount of LP tokens expected to be minted.
     * @custom:requirements prices must be available for all tokens and use 18 decimals.
     */
    function _verifyDepositAmountsWithOracles(
        uint256[] memory depositAmounts,
        uint256 poolTokens
    )
        private view
    {
        bool oracleVerification = false;
        if (_areAllOraclesSet()) {
            oracleVerification = true;
        }

        uint n = nTokens();
        uint256 depositValue = 0;
        for (uint i = 0; i < n; ++i) {
            if (depositAmounts[i] > 0) {
                depositValue += _verifyAssetDeposit(tokenAt(i), depositAmounts[i], oracleVerification);
            }
        }

        if (oracleVerification) {
            _verifyPoolTokensFairValue(poolTokens, depositValue);
        }
    }

    /**
     * @notice Verifies a single-asset deposit against the expected LP token value.
     * @dev Uses current oracle prices to compute and compare values.
     * @param assetAddress The token being deposited.
     * @param assetAmount The amount of the token to deposit.
     * @param poolTokens The amount of LP tokens expected to be minted.
     */
    function _verifyDepositSingleAssetAmountWithOracles(
        address assetAddress,
        uint256 assetAmount,
        uint256 poolTokens
    )
        private view
    {
        bool oracleVerification = false;
        if (_areAllOraclesSet()) {
            oracleVerification = true;
        }

        uint256 depositValue = _verifyAssetDeposit(assetAddress, assetAmount, oracleVerification);

        if (oracleVerification) {
            _verifyPoolTokensFairValue(poolTokens, depositValue);
        }
    }

    function _verifyPoolTokensFairValue(uint256 poolTokens, uint256 valueToCompare) private view {
        uint256 lpTokenPrice = _getLpTokenPrice(totalSupply());
        uint256 poolTokensValue = (poolTokens * lpTokenPrice) / Constants.ONE_IN_DEFAULT_DECIMALS;

        _revertIfDeviationTooHigh(poolTokensValue, valueToCompare);
    }

    function _verifyAssetDeposit(
        address token,
        uint256 expectedAmount,
        bool oracleVerification
    )
        private view
        returns (uint256 depositValue)
    {
        uint256 delta = _currentDeltaOverLastBalance(token);
        if (delta < expectedAmount) {
            revert InsufficientInput();
        }

        if (oracleVerification) {
            depositValue = _getAssetAmountUsdValue(token, delta);
        }
    }

    /**
     * @notice Verifies a single-asset withdrawal against the value of LP tokens burned.
     * @dev Reverts if the USD value of the withdrawal exceeds LP token value plus tolerance.
     * @param assetAddress The token being withdrawn.
     * @param assetAmount The amount of the token to withdraw.
     * @param poolTokens The amount of LP tokens being burned.
     */
    function _verifyWithdrawSingleAssetAmountWithOracles(
        address assetAddress,
        uint256 assetAmount,
        uint256 poolTokens
    )
        private view
    {
        // skip if we don’t yet have a full set of price oracles
        if (_areAllOraclesSet()) {
            uint256 withdrawValue = _getAssetAmountUsdValue(assetAddress, assetAmount);
            _verifyPoolTokensFairValue(withdrawValue, poolTokens);
        }
    }

    /*
    unpack: internal function to unpack uint256 representation
    Input arguments:
      amountAndAddress: uint256 where first 24 hexchars are a uint96 shortened uint256
                         and last 40 hexchars are an address
    Returns: unpacked amount and address
    */
    function _unpack(
        uint256 amountAndAddress
    )
        private pure
        returns (
            uint256 amount,
            address contractAddress
        )
    {
        // uint256 -> uint160 automatically takes just last 40 hexchars
        contractAddress = address(uint160(amountAndAddress));
        // shift over the 40 hexchars to capture the amount
        amount = amountAndAddress >> 160;
    }

    /*
    packedTransmitAndDepositSingleAsset: deposit a single asset in an efficient way
    Input arguments:
      packedInput: Amount and contract address of asset to deposit
      packedConfig: First 32 hexchars are poolTokens, next 24 are goodUntil, next 6 is lockTime in minutes, final 2 are v
      r, s: Signature values
    */
    function packedTransmitAndDepositSingleAsset(
        uint256 packedInput,
        uint256 packedConfig,
        bytes32 r,
        bytes32 s,
        bytes calldata extraData
    )
        external payable
        marketIsRunning
    {
        uint256 poolTokens = packedConfig >> 128;
        uint256 goodUntil = uint256(uint96(packedConfig >> 32));
        uint256 lockTime = uint256(uint24(packedConfig >> 8));

        // validates message expiration
        if (goodUntil < block.timestamp) {
            revert ExpiredMessage();
        }

        // validates vesting time
        if (lockTime < 1) {
            revert InvalidLockTime();
        }

        Signature memory theSignature;
        uint256 inputAmount;
        address inputToken;
        {
            // scope to avoid stack too deep errors
            (inputAmount, inputToken) = _unpack(packedInput);
            uint8 v = uint8(packedConfig);

            theSignature = Signature(v, r, s);
            delete v;

            if (inputToken == ETH_SIGIL) {
                // Don't need to wrap the ETH here, do it in the deposit function
                inputToken = WRAPPER_CONTRACT;
            } else {
                IERC20(inputToken).safeTransferFrom(msg.sender, address(this), inputAmount);
            }
        }

        _depositSingleAsset(
            msg.sender,
            inputToken,
            inputAmount,
            lockTime,
            poolTokens,
            goodUntil,
            theSignature,
            extraData
        );
    }

    /*
    unpackAndSwap: internal function that performs unpacks a set of calldata-packed inputs and performs a swap
    Input arguments:
      packedInput: input amount and contract
      packedOutput: output amount and contract
      packedGoodUntil: packed good until (for verifier, direct from server)
      impliedOutputPrice: implied price for the output token to verify with the oracle
      auxData: bytes32, identifier. Final 20 bytes are destination address. First 12 bytes are auxData identifier string.
      r, vs: Signature values using EIP 2098 - https://eips.ethereum.org/EIPS/eip-2098
      performTransfer: if tokens should be transferred from msg.sender
    */
    function _unpackAndSwap(
        uint256 packedInput,
        uint256 packedOutput,
        uint256 packedGoodUntil,
        bytes32 auxData,
        bytes32 r,
        bytes32 vs,
        bool performTransfer
    )
        private
    {
        (uint256 inputAmount, address inputContractAddress) = _unpack(packedInput);
        (uint256 outputAmount, address outputContractAddress) = _unpack(packedOutput);
        Signature memory theSignature;

        {
            // Directly from https://eips.ethereum.org/EIPS/eip-2098
            bytes32 s = vs & 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
            uint8 v = 27 + uint8(uint256(vs) >> 255);

            theSignature = Signature(v, r, s);
        }

        if (performTransfer && (inputContractAddress != ETH_SIGIL)) {
            IERC20(inputContractAddress).safeTransferFrom(msg.sender, address(this), inputAmount);
        }

        _performUnpackedSwap(
            inputContractAddress,
            outputContractAddress,
            inputAmount,
            outputAmount,
            packedGoodUntil,
            auxData,
            theSignature
        );
    }

    function _performUnpackedSwap(
        address inputContractAddress,
        address outputContractAddress,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        bytes32 auxData,
        Signature memory theSignature
    )
        private
    {
        address destinationAddress = address(uint160(uint256(auxData)));
        bytes12 prefix = bytes12(auxData);
        bytes memory auxiliaryData = abi.encodePacked(prefix);

        if (inputContractAddress == ETH_SIGIL) {
            _sellEthForToken(
                outputContractAddress,
                inputAmount,
                outputAmount,
                goodUntil,
                destinationAddress,
                theSignature,
                auxiliaryData
            );
        } else if (outputContractAddress == ETH_SIGIL) {
            _sellTokenForEth(
                inputContractAddress,
                inputAmount,
                outputAmount,
                goodUntil,
                destinationAddress,
                theSignature,
                auxiliaryData
            );
        } else {
            _swap(
                inputContractAddress,
                outputContractAddress,
                inputAmount,
                outputAmount,
                goodUntil,
                destinationAddress,
                theSignature,
                auxiliaryData
            );
        }
    }

    // external function to transfer tokens and perform swap from packed calldata
    function packedTransmitAndSwap(
        uint256 packedInput,
        uint256 packedOutput,
        uint256 packedGoodUntil,
        bytes32 auxData,
        bytes32 r,
        bytes32 vs
    )
        external payable
        marketIsRunning
        receivedInTime(uint256(uint32(packedGoodUntil)))
    {
        _unpackAndSwap(
            packedInput,
            packedOutput,
            packedGoodUntil,
            auxData,
            r,
            vs,
            true
        );
    }

    // external function to perform swap from packed calldata
    function packedSwap(
        uint256 packedInput,
        uint256 packedOutput,
        uint256 packedGoodUntil,
        bytes32 auxData,
        bytes32 r,
        bytes32 vs
    )
        external payable
        marketIsRunning
        receivedInTime(uint256(uint32(packedGoodUntil)))
    {
        _unpackAndSwap(
            packedInput,
            packedOutput,
            packedGoodUntil,
            auxData,
            r,
            vs,
            false
        );
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 * - Set can be cleared (all elements removed) in O(n).
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position is the index of the value in the `values` array plus 1.
        // Position 0 is used to mean a value is not in the set.
        mapping(bytes32 value => uint256) _positions;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._positions[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We cache the value's position to prevent multiple reads from the same storage slot
        uint256 position = set._positions[value];

        if (position != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 valueIndex = position - 1;
            uint256 lastIndex = set._values.length - 1;

            if (valueIndex != lastIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the lastValue to the index where the value to delete is
                set._values[valueIndex] = lastValue;
                // Update the tracked position of the lastValue (that was just moved)
                set._positions[lastValue] = position;
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the tracked position for the deleted slot
            delete set._positions[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function _clear(Set storage set) private {
        uint256 len = _length(set);
        for (uint256 i = 0; i < len; ++i) {
            delete set._positions[set._values[i]];
        }
        Arrays.unsafeSetLength(set._values, 0);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._positions[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(Bytes32Set storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(AddressSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Removes all the values from a set. O(n).
     *
     * WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
     * function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
     */
    function clear(UintSet storage set) internal {
        _clear(set._inner);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly ("memory-safe") {
            result := store
        }

        return result;
    }
}

File 3 of 65 : 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 4 of 65 : Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { wrap } from "./Casting.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Implements the checked addition operation (+) in the SD59x18 type.
function add(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    return wrap(x.unwrap() + y.unwrap());
}

/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and(SD59x18 x, int256 bits) pure returns (SD59x18 result) {
    return wrap(x.unwrap() & bits);
}

/// @notice Implements the AND (&) bitwise operation in the SD59x18 type.
function and2(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    return wrap(x.unwrap() & y.unwrap());
}

/// @notice Implements the equal (=) operation in the SD59x18 type.
function eq(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() == y.unwrap();
}

/// @notice Implements the greater than operation (>) in the SD59x18 type.
function gt(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() > y.unwrap();
}

/// @notice Implements the greater than or equal to operation (>=) in the SD59x18 type.
function gte(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() >= y.unwrap();
}

/// @notice Implements a zero comparison check function in the SD59x18 type.
function isZero(SD59x18 x) pure returns (bool result) {
    result = x.unwrap() == 0;
}

/// @notice Implements the left shift operation (<<) in the SD59x18 type.
function lshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() << bits);
}

/// @notice Implements the lower than operation (<) in the SD59x18 type.
function lt(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() < y.unwrap();
}

/// @notice Implements the lower than or equal to operation (<=) in the SD59x18 type.
function lte(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() <= y.unwrap();
}

/// @notice Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() % y.unwrap());
}

/// @notice Implements the not equal operation (!=) in the SD59x18 type.
function neq(SD59x18 x, SD59x18 y) pure returns (bool result) {
    result = x.unwrap() != y.unwrap();
}

/// @notice Implements the NOT (~) bitwise operation in the SD59x18 type.
function not(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(~x.unwrap());
}

/// @notice Implements the OR (|) bitwise operation in the SD59x18 type.
function or(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() | y.unwrap());
}

/// @notice Implements the right shift operation (>>) in the SD59x18 type.
function rshift(SD59x18 x, uint256 bits) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() >> bits);
}

/// @notice Implements the checked subtraction operation (-) in the SD59x18 type.
function sub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() - y.unwrap());
}

/// @notice Implements the checked unary minus operation (-) in the SD59x18 type.
function unary(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(-x.unwrap());
}

/// @notice Implements the unchecked addition operation (+) in the SD59x18 type.
function uncheckedAdd(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(x.unwrap() + y.unwrap());
    }
}

/// @notice Implements the unchecked subtraction operation (-) in the SD59x18 type.
function uncheckedSub(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(x.unwrap() - y.unwrap());
    }
}

/// @notice Implements the unchecked unary minus operation (-) in the SD59x18 type.
function uncheckedUnary(SD59x18 x) pure returns (SD59x18 result) {
    unchecked {
        result = wrap(-x.unwrap());
    }
}

/// @notice Implements the XOR (^) bitwise operation in the SD59x18 type.
function xor(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() ^ y.unwrap());
}

File 5 of 65 : Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.

pragma solidity ^0.8.20;

import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";

/**
 * @dev Collection of functions related to array types.
 */
library Arrays {
    using SlotDerivation for bytes32;
    using StorageSlot for bytes32;

    /**
     * @dev Sort an array of uint256 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        uint256[] memory array,
        function(uint256, uint256) pure returns (bool) comp
    ) internal pure returns (uint256[] memory) {
        _quickSort(_begin(array), _end(array), comp);
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of uint256 in increasing order.
     */
    function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
        sort(array, Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of address (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        address[] memory array,
        function(address, address) pure returns (bool) comp
    ) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of address in increasing order.
     */
    function sort(address[] memory array) internal pure returns (address[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Sort an array of bytes32 (in memory) following the provided comparator function.
     *
     * This function does the sorting "in place", meaning that it overrides the input. The object is returned for
     * convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
     *
     * NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
     * array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
     * when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
     * consume more gas than is available in a block, leading to potential DoS.
     *
     * IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
     */
    function sort(
        bytes32[] memory array,
        function(bytes32, bytes32) pure returns (bool) comp
    ) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), _castToUint256Comp(comp));
        return array;
    }

    /**
     * @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
     */
    function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
        sort(_castToUint256Array(array), Comparators.lt);
        return array;
    }

    /**
     * @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
     * at end (exclusive). Sorting follows the `comp` comparator.
     *
     * Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
     *
     * IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
     * be used only if the limits are within a memory array.
     */
    function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
        unchecked {
            if (end - begin < 0x40) return;

            // Use first element as pivot
            uint256 pivot = _mload(begin);
            // Position where the pivot should be at the end of the loop
            uint256 pos = begin;

            for (uint256 it = begin + 0x20; it < end; it += 0x20) {
                if (comp(_mload(it), pivot)) {
                    // If the value stored at the iterator's position comes before the pivot, we increment the
                    // position of the pivot and move the value there.
                    pos += 0x20;
                    _swap(pos, it);
                }
            }

            _swap(begin, pos); // Swap pivot into place
            _quickSort(begin, pos, comp); // Sort the left side of the pivot
            _quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
        }
    }

    /**
     * @dev Pointer to the memory location of the first element of `array`.
     */
    function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
        assembly ("memory-safe") {
            ptr := add(array, 0x20)
        }
    }

    /**
     * @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
     * that comes just after the last element of the array.
     */
    function _end(uint256[] memory array) private pure returns (uint256 ptr) {
        unchecked {
            return _begin(array) + array.length * 0x20;
        }
    }

    /**
     * @dev Load memory word (as a uint256) at location `ptr`.
     */
    function _mload(uint256 ptr) private pure returns (uint256 value) {
        assembly {
            value := mload(ptr)
        }
    }

    /**
     * @dev Swaps the elements memory location `ptr1` and `ptr2`.
     */
    function _swap(uint256 ptr1, uint256 ptr2) private pure {
        assembly {
            let value1 := mload(ptr1)
            let value2 := mload(ptr2)
            mstore(ptr1, value2)
            mstore(ptr2, value1)
        }
    }

    /// @dev Helper: low level cast address memory array to uint256 memory array
    function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 memory array to uint256 memory array
    function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast address comp function to uint256 comp function
    function _castToUint256Comp(
        function(address, address) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /// @dev Helper: low level cast bytes32 comp function to uint256 comp function
    function _castToUint256Comp(
        function(bytes32, bytes32) pure returns (bool) input
    ) private pure returns (function(uint256, uint256) pure returns (bool) output) {
        assembly {
            output := input
        }
    }

    /**
     * @dev Searches a sorted `array` and returns the first index that contains
     * a value greater or equal to `element`. If no such index exists (i.e. all
     * values in the array are strictly less than `element`), the array length is
     * returned. Time complexity O(log n).
     *
     * NOTE: The `array` is expected to be sorted in ascending order, and to
     * contain no repeated elements.
     *
     * IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
     * support for repeated elements in the array. The {lowerBound} function should
     * be used instead.
     */
    function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
        if (low > 0 && unsafeAccess(array, low - 1).value == element) {
            return low - 1;
        } else {
            return low;
        }
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value greater or equal than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
     */
    function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Searches an `array` sorted in ascending order and returns the first
     * index that contains a value strictly greater than `element`. If no such index
     * exists (i.e. all values in the array are strictly less than `element`), the array
     * length is returned. Time complexity O(log n).
     *
     * See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
     */
    function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeAccess(array, mid).value > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Same as {lowerBound}, but with an array in memory.
     */
    function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) < element) {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            } else {
                high = mid;
            }
        }

        return low;
    }

    /**
     * @dev Same as {upperBound}, but with an array in memory.
     */
    function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
        uint256 low = 0;
        uint256 high = array.length;

        if (high == 0) {
            return 0;
        }

        while (low < high) {
            uint256 mid = Math.average(low, high);

            // Note that mid will always be strictly less than high (i.e. it will be a valid array index)
            // because Math.average rounds towards zero (it does integer division with truncation).
            if (unsafeMemoryAccess(array, mid) > element) {
                high = mid;
            } else {
                // this cannot overflow because mid < high
                unchecked {
                    low = mid + 1;
                }
            }
        }

        return low;
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getAddressSlot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getBytes32Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
        bytes32 slot;
        assembly ("memory-safe") {
            slot := arr.slot
        }
        return slot.deriveArray().offset(pos).getUint256Slot();
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
     *
     * WARNING: Only use if you are certain `pos` is lower than the array length.
     */
    function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
        assembly {
            res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(address[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }

    /**
     * @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
     *
     * WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
     */
    function unsafeSetLength(uint256[] storage array, uint256 len) internal {
        assembly ("memory-safe") {
            sstore(array.slot, len)
        }
    }
}

File 6 of 65 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;

/// @notice The unsigned 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint128. This is useful when end users want to use uint128 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD21x18 is uint128;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD59x18,
    Casting.intoUD60x18,
    Casting.intoUint128,
    Casting.intoUint256,
    Casting.intoUint40,
    Casting.unwrap
} for UD21x18 global;

File 7 of 65 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;

/// @notice The signed 59.18-decimal fixed-point number representation, which can have up to 59 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int256.
type SD59x18 is int256;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoInt256,
    Casting.intoSD1x18,
    Casting.intoSD21x18,
    Casting.intoUD2x18,
    Casting.intoUD21x18,
    Casting.intoUD60x18,
    Casting.intoUint256,
    Casting.intoUint128,
    Casting.intoUint40,
    Casting.unwrap
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

using {
    Math.abs,
    Math.avg,
    Math.ceil,
    Math.div,
    Math.exp,
    Math.exp2,
    Math.floor,
    Math.frac,
    Math.gm,
    Math.inv,
    Math.log10,
    Math.log2,
    Math.ln,
    Math.mul,
    Math.pow,
    Math.powu,
    Math.sqrt
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

using {
    Helpers.add,
    Helpers.and,
    Helpers.eq,
    Helpers.gt,
    Helpers.gte,
    Helpers.isZero,
    Helpers.lshift,
    Helpers.lt,
    Helpers.lte,
    Helpers.mod,
    Helpers.neq,
    Helpers.not,
    Helpers.or,
    Helpers.rshift,
    Helpers.sub,
    Helpers.uncheckedAdd,
    Helpers.uncheckedSub,
    Helpers.uncheckedUnary,
    Helpers.xor
} for SD59x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                    OPERATORS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes it possible to use these operators on the SD59x18 type.
using {
    Helpers.add as +,
    Helpers.and2 as &,
    Math.div as /,
    Helpers.eq as ==,
    Helpers.gt as >,
    Helpers.gte as >=,
    Helpers.lt as <,
    Helpers.lte as <=,
    Helpers.mod as %,
    Math.mul as *,
    Helpers.neq as !=,
    Helpers.not as ~,
    Helpers.or as |,
    Helpers.sub as -,
    Helpers.unary as -,
    Helpers.xor as ^
} for SD59x18 global;

File 8 of 65 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD21x18 } from "./ValueType.sol";

/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint128.
error PRBMath_SD21x18_ToUint128_Underflow(SD21x18 x);

/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in UD60x18.
error PRBMath_SD21x18_ToUD60x18_Underflow(SD21x18 x);

/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint256.
error PRBMath_SD21x18_ToUint256_Underflow(SD21x18 x);

/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Overflow(SD21x18 x);

/// @notice Thrown when trying to cast an SD21x18 number that doesn't fit in uint40.
error PRBMath_SD21x18_ToUint40_Underflow(SD21x18 x);

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

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature derives the `address(0)`.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ? {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(error, errorArg);
        return recovered;
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError error, bytes32 errorArg) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (error == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

File 11 of 65 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_SD59x18 } from "../sd59x18/Constants.sol";
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Casts a UD60x18 number into SD1x18.
/// @dev Requirements:
/// - x = uMAX_SD1x18
function intoSD1x18(UD60x18 x) pure returns (SD1x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(int256(uMAX_SD1x18))) {
        revert CastingErrors.PRBMath_UD60x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(uint64(xUint)));
}

/// @notice Casts a UD60x18 number into SD21x18.
/// @dev Requirements:
/// - x = uMAX_SD21x18
function intoSD21x18(UD60x18 x) pure returns (SD21x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(int256(uMAX_SD21x18))) {
        revert CastingErrors.PRBMath_UD60x18_IntoSD21x18_Overflow(x);
    }
    result = SD21x18.wrap(int128(uint128(xUint)));
}

/// @notice Casts a UD60x18 number into UD2x18.
/// @dev Requirements:
/// - x = uMAX_UD2x18
function intoUD2x18(UD60x18 x) pure returns (UD2x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uMAX_UD2x18) {
        revert CastingErrors.PRBMath_UD60x18_IntoUD2x18_Overflow(x);
    }
    result = UD2x18.wrap(uint64(xUint));
}

/// @notice Casts a UD60x18 number into UD21x18.
/// @dev Requirements:
/// - x = uMAX_UD21x18
function intoUD21x18(UD60x18 x) pure returns (UD21x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uMAX_UD21x18) {
        revert CastingErrors.PRBMath_UD60x18_IntoUD21x18_Overflow(x);
    }
    result = UD21x18.wrap(uint128(xUint));
}

/// @notice Casts a UD60x18 number into SD59x18.
/// @dev Requirements:
/// - x = uMAX_SD59x18
function intoSD59x18(UD60x18 x) pure returns (SD59x18 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > uint256(uMAX_SD59x18)) {
        revert CastingErrors.PRBMath_UD60x18_IntoSD59x18_Overflow(x);
    }
    result = SD59x18.wrap(int256(xUint));
}

/// @notice Casts a UD60x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint256(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x);
}

/// @notice Casts a UD60x18 number into uint128.
/// @dev Requirements:
/// - x = MAX_UINT128
function intoUint128(UD60x18 x) pure returns (uint128 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > MAX_UINT128) {
        revert CastingErrors.PRBMath_UD60x18_IntoUint128_Overflow(x);
    }
    result = uint128(xUint);
}

/// @notice Casts a UD60x18 number into uint40.
/// @dev Requirements:
/// - x = MAX_UINT40
function intoUint40(UD60x18 x) pure returns (uint40 result) {
    uint256 xUint = UD60x18.unwrap(x);
    if (xUint > MAX_UINT40) {
        revert CastingErrors.PRBMath_UD60x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for {wrap}.
function ud(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

/// @notice Alias for {wrap}.
function ud60x18(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

/// @notice Unwraps a UD60x18 number into uint256.
function unwrap(UD60x18 x) pure returns (uint256 result) {
    result = UD60x18.unwrap(x);
}

/// @notice Wraps a uint256 number into the UD60x18 value type.
function wrap(uint256 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(x);
}

File 12 of 65 : Helpers.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { wrap } from "./Casting.sol";
import { UD60x18 } from "./ValueType.sol";

/// @notice Implements the checked addition operation (+) in the UD60x18 type.
function add(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() + y.unwrap());
}

/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() & bits);
}

/// @notice Implements the AND (&) bitwise operation in the UD60x18 type.
function and2(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() & y.unwrap());
}

/// @notice Implements the equal operation (==) in the UD60x18 type.
function eq(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() == y.unwrap();
}

/// @notice Implements the greater than operation (>) in the UD60x18 type.
function gt(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() > y.unwrap();
}

/// @notice Implements the greater than or equal to operation (>=) in the UD60x18 type.
function gte(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() >= y.unwrap();
}

/// @notice Implements a zero comparison check function in the UD60x18 type.
function isZero(UD60x18 x) pure returns (bool result) {
    // This wouldn't work if x could be negative.
    result = x.unwrap() == 0;
}

/// @notice Implements the left shift operation (<<) in the UD60x18 type.
function lshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() << bits);
}

/// @notice Implements the lower than operation (<) in the UD60x18 type.
function lt(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() < y.unwrap();
}

/// @notice Implements the lower than or equal to operation (<=) in the UD60x18 type.
function lte(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() <= y.unwrap();
}

/// @notice Implements the checked modulo operation (%) in the UD60x18 type.
function mod(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() % y.unwrap());
}

/// @notice Implements the not equal operation (!=) in the UD60x18 type.
function neq(UD60x18 x, UD60x18 y) pure returns (bool result) {
    result = x.unwrap() != y.unwrap();
}

/// @notice Implements the NOT (~) bitwise operation in the UD60x18 type.
function not(UD60x18 x) pure returns (UD60x18 result) {
    result = wrap(~x.unwrap());
}

/// @notice Implements the OR (|) bitwise operation in the UD60x18 type.
function or(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() | y.unwrap());
}

/// @notice Implements the right shift operation (>>) in the UD60x18 type.
function rshift(UD60x18 x, uint256 bits) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() >> bits);
}

/// @notice Implements the checked subtraction operation (-) in the UD60x18 type.
function sub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() - y.unwrap());
}

/// @notice Implements the unchecked addition operation (+) in the UD60x18 type.
function uncheckedAdd(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(x.unwrap() + y.unwrap());
    }
}

/// @notice Implements the unchecked subtraction operation (-) in the UD60x18 type.
function uncheckedSub(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(x.unwrap() - y.unwrap());
    }
}

/// @notice Implements the XOR (^) bitwise operation in the UD60x18 type.
function xor(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(x.unwrap() ^ y.unwrap());
}

File 13 of 65 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD21x18 } from "./ValueType.sol";

/// @notice Casts a UD21x18 number into SD59x18.
/// @dev There is no overflow check because UD21x18 ? SD59x18.
function intoSD59x18(UD21x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(uint256(UD21x18.unwrap(x))));
}

/// @notice Casts a UD21x18 number into UD60x18.
/// @dev There is no overflow check because UD21x18 ? UD60x18.
function intoUD60x18(UD21x18 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(UD21x18.unwrap(x));
}

/// @notice Casts a UD21x18 number into uint128.
/// @dev This is basically an alias for {unwrap}.
function intoUint128(UD21x18 x) pure returns (uint128 result) {
    result = UD21x18.unwrap(x);
}

/// @notice Casts a UD21x18 number into uint256.
/// @dev There is no overflow check because UD21x18 ? uint256.
function intoUint256(UD21x18 x) pure returns (uint256 result) {
    result = uint256(UD21x18.unwrap(x));
}

/// @notice Casts a UD21x18 number into uint40.
/// @dev Requirements:
/// - x = MAX_UINT40
function intoUint40(UD21x18 x) pure returns (uint40 result) {
    uint128 xUint = UD21x18.unwrap(x);
    if (xUint > uint128(Common.MAX_UINT40)) {
        revert Errors.PRBMath_UD21x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for {wrap}.
function ud21x18(uint128 x) pure returns (UD21x18 result) {
    result = UD21x18.wrap(x);
}

/// @notice Unwrap a UD21x18 number into uint128.
function unwrap(UD21x18 x) pure returns (uint128 result) {
    result = UD21x18.unwrap(x);
}

/// @notice Wraps a uint128 number into UD21x18.
function wrap(uint128 x) pure returns (UD21x18 result) {
    result = UD21x18.wrap(x);
}

File 14 of 65 : BladeErrors.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;


error InvariantCheckFailed();
error InsufficientInput();
error InvalidFeeSplitTooMuch();
error InvalidFeeSplitTooSoon();
error InvalidLockTime();
error PoolStateDeviation();
error MarketTradeHalted();
error MismatchedArrayLengths();
error UnauthorizedCaller();
error ExistingVestingDeposit();
error UnlockDepositFailed();
error ExpiredMessage();
error EthTransferFailed();
error TokenNotInPool();
error InvalidLPTokenValue();
error TokenDecimalsNotSupported();

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Provides a set of functions to compare values.
 *
 * _Available since v5.1._
 */
library Comparators {
    function lt(uint256 a, uint256 b) internal pure returns (bool) {
        return a < b;
    }

    function gt(uint256 a, uint256 b) internal pure returns (bool) {
        return a > b;
    }
}

// SPDX-License-Identifier: UNLICENSED
// Copyright 2023 Shipyard Software, Inc.
pragma solidity ^0.8.20;

interface WrapperContractInterface {
    function withdraw(uint256 amount) external;
}

File 18 of 65 : BladeTypes.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

struct Signature {
    uint8 v;
    bytes32 r;
    bytes32 s;
}

struct Deposit {
    uint lockedUntil;
    uint256 poolTokenAmount;
}

struct UtilStruct {
    uint256 qX;
    uint256 qY;
    uint256 decimalMultiplierX;
    uint256 decimalMultiplierY;
}

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

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * Both values are immutable: they can only be set once during construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner`'s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}

File 20 of 65 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD21x18 } from "./ValueType.sol";

/// @dev Euler's number as an SD21x18 number.
SD21x18 constant E = SD21x18.wrap(2_718281828459045235);

/// @dev The maximum value an SD21x18 number can have.
int128 constant uMAX_SD21x18 = 170141183460469231731_687303715884105727;
SD21x18 constant MAX_SD21x18 = SD21x18.wrap(uMAX_SD21x18);

/// @dev The minimum value an SD21x18 number can have.
int128 constant uMIN_SD21x18 = -170141183460469231731_687303715884105728;
SD21x18 constant MIN_SD21x18 = SD21x18.wrap(uMIN_SD21x18);

/// @dev PI as an SD21x18 number.
SD21x18 constant PI = SD21x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of SD21x18.
SD21x18 constant UNIT = SD21x18.wrap(1e18);
int128 constant uUNIT = 1e18;

File 21 of 65 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD59x18 } from "./ValueType.sol";

/// @notice Thrown when taking the absolute value of `MIN_SD59x18`.
error PRBMath_SD59x18_Abs_MinSD59x18();

/// @notice Thrown when ceiling a number overflows SD59x18.
error PRBMath_SD59x18_Ceil_Overflow(SD59x18 x);

/// @notice Thrown when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMath_SD59x18_Convert_Overflow(int256 x);

/// @notice Thrown when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMath_SD59x18_Convert_Underflow(int256 x);

/// @notice Thrown when dividing two numbers and one of them is `MIN_SD59x18`.
error PRBMath_SD59x18_Div_InputTooSmall();

/// @notice Thrown when dividing two numbers and one of the intermediary unsigned results overflows SD59x18.
error PRBMath_SD59x18_Div_Overflow(SD59x18 x, SD59x18 y);

/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_SD59x18_Exp_InputTooBig(SD59x18 x);

/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_SD59x18_Exp2_InputTooBig(SD59x18 x);

/// @notice Thrown when flooring a number underflows SD59x18.
error PRBMath_SD59x18_Floor_Underflow(SD59x18 x);

/// @notice Thrown when taking the geometric mean of two numbers and their product is negative.
error PRBMath_SD59x18_Gm_NegativeProduct(SD59x18 x, SD59x18 y);

/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows SD59x18.
error PRBMath_SD59x18_Gm_Overflow(SD59x18 x, SD59x18 y);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD1x18.
error PRBMath_SD59x18_IntoSD1x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in SD21x18.
error PRBMath_SD59x18_IntoSD21x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD2x18.
error PRBMath_SD59x18_IntoUD2x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD21x18.
error PRBMath_SD59x18_IntoUD21x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in UD60x18.
error PRBMath_SD59x18_IntoUD60x18_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint128.
error PRBMath_SD59x18_IntoUint128_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint256.
error PRBMath_SD59x18_IntoUint256_Underflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Overflow(SD59x18 x);

/// @notice Thrown when trying to cast an SD59x18 number that doesn't fit in uint40.
error PRBMath_SD59x18_IntoUint40_Underflow(SD59x18 x);

/// @notice Thrown when taking the logarithm of a number less than or equal to zero.
error PRBMath_SD59x18_Log_InputTooSmall(SD59x18 x);

/// @notice Thrown when multiplying two numbers and one of the inputs is `MIN_SD59x18`.
error PRBMath_SD59x18_Mul_InputTooSmall();

/// @notice Thrown when multiplying two numbers and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Mul_Overflow(SD59x18 x, SD59x18 y);

/// @notice Thrown when raising a number to a power and the intermediary absolute result overflows SD59x18.
error PRBMath_SD59x18_Powu_Overflow(SD59x18 x, uint256 y);

/// @notice Thrown when taking the square root of a negative number.
error PRBMath_SD59x18_Sqrt_NegativeInput(SD59x18 x);

/// @notice Thrown when the calculating the square root overflows SD59x18.
error PRBMath_SD59x18_Sqrt_Overflow(SD59x18 x);

File 22 of 65 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { wrap } from "./Casting.sol";
import {
    uEXP_MAX_INPUT,
    uEXP2_MAX_INPUT,
    uHALF_UNIT,
    uLOG2_10,
    uLOG2_E,
    uMAX_UD60x18,
    uMAX_WHOLE_UD60x18,
    UNIT,
    uUNIT,
    uUNIT_SQUARED,
    ZERO
} from "./Constants.sol";
import { UD60x18 } from "./ValueType.sol";

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the arithmetic average of x and y using the following formula:
///
/// $$
/// avg(x, y) = (x & y) + ((xUint ^ yUint) / 2)
/// $$
///
/// In English, this is what this formula does:
///
/// 1. AND x and y.
/// 2. Calculate half of XOR x and y.
/// 3. Add the two results together.
///
/// This technique is known as SWAR, which stands for "SIMD within a register". You can read more about it here:
/// https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The arithmetic average as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    uint256 yUint = y.unwrap();
    unchecked {
        result = wrap((xUint & yUint) + ((xUint ^ yUint) >> 1));
    }
}

/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev This is optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x = MAX_WHOLE_UD60x18
///
/// @param x The UD60x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    if (xUint > uMAX_WHOLE_UD60x18) {
        revert Errors.PRBMath_UD60x18_Ceil_Overflow(x);
    }

    assembly ("memory-safe") {
        // Equivalent to `x % UNIT`.
        let remainder := mod(x, uUNIT)

        // Equivalent to `UNIT - remainder`.
        let delta := sub(uUNIT, remainder)

        // Equivalent to `x + remainder > 0 ? delta : 0`.
        result := add(x, mul(delta, gt(remainder, 0)))
    }
}

/// @notice Divides two UD60x18 numbers, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @param x The numerator as a UD60x18 number.
/// @param y The denominator as a UD60x18 number.
/// @return result The quotient as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(Common.mulDiv(x.unwrap(), uUNIT, y.unwrap()));
}

/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Requirements:
/// - x = 133_084258667509499440
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    // This check prevents values greater than 192e18 from being passed to {exp2}.
    if (xUint > uEXP_MAX_INPUT) {
        revert Errors.PRBMath_UD60x18_Exp_InputTooBig(x);
    }

    unchecked {
        // Inline the fixed-point multiplication to save gas.
        uint256 doubleUnitProduct = xUint * uLOG2_E;
        result = exp2(wrap(doubleUnitProduct / uUNIT));
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693
///
/// Requirements:
/// - x < 192e18
/// - The result must fit in UD60x18.
///
/// @param x The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
    if (xUint > uEXP2_MAX_INPUT) {
        revert Errors.PRBMath_UD60x18_Exp2_InputTooBig(x);
    }

    // Convert x to the 192.64-bit fixed-point format.
    uint256 x_192x64 = (xUint << 64) / uUNIT;

    // Pass x to the {Common.exp2} function, which uses the 192.64-bit fixed-point number representation.
    result = wrap(Common.exp2(x_192x64));
}

/// @notice Yields the greatest whole number less than or equal to x.
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
/// @param x The UD60x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(UD60x18 x) pure returns (UD60x18 result) {
    assembly ("memory-safe") {
        // Equivalent to `x % UNIT`.
        let remainder := mod(x, uUNIT)

        // Equivalent to `x - remainder > 0 ? remainder : 0)`.
        result := sub(x, mul(remainder, gt(remainder, 0)))
    }
}

/// @notice Yields the excess beyond the floor of x using the odd function definition.
/// @dev See https://en.wikipedia.org/wiki/Fractional_part.
/// @param x The UD60x18 number to get the fractional part of.
/// @return result The fractional part of x as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function frac(UD60x18 x) pure returns (UD60x18 result) {
    assembly ("memory-safe") {
        result := mod(x, uUNIT)
    }
}

/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$, rounding down.
///
/// @dev Requirements:
/// - x * y must fit in UD60x18.
///
/// @param x The first operand as a UD60x18 number.
/// @param y The second operand as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    uint256 yUint = y.unwrap();
    if (xUint == 0 || yUint == 0) {
        return ZERO;
    }

    unchecked {
        // Checking for overflow this way is faster than letting Solidity do it.
        uint256 xyUint = xUint * yUint;
        if (xyUint / xUint != yUint) {
            revert Errors.PRBMath_UD60x18_Gm_Overflow(x, y);
        }

        // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
        // during multiplication. See the comments in {Common.sqrt}.
        result = wrap(Common.sqrt(xyUint));
    }
}

/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The UD60x18 number for which to calculate the inverse.
/// @return result The inverse as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(UD60x18 x) pure returns (UD60x18 result) {
    unchecked {
        result = wrap(uUNIT_SQUARED / x.unwrap());
    }
}

/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(UD60x18 x) pure returns (UD60x18 result) {
    unchecked {
        // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
        // {log2} can return is ~196_205294292027477728.
        result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
    }
}

/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The UD60x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    if (xUint < uUNIT) {
        revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
    }

    // Note that the `mul` in this assembly block is the standard multiplication operation, not {UD60x18.mul}.
    // prettier-ignore
    assembly ("memory-safe") {
        switch x
        case 1 { result := mul(uUNIT, sub(0, 18)) }
        case 10 { result := mul(uUNIT, sub(1, 18)) }
        case 100 { result := mul(uUNIT, sub(2, 18)) }
        case 1000 { result := mul(uUNIT, sub(3, 18)) }
        case 10000 { result := mul(uUNIT, sub(4, 18)) }
        case 100000 { result := mul(uUNIT, sub(5, 18)) }
        case 1000000 { result := mul(uUNIT, sub(6, 18)) }
        case 10000000 { result := mul(uUNIT, sub(7, 18)) }
        case 100000000 { result := mul(uUNIT, sub(8, 18)) }
        case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
        case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
        case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
        case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
        case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
        case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
        case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
        case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
        case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
        case 1000000000000000000 { result := 0 }
        case 10000000000000000000 { result := uUNIT }
        case 100000000000000000000 { result := mul(uUNIT, 2) }
        case 1000000000000000000000 { result := mul(uUNIT, 3) }
        case 10000000000000000000000 { result := mul(uUNIT, 4) }
        case 100000000000000000000000 { result := mul(uUNIT, 5) }
        case 1000000000000000000000000 { result := mul(uUNIT, 6) }
        case 10000000000000000000000000 { result := mul(uUNIT, 7) }
        case 100000000000000000000000000 { result := mul(uUNIT, 8) }
        case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
        case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
        case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
        case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
        case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
        case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
        case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
        case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
        case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
        case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
        case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
        case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
        case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
        case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
        case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
        case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
        case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
        case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
        case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
        case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
        case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
        case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
        case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
        case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
        case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
        case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
        case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
        case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
        case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
        case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
        case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
        case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
        case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
        case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
        case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
        case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
        case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
        case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
        case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
        case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
        case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
        case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 59) }
        default { result := uMAX_UD60x18 }
    }

    if (result.unwrap() == uMAX_UD60x18) {
        unchecked {
            // Inline the fixed-point division to save gas.
            result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
        }
    }
}

/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x = UNIT
///
/// @param x The UD60x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    if (xUint < uUNIT) {
        revert Errors.PRBMath_UD60x18_Log_InputTooSmall(x);
    }

    unchecked {
        // Calculate the integer part of the logarithm.
        uint256 n = Common.msb(xUint / uUNIT);

        // This is the integer part of the logarithm as a UD60x18 number. The operation can't overflow because n
        // n is at most 255 and UNIT is 1e18.
        uint256 resultUint = n * uUNIT;

        // Calculate $y = x * 2^{-n}$.
        uint256 y = xUint >> n;

        // If y is the unit number, the fractional part is zero.
        if (y == uUNIT) {
            return wrap(resultUint);
        }

        // Calculate the fractional part via the iterative approximation.
        // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
        uint256 DOUBLE_UNIT = 2e18;
        for (uint256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
            y = (y * y) / uUNIT;

            // Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
            if (y >= DOUBLE_UNIT) {
                // Add the 2^{-m} factor to the logarithm.
                resultUint += delta;

                // Halve y, which corresponds to z/2 in the Wikipedia article.
                y >>= 1;
            }
        }
        result = wrap(resultUint);
    }
}

/// @notice Multiplies two UD60x18 numbers together, returning a new UD60x18 number.
///
/// @dev Uses {Common.mulDiv} to enable overflow-safe multiplication and division.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
///
/// @dev See the documentation in {Common.mulDiv18}.
/// @param x The multiplicand as a UD60x18 number.
/// @param y The multiplier as a UD60x18 number.
/// @return result The product as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    result = wrap(Common.mulDiv18(x.unwrap(), y.unwrap()));
}

/// @notice Raises x to the power of y.
///
/// For $1 \leq x \leq \infty$, the following standard formula is used:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// For $0 \leq x \lt 1$, since the unsigned {log2} is undefined, an equivalent formula is used:
///
/// $$
/// i = \frac{1}{x}
/// w = 2^{log_2{i} * y}
/// x^y = \frac{1}{w}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2} and {mul}.
/// - Returns `UNIT` for 0^0.
/// - It may not perform well with very small values of x. Consider using SD59x18 as an alternative.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a UD60x18 number.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(UD60x18 x, UD60x18 y) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();
    uint256 yUint = y.unwrap();

    // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
    if (xUint == 0) {
        return yUint == 0 ? UNIT : ZERO;
    }
    // If x is `UNIT`, the result is always `UNIT`.
    else if (xUint == uUNIT) {
        return UNIT;
    }

    // If y is zero, the result is always `UNIT`.
    if (yUint == 0) {
        return UNIT;
    }
    // If y is `UNIT`, the result is always x.
    else if (yUint == uUNIT) {
        return x;
    }

    // If x is > UNIT, use the standard formula.
    if (xUint > uUNIT) {
        result = exp2(mul(log2(x), y));
    }
    // Conversely, if x < UNIT, use the equivalent formula.
    else {
        UD60x18 i = wrap(uUNIT_SQUARED / xUint);
        UD60x18 w = exp2(mul(log2(i), y));
        result = wrap(uUNIT_SQUARED / w.unwrap());
    }
}

/// @notice Raises x (a UD60x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - The result must fit in UD60x18.
///
/// @param x The base as a UD60x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(UD60x18 x, uint256 y) pure returns (UD60x18 result) {
    // Calculate the first iteration of the loop in advance.
    uint256 xUint = x.unwrap();
    uint256 resultUint = y & 1 > 0 ? xUint : uUNIT;

    // Equivalent to `for(y /= 2; y > 0; y /= 2)`.
    for (y >>= 1; y > 0; y >>= 1) {
        xUint = Common.mulDiv18(xUint, xUint);

        // Equivalent to `y % 2 == 1`.
        if (y & 1 > 0) {
            resultUint = Common.mulDiv18(resultUint, xUint);
        }
    }
    result = wrap(resultUint);
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x = MAX_UD60x18 / UNIT
///
/// @param x The UD60x18 number for which to calculate the square root.
/// @return result The result as a UD60x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(UD60x18 x) pure returns (UD60x18 result) {
    uint256 xUint = x.unwrap();

    unchecked {
        if (xUint > uMAX_UD60x18 / uUNIT) {
            revert Errors.PRBMath_UD60x18_Sqrt_Overflow(x);
        }
        // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two UD60x18 numbers.
        // In this case, the two numbers are both the square root.
        result = wrap(Common.sqrt(xUint * uUNIT));
    }
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import "../base/BladeErrors.sol";
import { Signature, Deposit } from "../types/BladeTypes.sol";
import {Constants} from "../base/Constants.sol";
import { IBladeExchange } from "../interfaces/IBladeExchange.sol";
import { BladeSignatureLib } from "../libraries/BladeSignatureLib.sol";


abstract contract BladeCommonExchange is IBladeExchange, ERC20, ReentrancyGuard, Ownable {
    using SafeERC20 for IERC20;
    using EnumerableSet for EnumerableSet.AddressSet;
    using SafeCast for uint256;
    using SafeCast for int256;

    uint256 constant ONE_IN_TEN_DECIMALS = 1e10;
    uint256 constant ONE_IN_PRICE_DECIMALS = 1e8;
    uint256 constant ONE_BASIS_POINT_IN_TEN_DECIMALS = 1e6;
    address constant ETH_SIGIL = address(0);

    uint256 constant MAXIMUM_FEE_WITHDRAWAL_IN_TEN_DECIMALS = ONE_IN_TEN_DECIMALS / 20;
    uint256 constant MINIMUM_DURATION_BETWEEN_FEE_WITHDRAWAL = 7 days;

    // Allow for inputs up to 0.5% more than quoted values to have scaled output.
    // Inputs higher than this value just get 0.5% more.
    uint256 constant MAX_ALLOWED_OVER_TEN_DECIMALS = ONE_IN_TEN_DECIMALS+50*ONE_BASIS_POINT_IN_TEN_DECIMALS;

    // LP token price deviation in basis points
    uint8 constant PRICE_TOLERANCE_IN_BPS = 10;
    
    // Constant values for EIP-712 signing
    string constant VERSION = "2.0.0";
    string constant NAME = "Blade";
    bytes32 immutable DOMAIN_SEPARATOR;

    // Signer is passed in on construction, hence "immutable"
    address immutable public DESIGNATED_SIGNER;

    address immutable public WRAPPER_CONTRACT;

    //uint256 public lastDaoWithdrawal;
    uint256 public lastFeeWithdrawal;

    // Halt market
    address public triageRole;
    bool private _marketHalted;

    // Assets
    // lastBalances: used for "transmit then swap then sync" modality
    // assetSet is a set of keys that have lastBalances
    mapping(address => uint256) public lastBalances;
    mapping(address => uint8) tokenDecimals;
    EnumerableSet.AddressSet assetSet;

    // Allows lookup
    mapping(address => Deposit) public vestingDeposits;

    modifier marketIsRunning {
        _requireMarketIsRunning();
        _;
    }

    modifier OnlyTriage() {
        _requireOnlyTriage();
        _;
    }

    modifier validLockTime(uint256 lockTime) {
        if (lockTime < 1) {
            revert InvalidLockTime();
        }
        _;
    }

    modifier receivedInTime(uint256 goodUntil) {
        if (goodUntil < block.timestamp) {
            revert ExpiredMessage();
        }
        _;
    }

    modifier onlyTokenHolder(address tokenHolder) {
        if (msg.sender != tokenHolder) {
            revert UnauthorizedCaller();
        }
        _;
    }

    // Take in the designated signer address and the token list
    constructor(
        address theSigner,
        address theWrapper,
        address[] memory tokens,
        address initialOwner
    )
        ERC20(tokenName(), tokenSymbol())
        Ownable(initialOwner)
    {
        DESIGNATED_SIGNER = theSigner;
        uint i;
        uint n = tokens.length;
        while(i < n) {
            address token = tokens[i];

            assetSet.add(token);

            // Cache token decimals
            uint8 decimals = IERC20Metadata(token).decimals();

            if (decimals > 18) {
                revert TokenDecimalsNotSupported();
            }

            tokenDecimals[token] = decimals;

            i++;
        }
        DOMAIN_SEPARATOR = BladeSignatureLib.createDomainSeparator(NAME, VERSION, address(this));
        WRAPPER_CONTRACT = theWrapper;
    }

    // Allows the receipt of ETH directly
    receive() external payable {}

    function _verifyDigestSignature(
        bytes32 digest,
        Signature memory sig
    ) internal view {
        BladeSignatureLib.verifyDigestSignature(digest, sig, DESIGNATED_SIGNER);
    }

    function deposit(
        address depositor,
        uint256[] calldata depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    ) public payable virtual;

    /*
    Triage emergency functionality.

    owner can set an address that has the ability to halt trade.
    Only proportional withdrawals are allowed if trade is halted.
    */

    function setTriageRole(address newTriage) external onlyOwner {
        triageRole = newTriage;
        emit TriageAddressChanged(newTriage);
    }

    function isTradeHalted() external view virtual returns (bool) {
        return _marketHalted;
    }

    function stopTrade() external OnlyTriage {
        _marketHalted = true;
        emit MarketHalted(msg.sender);
    }

    function resumeTrade() external OnlyTriage {
        _marketHalted = false;
        emit MarketResumed(msg.sender);
    }

    function _requireOnlyTriage() private view {
        if (msg.sender != triageRole) {
            revert UnauthorizedCaller();
        }
    }

    function _requireMarketIsRunning() private view {
        if (_marketHalted) {
            revert MarketTradeHalted();
        }
    }

    function tokenName() internal pure virtual returns (string memory) {
        return "Blade LP Token";
    }

    function tokenSymbol() internal pure virtual returns (string memory) {
        return "BladeLP";
    }

    function safeEthSend(address recipient, uint256 howMuch) internal {
        (bool success, ) = payable(recipient).call{value: howMuch}("");
        if (!success) revert EthTransferFailed();
    }

    /* TOKEN AND ASSET FUNCTIONS */
    function nTokens() public view returns (uint) {
        return assetSet.length();
    }

    function tokenAt(uint i) public view returns (address) {
        return assetSet.at(i);
    }

    function isToken(address token) public view returns (bool) {
        return assetSet.contains(token);
    }

    function _sync(address token) internal virtual;

    // Can be overridden
    function getLastBalance(address token) public view virtual returns (uint256) {
        return lastBalances[token];
    }

    function getTokenBalance(address token) internal view returns (uint256) {
        return IERC20(token).balanceOf(address(this));
    }

    function allTokensBalance() external view returns (uint256[] memory, address[] memory, uint256) {
        uint n = nTokens();
        uint256[] memory balances = new uint256[](n);
        address[] memory tokens = new address[](n);
        for (uint i = 0; i < n; i++) {
            address token = tokenAt(i);
            balances[i] = getLastBalance(token);
            tokens[i] = token;
        }

        return (balances, tokens, totalSupply());
    }

    function allTokensStateBalance() external view returns (uint256[] memory, address[] memory, uint256) {
        uint n = nTokens();
        uint256[] memory balances = new uint256[](n);
        address[] memory tokens = new address[](n);
        for (uint i = 0; i < n; i++) {
            address token = tokenAt(i);
            balances[i] = getTokenBalance(token);
            tokens[i] = token;
        }

        return (balances, tokens, totalSupply());
    }

    function transmitAndDeposit(
        uint256[] calldata depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    )
        external
        marketIsRunning
    {
        uint i = 0;
        uint n = depositAmounts.length;
        while(i < n) {
            uint256 transferAmount = depositAmounts[i];
            if(transferAmount > 0){
                IERC20(tokenAt(i)).safeTransferFrom(msg.sender, address(this), transferAmount);
            }
            i++;
        }
        deposit(msg.sender, depositAmounts, lockTime, poolTokens, goodUntil, theSignature, extraData);
    }

    /**
    * @notice Verifies that the on-chain LP token price is within acceptable bounds of the provided reference price.
    * @dev Uses external token prices (all with 18 decimals) to recompute the LP token price on-chain.
    *      If the deviation exceeds the predefined tolerance (in BPS), the transaction reverts.
    *      This protects against large valuation mismatches.
    * @param lpTokenPrice The expected LP token price, computed off-chain and provided as reference. Must use 18 decimals.
    * @param prices External token prices used to calculate the current on-chain LP token price. Each must use 18 decimals.
    * @custom:conditions Skips verification if total LP token supply is zero.
    */
    function _verifyLpTokenStatePool(
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        private view
    {
        uint256 lpTotalSupply = totalSupply();
        if (lpTotalSupply == 0) {
            return; // No validation needed on first deposit
        }

        if (lpTokenPrice == 0) {
            revert InvalidLPTokenValue();
        }

        uint256 n = nTokens();
        uint256 totalValue;
        for (uint i = 0; i < n; ++i) {
            address token = tokenAt(i);
            uint256 decimalMultiplier = 10 ** (18 - tokenDecimals[token]);
            uint256 tokenBalance = getTokenBalance(token) * decimalMultiplier;
            uint256 tokenValue = (tokenBalance * prices[i]) / Constants.ONE_IN_DEFAULT_DECIMALS;
            totalValue += tokenValue;
        }
        uint256 onChainLpTokenPrice = (totalValue * Constants.ONE_IN_DEFAULT_DECIMALS) / lpTotalSupply;

        // Nothing to do if they match exactly
        if (onChainLpTokenPrice == lpTokenPrice) {
            return;
        }

        // Calculate how much deviation is allowed (referenceValue * toleranceBps / 10 000)
        uint256 maxAllowedDeviation = (lpTokenPrice * Constants.PRICE_TOLERANCE_IN_BPS) / Constants.ONE_IN_BASIS_POINTS;

        // Compute the absolute difference between actual and reference
        uint256 absoluteDifference = onChainLpTokenPrice > lpTokenPrice
            ? onChainLpTokenPrice - lpTokenPrice
            : lpTokenPrice - onChainLpTokenPrice;

        // Revert if the difference exceeds the allowed tolerance
        if (absoluteDifference > maxAllowedDeviation) {
            revert PoolStateDeviation();
        }
    }

    // nonReentrant asset transfer
    function transferAsset(address token, address recipient, uint256 amount) internal nonReentrant {
        IERC20(token).safeTransfer(recipient, amount);
        // We never want to transfer an asset without sync'ing
        _sync(token);
    }

    function calculateFairOutput(uint256 statedInput, uint256 actualInput, uint256 statedOutput) internal pure returns (uint256) {
        if (actualInput == statedInput) {
            return statedOutput;
        } else {
            uint256 theFraction = (ONE_IN_TEN_DECIMALS*actualInput)/statedInput;
            if (theFraction >= MAX_ALLOWED_OVER_TEN_DECIMALS) {
                return (MAX_ALLOWED_OVER_TEN_DECIMALS*statedOutput)/ONE_IN_TEN_DECIMALS;
            } else {
                return (theFraction*statedOutput)/ONE_IN_TEN_DECIMALS;
            }
        }
    }

    /* DEPOSIT FUNCTIONALITY */
    function canUnlockDeposit(address depositor) public view returns (bool) {
        Deposit storage myDeposit = vestingDeposits[depositor];
        return (myDeposit.poolTokenAmount > 0) && (myDeposit.lockedUntil <= block.timestamp);
    }

    function unlockDeposit() external returns (uint256 poolTokens) {
        if (!canUnlockDeposit(msg.sender)) {
            revert UnlockDepositFailed();
        }

        poolTokens = vestingDeposits[msg.sender].poolTokenAmount;
        delete vestingDeposits[msg.sender];

        _transfer(address(this), msg.sender, poolTokens);
    }

    // Mints tokens to this contract to hold for vesting
    function _createVestingDeposit(address depositor, uint256 lockTime, uint256 poolTokens) private {
        if (lockTime < 1) {
            revert InvalidLockTime();
        }

        if (vestingDeposits[depositor].poolTokenAmount != 0) {
            revert ExistingVestingDeposit();
        }

        Deposit memory myDeposit = Deposit({
            lockedUntil: block.timestamp + (lockTime * 1 minutes),
            poolTokenAmount: poolTokens
        });
        vestingDeposits[depositor] = myDeposit;
        _mint(address(this), poolTokens);
    }

    function takeFees(
        uint256 entitledFeesInDollars,
        uint256 averagePoolBalanceInDollars
    )
        external onlyOwner
    {
        // calculate fraction in base ten
        uint256 theFraction = (ONE_IN_TEN_DECIMALS * entitledFeesInDollars) / averagePoolBalanceInDollars;

        // Validates is less thant max allowed
        if(theFraction > MAXIMUM_FEE_WITHDRAWAL_IN_TEN_DECIMALS) {
            revert InvalidFeeSplitTooMuch();
        }

        // Validates withdrawal time
        if(block.timestamp < lastFeeWithdrawal + MINIMUM_DURATION_BETWEEN_FEE_WITHDRAWAL) {
            revert InvalidFeeSplitTooSoon();
        }

        lastFeeWithdrawal = block.timestamp;

        // Calculates tokens to mint
        uint256 tokensToMint = (theFraction * totalSupply()) / ONE_IN_TEN_DECIMALS;
        _mint(msg.sender, tokensToMint);

        emit FeesTaken(entitledFeesInDollars, averagePoolBalanceInDollars, tokensToMint);
    }

    function _decodeAndValidatePrices(bytes memory extraData)
        private view
        returns (uint256 lpTokenPrice, uint256[] memory prices)
    {
        // Decode extra data
        (lpTokenPrice, prices) = abi.decode(extraData, (uint256, uint256[]));

        uint256 n = nTokens();
        if (prices.length != n) {
            revert MismatchedArrayLengths();
        }

    }

    function _depositChecks(
        address depositor,
        uint256[] memory depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature memory sig,
        bytes memory extraData
    )
        internal view
        returns (bytes32 digest)
    {
        uint n = nTokens();
        if (n != depositAmounts.length) {
            revert MismatchedArrayLengths();
        }

        // Decode extra data
        (uint256 lpTokenPrice, uint256[] memory prices) = _decodeAndValidatePrices(extraData);

        // Check the signature
        digest = BladeSignatureLib.createDepositDigest(
            DOMAIN_SEPARATOR,
            depositor,
            depositAmounts,
            lockTime,
            poolTokens,
            goodUntil,
            lpTokenPrice,
            prices
        );

        // Verify signature
        _verifyDigestSignature(digest, sig);

        // Revert if the pool state has changed
        _verifyLpTokenStatePool(lpTokenPrice, prices);
    }

    function _singleDepositChecks(
        address depositor,
        address inputToken,
        uint256 inputAmount,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature memory sig,
        bytes memory extraData
    )
        internal view
        returns (bytes32 digest)
    {
        // Decode extra data
        (uint256 lpTokenPrice, uint256[] memory prices) = _decodeAndValidatePrices(extraData);

        // Check the signature
        digest = BladeSignatureLib.createSingleDepositDigest(
            DOMAIN_SEPARATOR,
            depositor,
            inputToken,
            inputAmount,
            lockTime,
            poolTokens,
            goodUntil,
            lpTokenPrice,
            prices
        );

        // Verify signature
        _verifyDigestSignature(digest, sig);

        // Revert if the pool state has changed
        _verifyLpTokenStatePool(lpTokenPrice, prices);
    }

    function _singleWithdrawChecks(
        address tokenHolder,
        uint256 poolTokenAmountToBurn,
        address assetAddress,
        uint256 assetAmount,
        uint256 goodUntil,
        Signature calldata sig,
        bytes calldata extraData
    )
        internal view
        returns (bytes32 digest)
    {
        // Decode extra data
        (uint256 lpTokenPrice, uint256[] memory prices) = _decodeAndValidatePrices(extraData);

        // Check the signature
        digest = BladeSignatureLib.createWithdrawalDigest(
            DOMAIN_SEPARATOR,
            tokenHolder,
            poolTokenAmountToBurn,
            assetAddress,
            assetAmount,
            goodUntil,
            lpTokenPrice,
            prices
        );

        // Revert if it's signed by the wrong address
        // Revert if it's a replay, or if the timestamp is too late
        _verifyDigestSignature(digest, sig);

        // Revert if the pool state has changed
        _verifyLpTokenStatePool(lpTokenPrice, prices);
    }

    function _finalizeDeposit(
        address depositor,
        uint256 lockTime,
        uint256 poolTokens
    )
    internal
    {
        _createVestingDeposit(depositor, lockTime, poolTokens);
        emit Deposited(depositor, poolTokens, lockTime);
    }

    /* WITHDRAWAL FUNCTIONALITY */
    function _proportionalWithdrawal(uint256 myFraction) private {
        uint256 toTransfer;

        uint i;
        uint n = nTokens();
        while(i < n) {
            address theToken = tokenAt(i);
            toTransfer = (myFraction * getLastBalance(theToken)) / ONE_IN_TEN_DECIMALS;
            // syncs done automatically on transfer
            transferAsset(theToken, msg.sender, toTransfer);
            i++;
        }
    }

    function burnToWithdraw(uint256 amount) external {
        // Capture the fraction first, before burning
        uint256 theFractionBaseTen = (ONE_IN_TEN_DECIMALS * amount) / totalSupply();

        // Reverts if balance is insufficient
        _burn(msg.sender, amount);

        _proportionalWithdrawal(theFractionBaseTen);
        emit Withdrawn(msg.sender, amount, theFractionBaseTen);
    }

    function _verifySwapSignature(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature memory sig
    )
        internal view
        returns (bytes32 digest)
    {
        digest = BladeSignatureLib.createSwapDigest(
            DOMAIN_SEPARATOR,
            inputToken,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress
        );

        _verifyDigestSignature(digest, sig);
    }

    function _wrapMsgValue() internal {
        if (msg.value > 0) {
            safeEthSend(WRAPPER_CONTRACT, msg.value);
        }
    }
}

File 25 of 65 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;

/// @notice The unsigned 2.18-decimal fixed-point number representation, which can have up to 2 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type uint64. This is useful when end users want to use uint64 to save gas, e.g. with tight variable packing in contract
/// storage.
type UD2x18 is uint64;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD59x18,
    Casting.intoUD60x18,
    Casting.intoUint128,
    Casting.intoUint256,
    Casting.intoUint40,
    Casting.unwrap
} for UD2x18 global;

File 26 of 65 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { UD2x18 } from "./ValueType.sol";

/// @notice Casts a UD2x18 number into SD59x18.
/// @dev There is no overflow check because UD2x18 ? SD59x18.
function intoSD59x18(UD2x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(uint256(UD2x18.unwrap(x))));
}

/// @notice Casts a UD2x18 number into UD60x18.
/// @dev There is no overflow check because UD2x18 ? UD60x18.
function intoUD60x18(UD2x18 x) pure returns (UD60x18 result) {
    result = UD60x18.wrap(UD2x18.unwrap(x));
}

/// @notice Casts a UD2x18 number into uint128.
/// @dev There is no overflow check because UD2x18 ? uint128.
function intoUint128(UD2x18 x) pure returns (uint128 result) {
    result = uint128(UD2x18.unwrap(x));
}

/// @notice Casts a UD2x18 number into uint256.
/// @dev There is no overflow check because UD2x18 ? uint256.
function intoUint256(UD2x18 x) pure returns (uint256 result) {
    result = uint256(UD2x18.unwrap(x));
}

/// @notice Casts a UD2x18 number into uint40.
/// @dev Requirements:
/// - x = MAX_UINT40
function intoUint40(UD2x18 x) pure returns (uint40 result) {
    uint64 xUint = UD2x18.unwrap(x);
    if (xUint > uint64(Common.MAX_UINT40)) {
        revert Errors.PRBMath_UD2x18_IntoUint40_Overflow(x);
    }
    result = uint40(xUint);
}

/// @notice Alias for {wrap}.
function ud2x18(uint64 x) pure returns (UD2x18 result) {
    result = UD2x18.wrap(x);
}

/// @notice Unwrap a UD2x18 number into uint64.
function unwrap(UD2x18 x) pure returns (uint64 result) {
    result = UD2x18.unwrap(x);
}

/// @notice Wraps a uint64 number into UD2x18.
function wrap(uint64 x) pure returns (UD2x18 result) {
    result = UD2x18.wrap(x);
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

pragma solidity ^0.8.20;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        (1 << 0x08) | // backspace
            (1 << 0x09) | // tab
            (1 << 0x0a) | // newline
            (1 << 0x0c) | // form feed
            (1 << 0x0d) | // carriage return
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
     * RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
     * characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);
        bytes memory output = new bytes(2 * buffer.length); // worst case scenario
        uint256 outputLength = 0;

        for (uint256 i; i < buffer.length; ++i) {
            bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
            if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
                output[outputLength++] = "\\";
                if (char == 0x08) output[outputLength++] = "b";
                else if (char == 0x09) output[outputLength++] = "t";
                else if (char == 0x0a) output[outputLength++] = "n";
                else if (char == 0x0c) output[outputLength++] = "f";
                else if (char == 0x0d) output[outputLength++] = "r";
                else if (char == 0x5c) output[outputLength++] = "\\";
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    output[outputLength++] = '"';
                }
            } else {
                output[outputLength++] = char;
            }
        }
        // write the actual length and deallocate unused memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(buffer, add(0x20, offset)))
        }
    }
}

File 30 of 65 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD60x18 } from "./ValueType.sol";

/// @notice Thrown when ceiling a number overflows UD60x18.
error PRBMath_UD60x18_Ceil_Overflow(UD60x18 x);

/// @notice Thrown when converting a basic integer to the fixed-point format overflows UD60x18.
error PRBMath_UD60x18_Convert_Overflow(uint256 x);

/// @notice Thrown when taking the natural exponent of a base greater than 133_084258667509499441.
error PRBMath_UD60x18_Exp_InputTooBig(UD60x18 x);

/// @notice Thrown when taking the binary exponent of a base greater than 192e18.
error PRBMath_UD60x18_Exp2_InputTooBig(UD60x18 x);

/// @notice Thrown when taking the geometric mean of two numbers and multiplying them overflows UD60x18.
error PRBMath_UD60x18_Gm_Overflow(UD60x18 x, UD60x18 y);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD1x18.
error PRBMath_UD60x18_IntoSD1x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD21x18.
error PRBMath_UD60x18_IntoSD21x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in SD59x18.
error PRBMath_UD60x18_IntoSD59x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD2x18.
error PRBMath_UD60x18_IntoUD2x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in UD21x18.
error PRBMath_UD60x18_IntoUD21x18_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint128.
error PRBMath_UD60x18_IntoUint128_Overflow(UD60x18 x);

/// @notice Thrown when trying to cast a UD60x18 number that doesn't fit in uint40.
error PRBMath_UD60x18_IntoUint40_Overflow(UD60x18 x);

/// @notice Thrown when taking the logarithm of a number less than UNIT.
error PRBMath_UD60x18_Log_InputTooSmall(UD60x18 x);

/// @notice Thrown when calculating the square root overflows UD60x18.
error PRBMath_UD60x18_Sqrt_Overflow(UD60x18 x);

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

File 32 of 65 : Constants.sol
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.20;

library Constants {
    uint256 constant ONE_IN_BASIS_POINTS = 10000;
    uint8 constant PRICE_TOLERANCE_IN_BPS = 10;
    uint256 constant ONE_IN_DEFAULT_DECIMALS = 1e18;
}

File 33 of 65 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;

/// @notice The signed 21.18-decimal fixed-point number representation, which can have up to 21 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int128. This is useful when end users want to use int128 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD21x18 is int128;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD59x18,
    Casting.intoUD60x18,
    Casting.intoUint128,
    Casting.intoUint256,
    Casting.intoUint40,
    Casting.unwrap
} for SD21x18 global;

// SPDX-License-Identifier: UNLICENSED
// Copyright 2024 Shipyard Software, Inc.
pragma solidity ^0.8.20;

import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";

// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

library SafeAggregatorInterface {
    using SafeCast for int256;

    error OracleStalePrice();

    // Returns the latest price from the oracle as a uint256, reverting if invalid or older than minimumTime
    function safeUnsignedLatest(address oracle, uint256 minimumTime) internal view returns (uint256) {
        (uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound) = AggregatorV3Interface(oracle).latestRoundData();
        if (roundId != answeredInRound || updatedAt + minimumTime <= block.timestamp) {
            revert OracleStalePrice();
        }

        return answer.toUint256();
    }
}

File 35 of 65 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;
import "./Helpers.sol" as Helpers;
import "./Math.sol" as Math;

/// @notice The unsigned 60.18-decimal fixed-point number representation, which can have up to 60 digits and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the Solidity type uint256.
/// @dev The value type is defined here so it can be imported in all other files.
type UD60x18 is uint256;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD1x18,
    Casting.intoSD21x18,
    Casting.intoSD59x18,
    Casting.intoUD2x18,
    Casting.intoUD21x18,
    Casting.intoUint128,
    Casting.intoUint256,
    Casting.intoUint40,
    Casting.unwrap
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                            MATHEMATICAL FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
    Math.avg,
    Math.ceil,
    Math.div,
    Math.exp,
    Math.exp2,
    Math.floor,
    Math.frac,
    Math.gm,
    Math.inv,
    Math.ln,
    Math.log10,
    Math.log2,
    Math.mul,
    Math.pow,
    Math.powu,
    Math.sqrt
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                HELPER FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes the functions in this library callable on the UD60x18 type.
using {
    Helpers.add,
    Helpers.and,
    Helpers.eq,
    Helpers.gt,
    Helpers.gte,
    Helpers.isZero,
    Helpers.lshift,
    Helpers.lt,
    Helpers.lte,
    Helpers.mod,
    Helpers.neq,
    Helpers.not,
    Helpers.or,
    Helpers.rshift,
    Helpers.sub,
    Helpers.uncheckedAdd,
    Helpers.uncheckedSub,
    Helpers.xor
} for UD60x18 global;

/*//////////////////////////////////////////////////////////////////////////
                                    OPERATORS
//////////////////////////////////////////////////////////////////////////*/

// The global "using for" directive makes it possible to use these operators on the UD60x18 type.
using {
    Helpers.add as +,
    Helpers.and2 as &,
    Math.div as /,
    Helpers.eq as ==,
    Helpers.gt as >,
    Helpers.gte as >=,
    Helpers.lt as <,
    Helpers.lte as <=,
    Helpers.or as |,
    Helpers.mod as %,
    Math.mul as *,
    Helpers.neq as !=,
    Helpers.not as ~,
    Helpers.sub as -,
    Helpers.xor as ^
} for UD60x18 global;

File 36 of 65 : SD59x18.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

/*

¦¦¦¦¦¦+ ¦¦¦¦¦¦+ ¦¦¦¦¦¦+ ¦¦¦+   ¦¦¦+ ¦¦¦¦¦+ ¦¦¦¦¦¦¦¦+¦¦+  ¦¦+
¦¦+--¦¦+¦¦+--¦¦+¦¦+--¦¦+¦¦¦¦+ ¦¦¦¦¦¦¦+--¦¦++--¦¦+--+¦¦¦  ¦¦¦
¦¦¦¦¦¦++¦¦¦¦¦¦++¦¦¦¦¦¦++¦¦+¦¦¦¦+¦¦¦¦¦¦¦¦¦¦¦   ¦¦¦   ¦¦¦¦¦¦¦¦
¦¦+---+ ¦¦+--¦¦+¦¦+--¦¦+¦¦¦+¦¦++¦¦¦¦¦+--¦¦¦   ¦¦¦   ¦¦+--¦¦¦
¦¦¦     ¦¦¦  ¦¦¦¦¦¦¦¦¦++¦¦¦ +-+ ¦¦¦¦¦¦  ¦¦¦   ¦¦¦   ¦¦¦  ¦¦¦
+-+     +-+  +-++-----+ +-+     +-++-+  +-+   +-+   +-+  +-+

¦¦¦¦¦¦¦+¦¦¦¦¦¦+ ¦¦¦¦¦¦¦+ ¦¦¦¦¦+ ¦¦+  ¦¦+ ¦¦+ ¦¦¦¦¦+
¦¦+----+¦¦+--¦¦+¦¦+----+¦¦+--¦¦++¦¦+¦¦++¦¦¦¦¦¦+--¦¦+
¦¦¦¦¦¦¦+¦¦¦  ¦¦¦¦¦¦¦¦¦¦++¦¦¦¦¦¦¦ +¦¦¦++ +¦¦¦+¦¦¦¦¦++
+----¦¦¦¦¦¦  ¦¦¦+----¦¦¦ +---¦¦¦ ¦¦+¦¦+  ¦¦¦¦¦+--¦¦+
¦¦¦¦¦¦¦¦¦¦¦¦¦¦++¦¦¦¦¦¦¦¦ ¦¦¦¦¦++¦¦++ ¦¦+ ¦¦¦+¦¦¦¦¦++
+------++-----+ +------+ +----+ +-+  +-+ +-+ +----+

*/

import "./sd59x18/Casting.sol";
import "./sd59x18/Constants.sol";
import "./sd59x18/Conversions.sol";
import "./sd59x18/Errors.sol";
import "./sd59x18/Helpers.sol";
import "./sd59x18/Math.sol";
import "./sd59x18/ValueType.sol";

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

import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

import {Signature} from "../types/BladeTypes.sol";

library BladeSignatureLib {
    error SignatureValidation();

    bytes32 internal constant EIP712DOMAIN_TYPEHASH =
        keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );

    bytes32 internal constant OFFERSTRUCT_TYPEHASH =
        keccak256(
            abi.encodePacked(
                "OfferStruct(address input_token,address output_token,uint256 input_amount,uint256 output_amount,uint256 good_until,address destination_address)"
            )
        );

    bytes32 internal constant DEPOSITSTRUCT_TYPEHASH =
        keccak256(
            abi.encodePacked(
                "DepositStruct(address depositor,uint256[] deposit_amounts,uint256 lock_time,uint256 pool_tokens,uint256 good_until,uint256 lp_token_price,uint256[] prices)"
            )
        );

    bytes32 internal constant SINGLEDEPOSITSTRUCT_TYPEHASH =
        keccak256(
            abi.encodePacked(
                "SingleDepositStruct(address depositor,address token,uint256 amount,uint256 lock_time,uint256 pool_tokens,uint256 good_until,uint256 lp_token_price,uint256[] prices)"
            )
        );

    bytes32 internal constant WITHDRAWALSTRUCT_TYPEHASH =
        keccak256(
            abi.encodePacked(
                "WithdrawalStruct(address token_holder,uint256 pool_token_amount_to_burn,address asset_address,uint256 asset_amount,uint256 good_until,uint256 lp_token_price,uint256[] prices)"
            )
        );

    function createDomainSeparator(
        string memory name,
        string memory version,
        address theSigner
    )
        internal view
        returns (bytes32)
    {
        return
            keccak256(
                abi.encode(
                    EIP712DOMAIN_TYPEHASH,
                    keccak256(abi.encodePacked(name)),
                    keccak256(abi.encodePacked(version)),
                    uint256(block.chainid),
                    theSigner
                )
            );
    }

    function hashInputOffer(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress
    )
        internal pure
        returns (bytes32)
    {
        return
            keccak256(
                abi.encode(
                    OFFERSTRUCT_TYPEHASH,
                    inputToken,
                    outputToken,
                    inputAmount,
                    outputAmount,
                    goodUntil,
                    destinationAddress
                )
            );
    }

    function hashDeposit(
        address depositor,
        uint256[] memory depositAmounts,
        uint256 minutesLocked,
        uint256 poolTokens,
        uint256 goodUntil,
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        internal pure
        returns (bytes32)
    {
        bytes32 depositAmountsHash = keccak256(
            abi.encodePacked(depositAmounts)
        );
        bytes32 pricesHash = keccak256(abi.encodePacked(prices));
        return
            keccak256(
                abi.encode(
                    DEPOSITSTRUCT_TYPEHASH,
                    depositor,
                    depositAmountsHash,
                    minutesLocked,
                    poolTokens,
                    goodUntil,
                    lpTokenPrice,
                    pricesHash
                )
            );
    }

    function hashSingleDeposit(
        address depositor,
        address inputToken,
        uint256 inputAmount,
        uint256 minutesLocked,
        uint256 poolTokens,
        uint256 goodUntil,
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        internal pure
        returns (bytes32)
    {
        bytes32 pricesHash = keccak256(abi.encodePacked(prices));
        return
            keccak256(
                abi.encode(
                    SINGLEDEPOSITSTRUCT_TYPEHASH,
                    depositor,
                    inputToken,
                    inputAmount,
                    minutesLocked,
                    poolTokens,
                    goodUntil,
                    lpTokenPrice,
                    pricesHash
                )
            );
    }

    function hashWithdrawal(
        address tokenHolder,
        uint256 poolTokenAmountToBurn,
        address assetAddress,
        uint256 assetAmount,
        uint256 goodUntil,
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        internal pure
        returns (bytes32)
    {
        bytes32 pricesHash = keccak256(abi.encodePacked(prices));
        return
            keccak256(
                abi.encode(
                    WITHDRAWALSTRUCT_TYPEHASH,
                    tokenHolder,
                    poolTokenAmountToBurn,
                    assetAddress,
                    assetAmount,
                    goodUntil,
                    lpTokenPrice,
                    pricesHash
                )
            );
    }

    function createSwapDigest(
        bytes32 domainSeparator,
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress
    )
        internal pure
        returns (bytes32 digest)
    {
        bytes32 hashedInput = hashInputOffer(
            inputToken,
            outputToken,
            inputAmount,
            outputAmount,
            goodUntil,
            destinationAddress
        );
        digest = MessageHashUtils.toTypedDataHash(domainSeparator, hashedInput);
    }

    function createDepositDigest(
        bytes32 domainSeparator,
        address depositor,
        uint256[] memory depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        internal pure
        returns (bytes32 depositDigest)
    {
        bytes32 hashedInput = hashDeposit(
            depositor,
            depositAmounts,
            lockTime,
            poolTokens,
            goodUntil,
            lpTokenPrice,
            prices
        );
        depositDigest = MessageHashUtils.toTypedDataHash(
            domainSeparator,
            hashedInput
        );
    }

    function createSingleDepositDigest(
        bytes32 domainSeparator,
        address depositor,
        address inputToken,
        uint256 inputAmount,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        internal pure
        returns (bytes32 depositDigest)
    {
        bytes32 hashedInput = hashSingleDeposit(
            depositor,
            inputToken,
            inputAmount,
            lockTime,
            poolTokens,
            goodUntil,
            lpTokenPrice,
            prices
        );
        depositDigest = MessageHashUtils.toTypedDataHash(
            domainSeparator,
            hashedInput
        );
    }

    function createWithdrawalDigest(
        bytes32 domainSeparator,
        address tokenHolder,
        uint256 poolTokenAmountToBurn,
        address assetAddress,
        uint256 assetAmount,
        uint256 goodUntil,
        uint256 lpTokenPrice,
        uint256[] memory prices
    )
        internal pure
        returns (bytes32 withdrawalDigest)
    {
        bytes32 hashedInput = hashWithdrawal(
            tokenHolder,
            poolTokenAmountToBurn,
            assetAddress,
            assetAmount,
            goodUntil,
            lpTokenPrice,
            prices
        );
        withdrawalDigest = MessageHashUtils.toTypedDataHash(
            domainSeparator,
            hashedInput
        );
    }

    function verifyDigestSignature(
        bytes32 digest,
        Signature memory sig,
        address expectedSigner
    )
        internal view
    {
        address signer = ECDSA.recover(digest, sig.v, sig.r, sig.s);

        if (signer != expectedSigner) {
            // Check for signing with embedded tx.origin
            signer = ECDSA.recover(
                keccak256(abi.encodePacked(digest, tx.origin)),
                sig.v,
                sig.r,
                sig.s
            );
            if (signer != expectedSigner) {
                revert SignatureValidation();
            }
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
 * corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
 * the solidity language / compiler.
 *
 * See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
 *
 * Example usage:
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using StorageSlot for bytes32;
 *     using SlotDerivation for bytes32;
 *
 *     // Declare a namespace
 *     string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
 *
 *     function setValueInNamespace(uint256 key, address newValue) internal {
 *         _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
 *     }
 *
 *     function getValueInNamespace(uint256 key) internal view returns (address) {
 *         return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {StorageSlot}.
 *
 * NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
 * upgrade safety will ignore the slots accessed through this library.
 *
 * _Available since v5.1._
 */
library SlotDerivation {
    /**
     * @dev Derive an ERC-7201 slot from a string (namespace).
     */
    function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
        assembly ("memory-safe") {
            mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
            slot := and(keccak256(0x00, 0x20), not(0xff))
        }
    }

    /**
     * @dev Add an offset to a slot to get the n-th element of a structure or an array.
     */
    function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
        unchecked {
            return bytes32(uint256(slot) + pos);
        }
    }

    /**
     * @dev Derive the location of the first element in an array from the slot where the length is stored.
     */
    function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, slot)
            result := keccak256(0x00, 0x20)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, and(key, shr(96, not(0))))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, iszero(iszero(key)))
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            mstore(0x00, key)
            mstore(0x20, slot)
            result := keccak256(0x00, 0x40)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }

    /**
     * @dev Derive the location of a mapping element from the key.
     */
    function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
        assembly ("memory-safe") {
            let length := mload(key)
            let begin := add(key, 0x20)
            let end := add(begin, length)
            let cache := mload(end)
            mstore(end, slot)
            result := keccak256(begin, add(length, 0x20))
            mstore(end, cache)
        }
    }
}

File 39 of 65 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD60x18 } from "./ValueType.sol";

// NOTICE: the "u" prefix stands for "unwrapped".

/// @dev Euler's number as a UD60x18 number.
UD60x18 constant E = UD60x18.wrap(2_718281828459045235);

/// @dev The maximum input permitted in {exp}.
uint256 constant uEXP_MAX_INPUT = 133_084258667509499440;
UD60x18 constant EXP_MAX_INPUT = UD60x18.wrap(uEXP_MAX_INPUT);

/// @dev The maximum input permitted in {exp2}.
uint256 constant uEXP2_MAX_INPUT = 192e18 - 1;
UD60x18 constant EXP2_MAX_INPUT = UD60x18.wrap(uEXP2_MAX_INPUT);

/// @dev Half the UNIT number.
uint256 constant uHALF_UNIT = 0.5e18;
UD60x18 constant HALF_UNIT = UD60x18.wrap(uHALF_UNIT);

/// @dev $log_2(10)$ as a UD60x18 number.
uint256 constant uLOG2_10 = 3_321928094887362347;
UD60x18 constant LOG2_10 = UD60x18.wrap(uLOG2_10);

/// @dev $log_2(e)$ as a UD60x18 number.
uint256 constant uLOG2_E = 1_442695040888963407;
UD60x18 constant LOG2_E = UD60x18.wrap(uLOG2_E);

/// @dev The maximum value a UD60x18 number can have.
uint256 constant uMAX_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_584007913129639935;
UD60x18 constant MAX_UD60x18 = UD60x18.wrap(uMAX_UD60x18);

/// @dev The maximum whole value a UD60x18 number can have.
uint256 constant uMAX_WHOLE_UD60x18 = 115792089237316195423570985008687907853269984665640564039457_000000000000000000;
UD60x18 constant MAX_WHOLE_UD60x18 = UD60x18.wrap(uMAX_WHOLE_UD60x18);

/// @dev PI as a UD60x18 number.
UD60x18 constant PI = UD60x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of UD60x18.
uint256 constant uUNIT = 1e18;
UD60x18 constant UNIT = UD60x18.wrap(uUNIT);

/// @dev The unit number squared.
uint256 constant uUNIT_SQUARED = 1e36;
UD60x18 constant UNIT_SQUARED = UD60x18.wrap(uUNIT_SQUARED);

/// @dev Zero as a UD60x18 number.
UD60x18 constant ZERO = UD60x18.wrap(0);

File 40 of 65 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD21x18 } from "./ValueType.sol";

/// @notice Thrown when trying to cast a UD21x18 number that doesn't fit in uint40.
error PRBMath_UD21x18_IntoUint40_Overflow(UD21x18 x);

File 41 of 65 : Common.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

// Common.sol
//
// Common mathematical functions used in both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.

/*//////////////////////////////////////////////////////////////////////////
                                CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);

/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);

/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();

/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);

/*//////////////////////////////////////////////////////////////////////////
                                    CONSTANTS
//////////////////////////////////////////////////////////////////////////*/

/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;

/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;

/// @dev The maximum value a uint64 number can have.
uint64 constant MAX_UINT64 = type(uint64).max;

/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;

/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;

/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;

/*//////////////////////////////////////////////////////////////////////////
                                    FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
    unchecked {
        // Start from 0.5 in the 192.64-bit fixed-point format.
        result = 0x800000000000000000000000000000000000000000000000;

        // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
        //
        // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
        // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
        // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
        // we know that `x & 0xFF` is also 1.
        if (x & 0xFF00000000000000 > 0) {
            if (x & 0x8000000000000000 > 0) {
                result = (result * 0x16A09E667F3BCC909) >> 64;
            }
            if (x & 0x4000000000000000 > 0) {
                result = (result * 0x1306FE0A31B7152DF) >> 64;
            }
            if (x & 0x2000000000000000 > 0) {
                result = (result * 0x1172B83C7D517ADCE) >> 64;
            }
            if (x & 0x1000000000000000 > 0) {
                result = (result * 0x10B5586CF9890F62A) >> 64;
            }
            if (x & 0x800000000000000 > 0) {
                result = (result * 0x1059B0D31585743AE) >> 64;
            }
            if (x & 0x400000000000000 > 0) {
                result = (result * 0x102C9A3E778060EE7) >> 64;
            }
            if (x & 0x200000000000000 > 0) {
                result = (result * 0x10163DA9FB33356D8) >> 64;
            }
            if (x & 0x100000000000000 > 0) {
                result = (result * 0x100B1AFA5ABCBED61) >> 64;
            }
        }

        if (x & 0xFF000000000000 > 0) {
            if (x & 0x80000000000000 > 0) {
                result = (result * 0x10058C86DA1C09EA2) >> 64;
            }
            if (x & 0x40000000000000 > 0) {
                result = (result * 0x1002C605E2E8CEC50) >> 64;
            }
            if (x & 0x20000000000000 > 0) {
                result = (result * 0x100162F3904051FA1) >> 64;
            }
            if (x & 0x10000000000000 > 0) {
                result = (result * 0x1000B175EFFDC76BA) >> 64;
            }
            if (x & 0x8000000000000 > 0) {
                result = (result * 0x100058BA01FB9F96D) >> 64;
            }
            if (x & 0x4000000000000 > 0) {
                result = (result * 0x10002C5CC37DA9492) >> 64;
            }
            if (x & 0x2000000000000 > 0) {
                result = (result * 0x1000162E525EE0547) >> 64;
            }
            if (x & 0x1000000000000 > 0) {
                result = (result * 0x10000B17255775C04) >> 64;
            }
        }

        if (x & 0xFF0000000000 > 0) {
            if (x & 0x800000000000 > 0) {
                result = (result * 0x1000058B91B5BC9AE) >> 64;
            }
            if (x & 0x400000000000 > 0) {
                result = (result * 0x100002C5C89D5EC6D) >> 64;
            }
            if (x & 0x200000000000 > 0) {
                result = (result * 0x10000162E43F4F831) >> 64;
            }
            if (x & 0x100000000000 > 0) {
                result = (result * 0x100000B1721BCFC9A) >> 64;
            }
            if (x & 0x80000000000 > 0) {
                result = (result * 0x10000058B90CF1E6E) >> 64;
            }
            if (x & 0x40000000000 > 0) {
                result = (result * 0x1000002C5C863B73F) >> 64;
            }
            if (x & 0x20000000000 > 0) {
                result = (result * 0x100000162E430E5A2) >> 64;
            }
            if (x & 0x10000000000 > 0) {
                result = (result * 0x1000000B172183551) >> 64;
            }
        }

        if (x & 0xFF00000000 > 0) {
            if (x & 0x8000000000 > 0) {
                result = (result * 0x100000058B90C0B49) >> 64;
            }
            if (x & 0x4000000000 > 0) {
                result = (result * 0x10000002C5C8601CC) >> 64;
            }
            if (x & 0x2000000000 > 0) {
                result = (result * 0x1000000162E42FFF0) >> 64;
            }
            if (x & 0x1000000000 > 0) {
                result = (result * 0x10000000B17217FBB) >> 64;
            }
            if (x & 0x800000000 > 0) {
                result = (result * 0x1000000058B90BFCE) >> 64;
            }
            if (x & 0x400000000 > 0) {
                result = (result * 0x100000002C5C85FE3) >> 64;
            }
            if (x & 0x200000000 > 0) {
                result = (result * 0x10000000162E42FF1) >> 64;
            }
            if (x & 0x100000000 > 0) {
                result = (result * 0x100000000B17217F8) >> 64;
            }
        }

        if (x & 0xFF000000 > 0) {
            if (x & 0x80000000 > 0) {
                result = (result * 0x10000000058B90BFC) >> 64;
            }
            if (x & 0x40000000 > 0) {
                result = (result * 0x1000000002C5C85FE) >> 64;
            }
            if (x & 0x20000000 > 0) {
                result = (result * 0x100000000162E42FF) >> 64;
            }
            if (x & 0x10000000 > 0) {
                result = (result * 0x1000000000B17217F) >> 64;
            }
            if (x & 0x8000000 > 0) {
                result = (result * 0x100000000058B90C0) >> 64;
            }
            if (x & 0x4000000 > 0) {
                result = (result * 0x10000000002C5C860) >> 64;
            }
            if (x & 0x2000000 > 0) {
                result = (result * 0x1000000000162E430) >> 64;
            }
            if (x & 0x1000000 > 0) {
                result = (result * 0x10000000000B17218) >> 64;
            }
        }

        if (x & 0xFF0000 > 0) {
            if (x & 0x800000 > 0) {
                result = (result * 0x1000000000058B90C) >> 64;
            }
            if (x & 0x400000 > 0) {
                result = (result * 0x100000000002C5C86) >> 64;
            }
            if (x & 0x200000 > 0) {
                result = (result * 0x10000000000162E43) >> 64;
            }
            if (x & 0x100000 > 0) {
                result = (result * 0x100000000000B1721) >> 64;
            }
            if (x & 0x80000 > 0) {
                result = (result * 0x10000000000058B91) >> 64;
            }
            if (x & 0x40000 > 0) {
                result = (result * 0x1000000000002C5C8) >> 64;
            }
            if (x & 0x20000 > 0) {
                result = (result * 0x100000000000162E4) >> 64;
            }
            if (x & 0x10000 > 0) {
                result = (result * 0x1000000000000B172) >> 64;
            }
        }

        if (x & 0xFF00 > 0) {
            if (x & 0x8000 > 0) {
                result = (result * 0x100000000000058B9) >> 64;
            }
            if (x & 0x4000 > 0) {
                result = (result * 0x10000000000002C5D) >> 64;
            }
            if (x & 0x2000 > 0) {
                result = (result * 0x1000000000000162E) >> 64;
            }
            if (x & 0x1000 > 0) {
                result = (result * 0x10000000000000B17) >> 64;
            }
            if (x & 0x800 > 0) {
                result = (result * 0x1000000000000058C) >> 64;
            }
            if (x & 0x400 > 0) {
                result = (result * 0x100000000000002C6) >> 64;
            }
            if (x & 0x200 > 0) {
                result = (result * 0x10000000000000163) >> 64;
            }
            if (x & 0x100 > 0) {
                result = (result * 0x100000000000000B1) >> 64;
            }
        }

        if (x & 0xFF > 0) {
            if (x & 0x80 > 0) {
                result = (result * 0x10000000000000059) >> 64;
            }
            if (x & 0x40 > 0) {
                result = (result * 0x1000000000000002C) >> 64;
            }
            if (x & 0x20 > 0) {
                result = (result * 0x10000000000000016) >> 64;
            }
            if (x & 0x10 > 0) {
                result = (result * 0x1000000000000000B) >> 64;
            }
            if (x & 0x8 > 0) {
                result = (result * 0x10000000000000006) >> 64;
            }
            if (x & 0x4 > 0) {
                result = (result * 0x10000000000000003) >> 64;
            }
            if (x & 0x2 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
            if (x & 0x1 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
        }

        // In the code snippet below, two operations are executed simultaneously:
        //
        // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
        // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
        // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
        //
        // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
        // integer part, $2^n$.
        result *= UNIT;
        result >>= (191 - (x >> 64));
    }
}

/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
///     x >>= 128;
///     result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
    // 2^128
    assembly ("memory-safe") {
        let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^64
    assembly ("memory-safe") {
        let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^32
    assembly ("memory-safe") {
        let factor := shl(5, gt(x, 0xFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^16
    assembly ("memory-safe") {
        let factor := shl(4, gt(x, 0xFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^8
    assembly ("memory-safe") {
        let factor := shl(3, gt(x, 0xFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^4
    assembly ("memory-safe") {
        let factor := shl(2, gt(x, 0xF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^2
    assembly ("memory-safe") {
        let factor := shl(1, gt(x, 0x3))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^1
    // No need to shift x any more.
    assembly ("memory-safe") {
        let factor := gt(x, 0x1)
        result := or(result, factor)
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
    // 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; // Least significant 256 bits of the product
    uint256 prod1; // Most significant 256 bits of the product
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    // Handle non-overflow cases, 256 by 256 division.
    if (prod1 == 0) {
        unchecked {
            return prod0 / denominator;
        }
    }

    // Make sure the result is less than 2^256. Also prevents denominator == 0.
    if (prod1 >= denominator) {
        revert PRBMath_MulDiv_Overflow(x, y, denominator);
    }

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

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

        // Subtract 256 bit number from 512-bit number.
        prod1 := sub(prod1, gt(remainder, prod0))
        prod0 := sub(prod0, remainder)
    }

    unchecked {
        // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
        // because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
        // For more detail, see https://cs.stackexchange.com/q/138556/92363.
        uint256 lpotdod = denominator & (~denominator + 1);
        uint256 flippedLpotdod;

        assembly ("memory-safe") {
            // Factor powers of two out of denominator.
            denominator := div(denominator, lpotdod)

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

            // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
            // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
            // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
            flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
        }

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

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

/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
///     x * y = MAX\_UINT256 * UNIT \\
///     (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
    uint256 prod0;
    uint256 prod1;
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    if (prod1 == 0) {
        unchecked {
            return prod0 / UNIT;
        }
    }

    if (prod1 >= UNIT) {
        revert PRBMath_MulDiv18_Overflow(x, y);
    }

    uint256 remainder;
    assembly ("memory-safe") {
        remainder := mulmod(x, y, UNIT)
        result :=
            mul(
                or(
                    div(sub(prod0, remainder), UNIT_LPOTD),
                    mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
                ),
                UNIT_INVERSE
            )
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
    if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
        revert PRBMath_MulDivSigned_InputTooSmall();
    }

    // Get hold of the absolute values of x, y and the denominator.
    uint256 xAbs;
    uint256 yAbs;
    uint256 dAbs;
    unchecked {
        xAbs = x < 0 ? uint256(-x) : uint256(x);
        yAbs = y < 0 ? uint256(-y) : uint256(y);
        dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
    }

    // Compute the absolute value of x*y÷denominator. The result must fit in int256.
    uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
    if (resultAbs > uint256(type(int256).max)) {
        revert PRBMath_MulDivSigned_Overflow(x, y);
    }

    // Get the signs of x, y and the denominator.
    uint256 sx;
    uint256 sy;
    uint256 sd;
    assembly ("memory-safe") {
        // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
        sx := sgt(x, sub(0, 1))
        sy := sgt(y, sub(0, 1))
        sd := sgt(denominator, sub(0, 1))
    }

    // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
    // If there are, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
    }
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
    if (x == 0) {
        return 0;
    }

    // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
    //
    // We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
    //
    // $$
    // msb(x) <= x <= 2*msb(x)$
    // $$
    //
    // We write $msb(x)$ as $2^k$, and we get:
    //
    // $$
    // k = log_2(x)
    // $$
    //
    // Thus, we can write the initial inequality as:
    //
    // $$
    // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
    // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
    // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
    // $$
    //
    // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
    uint256 xAux = uint256(x);
    result = 1;
    if (xAux >= 2 ** 128) {
        xAux >>= 128;
        result <<= 64;
    }
    if (xAux >= 2 ** 64) {
        xAux >>= 64;
        result <<= 32;
    }
    if (xAux >= 2 ** 32) {
        xAux >>= 32;
        result <<= 16;
    }
    if (xAux >= 2 ** 16) {
        xAux >>= 16;
        result <<= 8;
    }
    if (xAux >= 2 ** 8) {
        xAux >>= 8;
        result <<= 4;
    }
    if (xAux >= 2 ** 4) {
        xAux >>= 4;
        result <<= 2;
    }
    if (xAux >= 2 ** 2) {
        result <<= 1;
    }

    // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
    // most 128 bits, 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 + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;

        // If x is not a perfect square, round the result toward zero.
        uint256 roundedResult = x / result;
        if (result >= roundedResult) {
            result = roundedResult;
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}

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

import { Signature } from "../types/BladeTypes.sol";


/// @title Blade Exchange Interface
/// @notice Shared interface for all Blade exchange implementations
interface IBladeExchange {
    event Swapped(
        address indexed inAsset,
        address indexed outAsset,
        address indexed recipient,
        uint256 inAmount,
        uint256 outAmount,
        bytes auxiliaryData
    );

    event Deposited(
        address indexed depositor,
        uint256 poolTokens,
        uint256 lockTime
    );

    event Withdrawn(
        address indexed withdrawer,
        uint256 poolTokens,
        uint256 fractionOfPool
    );

    event AssetWithdrawn(
        address indexed withdrawer,
        uint256 poolTokens,    
        address indexed assetAddress,
        uint256 assetAmount
    );

    event FeesTaken(
        uint256 entitledFeesInDollars,
        uint256 averagePoolBalanceInDollars,
        uint256 tokensTransferred
    );

    event TriageAddressChanged(address indexed newAddress);
    event MarketHalted(address indexed by);
    event MarketResumed(address indexed by);

    function WRAPPER_CONTRACT() external view returns (address);
    function tokenAt(uint index) external view returns (address);
    function nTokens() external view returns (uint);
    function isToken(address token) external view returns (bool);
    function burnToWithdraw(uint256 amount) external;

    function sellEthForToken(
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    ) external payable;

    function sellTokenForEth(
        address inputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    ) external;

    function transmitAndSellTokenForEth(
        address inputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    ) external;

    function transmitAndSwap(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    ) external;

    function swap(
        address inputToken,
        address outputToken,
        uint256 inputAmount,
        uint256 outputAmount,
        uint256 goodUntil,
        address destinationAddress,
        Signature calldata theSignature,
        bytes calldata auxiliaryData
    ) external;

    function transmitAndDepositSingleAsset(
        address inputToken,
        uint256 inputAmount,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    ) external;

    function deposit(
        address depositor,
        uint256[] calldata depositAmounts,
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    ) external payable;

    function depositSingleAsset(
        address depositor,
        address inputToken,
        uint256 inputAmount, 
        uint256 lockTime,
        uint256 poolTokens,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    ) external payable;

    function withdrawSingleAsset(
        address tokenHolder,
        uint256 poolTokenAmountToBurn,
        address assetAddress,
        uint256 assetAmount,
        uint256 goodUntil,
        Signature calldata theSignature,
        bytes calldata extraData
    ) external;
}

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import "../base/BladeErrors.sol";
import {Constants} from "../base/Constants.sol";
import {UtilStruct} from "../types/BladeTypes.sol";
import {SafeAggregatorInterface, AggregatorV3Interface} from "../libraries/SafeAggregatorInterface.sol";


abstract contract OracleManager is Ownable {
    using SafeERC20 for IERC20;
    using SafeCast for uint256;
    using SafeCast for int256;

    struct OracleInfo {
        address oracleAddress;
        uint256 minTimeTolerance;
        uint8 decimals;
    }

    address public sequencerUptimeFeed;
    uint256 private constant GRACE_PERIOD_TIME = 3600;
    mapping(address => OracleInfo) oracles;
    uint8 constant ORACLE_TOLERANCE_IN_BPS = 200; // 2% tolerance in basis points;
    uint8 constant LP_VALUE_TOLERANCE_IN_BPS = 20; // 0.2 %;

    event OracleAdded(
        address indexed token,
        address oracleAddress,
        uint256 minTimeTolerance
    );
    event OracleRemoved(address indexed token);
    event SequencerUptimeFeedAdded(
        address sequencerUptimeFeed
    );

    error OracleSwapDeviation();
    error OracleValueDeviation();
    error OracleNotSet();
    error InvalidOracle();
    error InvalidSequencerFeed();
    error SequencerDown();
    error GracePeriodNotOver();

    constructor(
        address[] memory tokens,
        address[] memory _oracles,
        uint256[] memory minTimeTolerances
    )
    {
        if (_oracles.length > 0) {
            if (
                tokens.length != _oracles.length ||
                tokens.length != minTimeTolerances.length
            ) {
                revert MismatchedArrayLengths();
            }

            for (uint i = 0; i < tokens.length; i++) {
                oracles[tokens[i]] = OracleInfo({
                    oracleAddress: _oracles[i],
                    minTimeTolerance: minTimeTolerances[i],
                    decimals: AggregatorV3Interface(_oracles[i]).decimals()
                });
            }
        }
    }

    function _isToken(address token) internal view virtual returns (bool);
    function _nTokens() internal view virtual returns (uint);
    function _tokenAt(uint index) internal view virtual returns (address);
    function _getLastBalance(address token) internal view virtual returns (uint256);
    function _getTokenDecimals(address token) internal view virtual returns (uint8);

    /// @notice Set or update the Chainlink sequencer uptime feed
    function setSequencerUptimeFeed(
        address feedAddress
    )
        external
        onlyOwner
    {
        _validateFeedAddress(feedAddress);
        sequencerUptimeFeed = feedAddress;

        emit SequencerUptimeFeedAdded(feedAddress);
    }

    /// @notice Validates that the feed implements latestRoundData
    function _validateFeedAddress(address feed) internal view {
        if (feed == address(0)) revert InvalidSequencerFeed();

        // Try-catch to ensure interface call does not revert
        try AggregatorV3Interface(feed).latestRoundData() returns (
            uint80, int256, uint256, uint256, uint80
        ) {
            // pass
        } catch {
            revert InvalidSequencerFeed();
        }
    }

    /// @notice Validate that the sequencer is up and grace period has passed
    function _enforceSequencerIsUp() internal view {
        if (sequencerUptimeFeed == address(0)) {
            // No sequencer feed set, skip validation
            return;
        }

        // prettier-ignore
        (
            /*uint80 roundID*/,
            int256 answer,
            uint256 startedAt,
            /*uint256 updatedAt*/,
            /*uint80 answeredInRound*/
        ) = AggregatorV3Interface(sequencerUptimeFeed).latestRoundData();

        // Answer == 0: Sequencer is up
        // Answer == 1: Sequencer is down
        if (answer != 0) {
            revert SequencerDown();
        }

        // Make sure the grace period has passed after the
        // sequencer is back up.
        uint256 timeSinceUp = block.timestamp - startedAt;
        if (timeSinceUp <= GRACE_PERIOD_TIME) {
            revert GracePeriodNotOver();
        }

    }

    function addOracle(
        address token,
        address oracleAddress,
        uint256 minTimeTolerance
    )
        external
        onlyOwner
    {
        if (minTimeTolerance <= 0) {
            revert InvalidOracle();
        }

        if (!_isToken(token)) {
            revert TokenNotInPool();
        }

        uint256 latestPrice = SafeAggregatorInterface.safeUnsignedLatest(
            oracleAddress,
            minTimeTolerance
        );
        if (latestPrice <= 0) {
            revert InvalidOracle();
        }

        oracles[token] = OracleInfo({
            oracleAddress: oracleAddress,
            minTimeTolerance: minTimeTolerance,
            decimals: AggregatorV3Interface(oracleAddress).decimals()
        });

        emit OracleAdded(token, oracleAddress, minTimeTolerance);
    }

    function removeOracle(address token) external onlyOwner {
        if (oracles[token].oracleAddress == address(0)) {
            revert OracleNotSet();
        }

        delete oracles[token];
        emit OracleRemoved(token);
    }

    /**
     * @notice Returns the USD value of a given token amount using the current oracle price.
     * @dev Prices must use 18 decimals. Token amounts are normalized to 18 decimals before multiplying by price.
     * @param inputToken The address of the token to value.
     * @param inputAmount The amount of the token, using its native decimals.
     * @return The USD value of the token amount, using 18 decimals.
     */
    function _getAssetAmountUsdValue(
        address inputToken,
        uint256 inputAmount
    )
        internal view
        returns (uint256)
    {
        (uint256 inputPrice, uint8 priceDecimals) = currentOraclePriceWithDecimals(inputToken);

        uint256 tokenMultiplier = 10 ** (18 - _getTokenDecimals(inputToken));
        uint256 normalizedAmount = inputAmount * tokenMultiplier;

        // Normalize to 18 decimals and calculate the deposit value
        uint256 usdValue = (normalizedAmount * inputPrice) / (10 ** priceDecimals);

        return usdValue;
    }

    /**
     * @notice Calculates the current LP token price and total pool value using oracle prices.
     * @dev If no LP tokens exist yet, returns a base price. Prices must use 18 decimals.
     * @return lpPrice The LP token price in USD using 18 decimals.
     */
    function _getLpTokenPrice(uint256 _totalSupply) internal view returns (uint256 lpPrice) {
        uint256 n = _nTokens();
        uint256 totalValue;
        for (uint i = 0; i < n; ++i) {
            address token = _tokenAt(i);
            totalValue += _getAssetAmountUsdValue(token, _getLastBalance(token));
        }

        if (_totalSupply > 0) {
            lpPrice = (totalValue * Constants.ONE_IN_DEFAULT_DECIMALS) / _totalSupply;
        } else {
            lpPrice = Constants.ONE_IN_DEFAULT_DECIMALS;
        }
    }

    /**
     * @notice Reverts if the actual value exceeds the reference value plus allowed tolerance.
     * @param actualValue The actual USD value (e.g., LP tokens).
     * @param referenceValue The expected USD value (e.g., tokens deposit).
     */
    function _revertIfDeviationTooHigh(uint256 actualValue, uint256 referenceValue) internal pure {
        uint256 tolerance = (referenceValue * LP_VALUE_TOLERANCE_IN_BPS) /
            Constants.ONE_IN_BASIS_POINTS;

        if (actualValue > referenceValue + tolerance) {
            revert OracleValueDeviation();
        }
    }

    /**
     * @notice Returns the oracle address and minimum time tolerance for a given token.
     * @param token The token address.
     * @return oracleAddress The Chainlink oracle contract for this token.
     * @return minTimeTolerance The required minimum freshness in seconds for the price feed.
     */
    function getOracleInfo(
        address token
    )
        public view
        returns (
            address oracleAddress,
            uint256 minTimeTolerance
        )
    {
        OracleInfo memory info = oracles[token];
        return (info.oracleAddress, info.minTimeTolerance);
    }

    /**
     * @notice Returns the latest oracle price and its decimals for a given token.
     * @dev The price must be scaled to 18 decimals before use in calculations.
     * @param token The token to fetch the oracle price for.
     * @return price The current token price from the oracle.
     * @return decimals The number of decimals used by the price feed.
     */
    function currentOraclePriceWithDecimals(
        address token
    )
        internal view
        returns (
            uint256 price,
            uint8 decimals
        )
    {
        _enforceSequencerIsUp();

        OracleInfo memory info = oracles[token];

        price = SafeAggregatorInterface.safeUnsignedLatest(
            info.oracleAddress,
            info.minTimeTolerance
        );
        decimals = info.decimals;
    }

    /**
     * @notice Validates that an output amount falls within acceptable range of the fair price based on oracles.
     * @dev Uses current oracle prices and token decimals to compute an expected fair output amount,
     *      then applies a tolerance defined by `ORACLE_TOLERANCE_IN_BPS`.
     * @param inputAmount The input token amount used for the swap.
     * @param outputAmount The actual output token amount being validated.
     * @param inputToken The token address of the input.
     * @param outputToken The token address of the output.
     * @custom:reverts Reverts if the output amount exceeds the upper bound of the expected amount.
     */
    function validatePrice(
        uint256 inputAmount,
        uint256 outputAmount,
        address inputToken,
        address outputToken
    )
        internal view
    {
        (
            uint256 inputPrice,
            uint8 inputPriceDecimals
        ) = currentOraclePriceWithDecimals(inputToken);
        (
            uint256 outputPrice,
            uint8 outputPriceDecimals
        ) = currentOraclePriceWithDecimals(outputToken);

        UtilStruct memory s;

        s.decimalMultiplierX = 10 ** (18 - _getTokenDecimals(inputToken));
        s.decimalMultiplierY = 10 ** (18 - _getTokenDecimals(outputToken));
        s.qX = inputAmount * s.decimalMultiplierX;

        // Normalize prices to 18 decimals
        uint256 inputPriceNorm = inputPrice * (10 ** (18 - inputPriceDecimals));
        uint256 outputPriceNorm = outputPrice * (10 ** (18 - outputPriceDecimals));

        uint256 oracleFairOutputAmount = ((s.qX * inputPriceNorm) / outputPriceNorm) / s.decimalMultiplierY;
        uint256 upperBound = oracleFairOutputAmount * (Constants.ONE_IN_BASIS_POINTS + ORACLE_TOLERANCE_IN_BPS) / Constants.ONE_IN_BASIS_POINTS;

        if (outputAmount > upperBound) {
            revert OracleSwapDeviation();
        }
    }

    function _areAllOraclesSet() internal view returns (bool) {
        uint256 n = _nTokens();
        for (uint256 i = 0; i < n; ++i) {
            if (oracles[_tokenAt(i)].oracleAddress == address(0)) {
                return false;
            }
        }
        return true;
    }
}

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

File 49 of 65 : Conversions.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { uMAX_SD59x18, uMIN_SD59x18, uUNIT } from "./Constants.sol";
import { PRBMath_SD59x18_Convert_Overflow, PRBMath_SD59x18_Convert_Underflow } from "./Errors.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Converts a simple integer to SD59x18 by multiplying it by `UNIT`.
///
/// @dev Requirements:
/// - x = `MIN_SD59x18 / UNIT`
/// - x = `MAX_SD59x18 / UNIT`
///
/// @param x The basic integer to convert.
/// @return result The same number converted to SD59x18.
function convert(int256 x) pure returns (SD59x18 result) {
    if (x < uMIN_SD59x18 / uUNIT) {
        revert PRBMath_SD59x18_Convert_Underflow(x);
    }
    if (x > uMAX_SD59x18 / uUNIT) {
        revert PRBMath_SD59x18_Convert_Overflow(x);
    }
    unchecked {
        result = SD59x18.wrap(x * uUNIT);
    }
}

/// @notice Converts an SD59x18 number to a simple integer by dividing it by `UNIT`.
/// @dev The result is rounded toward zero.
/// @param x The SD59x18 number to convert.
/// @return result The same number as a simple integer.
function convert(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x) / uUNIT;
}

File 50 of 65 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD2x18 } from "./ValueType.sol";

/// @dev Euler's number as a UD2x18 number.
UD2x18 constant E = UD2x18.wrap(2_718281828459045235);

/// @dev The maximum value a UD2x18 number can have.
uint64 constant uMAX_UD2x18 = 18_446744073709551615;
UD2x18 constant MAX_UD2x18 = UD2x18.wrap(uMAX_UD2x18);

/// @dev PI as a UD2x18 number.
UD2x18 constant PI = UD2x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of UD2x18.
UD2x18 constant UNIT = UD2x18.wrap(1e18);
uint64 constant uUNIT = 1e18;

File 51 of 65 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Errors.sol" as CastingErrors;
import { MAX_UINT128, MAX_UINT40 } from "../Common.sol";
import { uMAX_SD1x18, uMIN_SD1x18 } from "../sd1x18/Constants.sol";
import { SD1x18 } from "../sd1x18/ValueType.sol";
import { uMAX_SD21x18, uMIN_SD21x18 } from "../sd21x18/Constants.sol";
import { SD21x18 } from "../sd21x18/ValueType.sol";
import { uMAX_UD2x18 } from "../ud2x18/Constants.sol";
import { UD2x18 } from "../ud2x18/ValueType.sol";
import { uMAX_UD21x18 } from "../ud21x18/Constants.sol";
import { UD21x18 } from "../ud21x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Casts an SD59x18 number into int256.
/// @dev This is basically a functional alias for {unwrap}.
function intoInt256(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x);
}

/// @notice Casts an SD59x18 number into SD1x18.
/// @dev Requirements:
/// - x = uMIN_SD1x18
/// - x = uMAX_SD1x18
function intoSD1x18(SD59x18 x) pure returns (SD1x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < uMIN_SD1x18) {
        revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Underflow(x);
    }
    if (xInt > uMAX_SD1x18) {
        revert CastingErrors.PRBMath_SD59x18_IntoSD1x18_Overflow(x);
    }
    result = SD1x18.wrap(int64(xInt));
}

/// @notice Casts an SD59x18 number into SD21x18.
/// @dev Requirements:
/// - x = uMIN_SD21x18
/// - x = uMAX_SD21x18
function intoSD21x18(SD59x18 x) pure returns (SD21x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < uMIN_SD21x18) {
        revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Underflow(x);
    }
    if (xInt > uMAX_SD21x18) {
        revert CastingErrors.PRBMath_SD59x18_IntoSD21x18_Overflow(x);
    }
    result = SD21x18.wrap(int128(xInt));
}

/// @notice Casts an SD59x18 number into UD2x18.
/// @dev Requirements:
/// - x = 0
/// - x = uMAX_UD2x18
function intoUD2x18(SD59x18 x) pure returns (UD2x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Underflow(x);
    }
    if (xInt > int256(uint256(uMAX_UD2x18))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD2x18_Overflow(x);
    }
    result = UD2x18.wrap(uint64(uint256(xInt)));
}

/// @notice Casts an SD59x18 number into UD21x18.
/// @dev Requirements:
/// - x = 0
/// - x = uMAX_UD21x18
function intoUD21x18(SD59x18 x) pure returns (UD21x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Underflow(x);
    }
    if (xInt > int256(uint256(uMAX_UD21x18))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD21x18_Overflow(x);
    }
    result = UD21x18.wrap(uint128(uint256(xInt)));
}

/// @notice Casts an SD59x18 number into UD60x18.
/// @dev Requirements:
/// - x = 0
function intoUD60x18(SD59x18 x) pure returns (UD60x18 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint256(xInt));
}

/// @notice Casts an SD59x18 number into uint256.
/// @dev Requirements:
/// - x = 0
function intoUint256(SD59x18 x) pure returns (uint256 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint256_Underflow(x);
    }
    result = uint256(xInt);
}

/// @notice Casts an SD59x18 number into uint128.
/// @dev Requirements:
/// - x = 0
/// - x = uMAX_UINT128
function intoUint128(SD59x18 x) pure returns (uint128 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint128_Underflow(x);
    }
    if (xInt > int256(uint256(MAX_UINT128))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint128_Overflow(x);
    }
    result = uint128(uint256(xInt));
}

/// @notice Casts an SD59x18 number into uint40.
/// @dev Requirements:
/// - x = 0
/// - x = MAX_UINT40
function intoUint40(SD59x18 x) pure returns (uint40 result) {
    int256 xInt = SD59x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint40_Underflow(x);
    }
    if (xInt > int256(uint256(MAX_UINT40))) {
        revert CastingErrors.PRBMath_SD59x18_IntoUint40_Overflow(x);
    }
    result = uint40(uint256(xInt));
}

/// @notice Alias for {wrap}.
function sd(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

/// @notice Alias for {wrap}.
function sd59x18(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

/// @notice Unwraps an SD59x18 number into int256.
function unwrap(SD59x18 x) pure returns (int256 result) {
    result = SD59x18.unwrap(x);
}

/// @notice Wraps an int256 number into SD59x18.
function wrap(int256 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(x);
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
     */
    function toDataWithIntendedValidatorHash(
        address validator,
        bytes32 messageHash
    ) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, hex"19_00")
            mstore(0x02, shl(96, validator))
            mstore(0x16, messageHash)
            digest := keccak256(0x00, 0x36)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }
}

File 53 of 65 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD1x18 } from "./ValueType.sol";

/// @notice Casts an SD1x18 number into SD59x18.
/// @dev There is no overflow check because SD1x18 ? SD59x18.
function intoSD59x18(SD1x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(SD1x18.unwrap(x)));
}

/// @notice Casts an SD1x18 number into UD60x18.
/// @dev Requirements:
/// - x = 0
function intoUD60x18(SD1x18 x) pure returns (UD60x18 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint128.
/// @dev Requirements:
/// - x = 0
function intoUint128(SD1x18 x) pure returns (uint128 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUint128_Underflow(x);
    }
    result = uint128(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint256.
/// @dev Requirements:
/// - x = 0
function intoUint256(SD1x18 x) pure returns (uint256 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUint256_Underflow(x);
    }
    result = uint256(uint64(xInt));
}

/// @notice Casts an SD1x18 number into uint40.
/// @dev Requirements:
/// - x = 0
/// - x = MAX_UINT40
function intoUint40(SD1x18 x) pure returns (uint40 result) {
    int64 xInt = SD1x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD1x18_ToUint40_Underflow(x);
    }
    if (xInt > int64(uint64(Common.MAX_UINT40))) {
        revert CastingErrors.PRBMath_SD1x18_ToUint40_Overflow(x);
    }
    result = uint40(uint64(xInt));
}

/// @notice Alias for {wrap}.
function sd1x18(int64 x) pure returns (SD1x18 result) {
    result = SD1x18.wrap(x);
}

/// @notice Unwraps an SD1x18 number into int64.
function unwrap(SD1x18 x) pure returns (int64 result) {
    result = SD1x18.unwrap(x);
}

/// @notice Wraps an int64 number into SD1x18.
function wrap(int64 x) pure returns (SD1x18 result) {
    result = SD1x18.wrap(x);
}

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            // Invert denominator mod 2²56. Now that denominator is an odd number, it has an inverse modulo 2²56 such
            // that denominator * inv = 1 mod 2²56. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 24.
            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 28
            inverse *= 2 - denominator * inverse; // inverse mod 2¹6
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 264
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²8
            inverse *= 2 - denominator * inverse; // inverse mod 2²56

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

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

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

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

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

            // We now have x_n such that `x_n = 2**(e-1) = sqrt(a) < 2**e = 2 * x_n`. This implies e_n = 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to e_n = 2**(e-2).
            // This is going to be our x_0 (and e_0)
            xn = (3 * xn) >> 1; // e_0 := | x_0 - sqrt(a) | = 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n4 + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n4 + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n4 - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              = 0
            // Which proves that for all n = 1, sqrt(a) = x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // e_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | e_n² / (2 * x_n) |
            //         = e_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // e_1 = e_0² / | (2 * x_0) |
            //     = (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     = 2**(2*e-4) / (3 * 2**(e-1))
            //     = 2**(e-3) / 3
            //     = 2**(e-3-log2(3))
            //     = 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) = sqrt(a) = x_n:
            // e_{n+1} = e_n² / | (2 * x_n) |
            //         = (2**(e-k))² / (2 * 2**(e-1))
            //         = 2**(2*e-2*k) / 2**e
            //         = 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // e_1 := | x_1 - sqrt(a) | = 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // e_2 := | x_2 - sqrt(a) | = 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // e_3 := | x_3 - sqrt(a) | = 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // e_4 := | x_4 - sqrt(a) | = 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // e_5 := | x_5 - sqrt(a) | = 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // e_6 := | x_6 - sqrt(a) | = 2**(e-144)  -- general case with k = 72

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

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

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

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

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

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

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

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

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

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

File 55 of 65 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD21x18 } from "./ValueType.sol";

/// @dev Euler's number as a UD21x18 number.
UD21x18 constant E = UD21x18.wrap(2_718281828459045235);

/// @dev The maximum value a UD21x18 number can have.
uint128 constant uMAX_UD21x18 = 340282366920938463463_374607431768211455;
UD21x18 constant MAX_UD21x18 = UD21x18.wrap(uMAX_UD21x18);

/// @dev PI as a UD21x18 number.
UD21x18 constant PI = UD21x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of UD21x18.
uint256 constant uUNIT = 1e18;
UD21x18 constant UNIT = UD21x18.wrap(1e18);

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

File 57 of 65 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD1x18 } from "./ValueType.sol";

/// @dev Euler's number as an SD1x18 number.
SD1x18 constant E = SD1x18.wrap(2_718281828459045235);

/// @dev The maximum value an SD1x18 number can have.
int64 constant uMAX_SD1x18 = 9_223372036854775807;
SD1x18 constant MAX_SD1x18 = SD1x18.wrap(uMAX_SD1x18);

/// @dev The minimum value an SD1x18 number can have.
int64 constant uMIN_SD1x18 = -9_223372036854775808;
SD1x18 constant MIN_SD1x18 = SD1x18.wrap(uMIN_SD1x18);

/// @dev PI as an SD1x18 number.
SD1x18 constant PI = SD1x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of SD1x18.
SD1x18 constant UNIT = SD1x18.wrap(1e18);
int64 constant uUNIT = 1e18;

File 58 of 65 : ValueType.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "./Casting.sol" as Casting;

/// @notice The signed 1.18-decimal fixed-point number representation, which can have up to 1 digit and up to 18
/// decimals. The values of this are bound by the minimum and the maximum values permitted by the underlying Solidity
/// type int64. This is useful when end users want to use int64 to save gas, e.g. with tight variable packing in contract
/// storage.
type SD1x18 is int64;

/*//////////////////////////////////////////////////////////////////////////
                                    CASTING
//////////////////////////////////////////////////////////////////////////*/

using {
    Casting.intoSD59x18,
    Casting.intoUD60x18,
    Casting.intoUint128,
    Casting.intoUint256,
    Casting.intoUint40,
    Casting.unwrap
} for SD1x18 global;

File 59 of 65 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD1x18 } from "./ValueType.sol";

/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in UD60x18.
error PRBMath_SD1x18_ToUD60x18_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint128.
error PRBMath_SD1x18_ToUint128_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint256.
error PRBMath_SD1x18_ToUint256_Underflow(SD1x18 x);

/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Overflow(SD1x18 x);

/// @notice Thrown when trying to cast an SD1x18 number that doesn't fit in uint40.
error PRBMath_SD1x18_ToUint40_Underflow(SD1x18 x);

File 60 of 65 : Math.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as Errors;
import {
    uEXP_MAX_INPUT,
    uEXP2_MAX_INPUT,
    uEXP_MIN_THRESHOLD,
    uEXP2_MIN_THRESHOLD,
    uHALF_UNIT,
    uLOG2_10,
    uLOG2_E,
    uMAX_SD59x18,
    uMAX_WHOLE_SD59x18,
    uMIN_SD59x18,
    uMIN_WHOLE_SD59x18,
    UNIT,
    uUNIT,
    uUNIT_SQUARED,
    ZERO
} from "./Constants.sol";
import { wrap } from "./Helpers.sol";
import { SD59x18 } from "./ValueType.sol";

/// @notice Calculates the absolute value of x.
///
/// @dev Requirements:
/// - x > MIN_SD59x18.
///
/// @param x The SD59x18 number for which to calculate the absolute value.
/// @return result The absolute value of x as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function abs(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt == uMIN_SD59x18) {
        revert Errors.PRBMath_SD59x18_Abs_MinSD59x18();
    }
    result = xInt < 0 ? wrap(-xInt) : x;
}

/// @notice Calculates the arithmetic average of x and y.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The arithmetic average as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function avg(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();

    unchecked {
        // This operation is equivalent to `x / 2 +  y / 2`, and it can never overflow.
        int256 sum = (xInt >> 1) + (yInt >> 1);

        if (sum < 0) {
            // If at least one of x and y is odd, add 1 to the result, because shifting negative numbers to the right
            // rounds toward negative infinity. The right part is equivalent to `sum + (x % 2 == 1 || y % 2 == 1)`.
            assembly ("memory-safe") {
                result := add(sum, and(or(xInt, yInt), 1))
            }
        } else {
            // Add 1 if both x and y are odd to account for the double 0.5 remainder truncated after shifting.
            result = wrap(sum + (xInt & yInt & 1));
        }
    }
}

/// @notice Yields the smallest whole number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because every whole value has (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x = MAX_WHOLE_SD59x18
///
/// @param x The SD59x18 number to ceil.
/// @return result The smallest whole number greater than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ceil(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt > uMAX_WHOLE_SD59x18) {
        revert Errors.PRBMath_SD59x18_Ceil_Overflow(x);
    }

    int256 remainder = xInt % uUNIT;
    if (remainder == 0) {
        result = x;
    } else {
        unchecked {
            // Solidity uses C fmod style, which returns a modulus with the same sign as x.
            int256 resultInt = xInt - remainder;
            if (xInt > 0) {
                resultInt += uUNIT;
            }
            result = wrap(resultInt);
        }
    }
}

/// @notice Divides two SD59x18 numbers, returning a new SD59x18 number.
///
/// @dev This is an extension of {Common.mulDiv} for signed numbers, which works by computing the signs and the absolute
/// values separately.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv}.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The denominator must not be zero.
/// - The result must fit in SD59x18.
///
/// @param x The numerator as an SD59x18 number.
/// @param y The denominator as an SD59x18 number.
/// @return result The quotient as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function div(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();
    if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
        revert Errors.PRBMath_SD59x18_Div_InputTooSmall();
    }

    // Get hold of the absolute values of x and y.
    uint256 xAbs;
    uint256 yAbs;
    unchecked {
        xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
        yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
    }

    // Compute the absolute value (x*UNIT÷y). The resulting value must fit in SD59x18.
    uint256 resultAbs = Common.mulDiv(xAbs, uint256(uUNIT), yAbs);
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert Errors.PRBMath_SD59x18_Div_Overflow(x, y);
    }

    // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
    // negative, 0 for positive or zero).
    bool sameSign = (xInt ^ yInt) > -1;

    // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
    unchecked {
        result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
    }
}

/// @notice Calculates the natural exponent of x using the following formula:
///
/// $$
/// e^x = 2^{x * log_2{e}}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}.
///
/// Requirements:
/// - Refer to the requirements in {exp2}.
/// - x < 133_084258667509499441.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();

    // Any input less than the threshold returns zero.
    // This check also prevents an overflow for very small numbers.
    if (xInt < uEXP_MIN_THRESHOLD) {
        return ZERO;
    }

    // This check prevents values greater than 192e18 from being passed to {exp2}.
    if (xInt > uEXP_MAX_INPUT) {
        revert Errors.PRBMath_SD59x18_Exp_InputTooBig(x);
    }

    unchecked {
        // Inline the fixed-point multiplication to save gas.
        int256 doubleUnitProduct = xInt * uLOG2_E;
        result = exp2(wrap(doubleUnitProduct / uUNIT));
    }
}

/// @notice Calculates the binary exponent of x using the binary fraction method using the following formula:
///
/// $$
/// 2^{-x} = \frac{1}{2^x}
/// $$
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Notes:
/// - If x < -59_794705707972522261, the result is zero.
///
/// Requirements:
/// - x < 192e18.
/// - The result must fit in SD59x18.
///
/// @param x The exponent as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function exp2(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < 0) {
        // The inverse of any number less than the threshold is truncated to zero.
        if (xInt < uEXP2_MIN_THRESHOLD) {
            return ZERO;
        }

        unchecked {
            // Inline the fixed-point inversion to save gas.
            result = wrap(uUNIT_SQUARED / exp2(wrap(-xInt)).unwrap());
        }
    } else {
        // Numbers greater than or equal to 192e18 don't fit in the 192.64-bit format.
        if (xInt > uEXP2_MAX_INPUT) {
            revert Errors.PRBMath_SD59x18_Exp2_InputTooBig(x);
        }

        unchecked {
            // Convert x to the 192.64-bit fixed-point format.
            uint256 x_192x64 = uint256((xInt << 64) / uUNIT);

            // It is safe to cast the result to int256 due to the checks above.
            result = wrap(int256(Common.exp2(x_192x64)));
        }
    }
}

/// @notice Yields the greatest whole number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional
/// counterparts. See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x = MIN_WHOLE_SD59x18
///
/// @param x The SD59x18 number to floor.
/// @return result The greatest whole number less than or equal to x, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function floor(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < uMIN_WHOLE_SD59x18) {
        revert Errors.PRBMath_SD59x18_Floor_Underflow(x);
    }

    int256 remainder = xInt % uUNIT;
    if (remainder == 0) {
        result = x;
    } else {
        unchecked {
            // Solidity uses C fmod style, which returns a modulus with the same sign as x.
            int256 resultInt = xInt - remainder;
            if (xInt < 0) {
                resultInt -= uUNIT;
            }
            result = wrap(resultInt);
        }
    }
}

/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right.
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The SD59x18 number to get the fractional part of.
/// @return result The fractional part of x as an SD59x18 number.
function frac(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(x.unwrap() % uUNIT);
}

/// @notice Calculates the geometric mean of x and y, i.e. $\sqrt{x * y}$.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x * y must fit in SD59x18.
/// - x * y must not be negative, since complex numbers are not supported.
///
/// @param x The first operand as an SD59x18 number.
/// @param y The second operand as an SD59x18 number.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function gm(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();
    if (xInt == 0 || yInt == 0) {
        return ZERO;
    }

    unchecked {
        // Equivalent to `xy / x != y`. Checking for overflow this way is faster than letting Solidity do it.
        int256 xyInt = xInt * yInt;
        if (xyInt / xInt != yInt) {
            revert Errors.PRBMath_SD59x18_Gm_Overflow(x, y);
        }

        // The product must not be negative, since complex numbers are not supported.
        if (xyInt < 0) {
            revert Errors.PRBMath_SD59x18_Gm_NegativeProduct(x, y);
        }

        // We don't need to multiply the result by `UNIT` here because the x*y product picked up a factor of `UNIT`
        // during multiplication. See the comments in {Common.sqrt}.
        uint256 resultUint = Common.sqrt(uint256(xyInt));
        result = wrap(int256(resultUint));
    }
}

/// @notice Calculates the inverse of x.
///
/// @dev Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x must not be zero.
///
/// @param x The SD59x18 number for which to calculate the inverse.
/// @return result The inverse as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function inv(SD59x18 x) pure returns (SD59x18 result) {
    result = wrap(uUNIT_SQUARED / x.unwrap());
}

/// @notice Calculates the natural logarithm of x using the following formula:
///
/// $$
/// ln{x} = log_2{x} / log_2{e}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
/// - The precision isn't sufficiently fine-grained to return exactly `UNIT` when the input is `E`.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the natural logarithm.
/// @return result The natural logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function ln(SD59x18 x) pure returns (SD59x18 result) {
    // Inline the fixed-point multiplication to save gas. This is overflow-safe because the maximum value that
    // {log2} can return is ~195_205294292027477728.
    result = wrap(log2(x).unwrap() * uUNIT / uLOG2_E);
}

/// @notice Calculates the common logarithm of x using the following formula:
///
/// $$
/// log_{10}{x} = log_2{x} / log_2{10}
/// $$
///
/// However, if x is an exact power of ten, a hard coded value is returned.
///
/// @dev Notes:
/// - Refer to the notes in {log2}.
///
/// Requirements:
/// - Refer to the requirements in {log2}.
///
/// @param x The SD59x18 number for which to calculate the common logarithm.
/// @return result The common logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log10(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < 0) {
        revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
    }

    // Note that the `mul` in this block is the standard multiplication operation, not {SD59x18.mul}.
    // prettier-ignore
    assembly ("memory-safe") {
        switch x
        case 1 { result := mul(uUNIT, sub(0, 18)) }
        case 10 { result := mul(uUNIT, sub(1, 18)) }
        case 100 { result := mul(uUNIT, sub(2, 18)) }
        case 1000 { result := mul(uUNIT, sub(3, 18)) }
        case 10000 { result := mul(uUNIT, sub(4, 18)) }
        case 100000 { result := mul(uUNIT, sub(5, 18)) }
        case 1000000 { result := mul(uUNIT, sub(6, 18)) }
        case 10000000 { result := mul(uUNIT, sub(7, 18)) }
        case 100000000 { result := mul(uUNIT, sub(8, 18)) }
        case 1000000000 { result := mul(uUNIT, sub(9, 18)) }
        case 10000000000 { result := mul(uUNIT, sub(10, 18)) }
        case 100000000000 { result := mul(uUNIT, sub(11, 18)) }
        case 1000000000000 { result := mul(uUNIT, sub(12, 18)) }
        case 10000000000000 { result := mul(uUNIT, sub(13, 18)) }
        case 100000000000000 { result := mul(uUNIT, sub(14, 18)) }
        case 1000000000000000 { result := mul(uUNIT, sub(15, 18)) }
        case 10000000000000000 { result := mul(uUNIT, sub(16, 18)) }
        case 100000000000000000 { result := mul(uUNIT, sub(17, 18)) }
        case 1000000000000000000 { result := 0 }
        case 10000000000000000000 { result := uUNIT }
        case 100000000000000000000 { result := mul(uUNIT, 2) }
        case 1000000000000000000000 { result := mul(uUNIT, 3) }
        case 10000000000000000000000 { result := mul(uUNIT, 4) }
        case 100000000000000000000000 { result := mul(uUNIT, 5) }
        case 1000000000000000000000000 { result := mul(uUNIT, 6) }
        case 10000000000000000000000000 { result := mul(uUNIT, 7) }
        case 100000000000000000000000000 { result := mul(uUNIT, 8) }
        case 1000000000000000000000000000 { result := mul(uUNIT, 9) }
        case 10000000000000000000000000000 { result := mul(uUNIT, 10) }
        case 100000000000000000000000000000 { result := mul(uUNIT, 11) }
        case 1000000000000000000000000000000 { result := mul(uUNIT, 12) }
        case 10000000000000000000000000000000 { result := mul(uUNIT, 13) }
        case 100000000000000000000000000000000 { result := mul(uUNIT, 14) }
        case 1000000000000000000000000000000000 { result := mul(uUNIT, 15) }
        case 10000000000000000000000000000000000 { result := mul(uUNIT, 16) }
        case 100000000000000000000000000000000000 { result := mul(uUNIT, 17) }
        case 1000000000000000000000000000000000000 { result := mul(uUNIT, 18) }
        case 10000000000000000000000000000000000000 { result := mul(uUNIT, 19) }
        case 100000000000000000000000000000000000000 { result := mul(uUNIT, 20) }
        case 1000000000000000000000000000000000000000 { result := mul(uUNIT, 21) }
        case 10000000000000000000000000000000000000000 { result := mul(uUNIT, 22) }
        case 100000000000000000000000000000000000000000 { result := mul(uUNIT, 23) }
        case 1000000000000000000000000000000000000000000 { result := mul(uUNIT, 24) }
        case 10000000000000000000000000000000000000000000 { result := mul(uUNIT, 25) }
        case 100000000000000000000000000000000000000000000 { result := mul(uUNIT, 26) }
        case 1000000000000000000000000000000000000000000000 { result := mul(uUNIT, 27) }
        case 10000000000000000000000000000000000000000000000 { result := mul(uUNIT, 28) }
        case 100000000000000000000000000000000000000000000000 { result := mul(uUNIT, 29) }
        case 1000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 30) }
        case 10000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 31) }
        case 100000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 32) }
        case 1000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 33) }
        case 10000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 34) }
        case 100000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 35) }
        case 1000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 36) }
        case 10000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 37) }
        case 100000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 38) }
        case 1000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 39) }
        case 10000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 40) }
        case 100000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 41) }
        case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 42) }
        case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 43) }
        case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 44) }
        case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 45) }
        case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 46) }
        case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 47) }
        case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 48) }
        case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 49) }
        case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 50) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 51) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 52) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 53) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 54) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 55) }
        case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 56) }
        case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 57) }
        case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(uUNIT, 58) }
        default { result := uMAX_SD59x18 }
    }

    if (result.unwrap() == uMAX_SD59x18) {
        unchecked {
            // Inline the fixed-point division to save gas.
            result = wrap(log2(x).unwrap() * uUNIT / uLOG2_10);
        }
    }
}

/// @notice Calculates the binary logarithm of x using the iterative approximation algorithm:
///
/// $$
/// log_2{x} = n + log_2{y}, \text{ where } y = x*2^{-n}, \ y \in [1, 2)
/// $$
///
/// For $0 \leq x \lt 1$, the input is inverted:
///
/// $$
/// log_2{x} = -log_2{\frac{1}{x}}
/// $$
///
/// @dev See https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation.
///
/// Notes:
/// - Due to the lossy precision of the iterative approximation, the results are not perfectly accurate to the last decimal.
///
/// Requirements:
/// - x > 0
///
/// @param x The SD59x18 number for which to calculate the binary logarithm.
/// @return result The binary logarithm as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function log2(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt <= 0) {
        revert Errors.PRBMath_SD59x18_Log_InputTooSmall(x);
    }

    unchecked {
        int256 sign;
        if (xInt >= uUNIT) {
            sign = 1;
        } else {
            sign = -1;
            // Inline the fixed-point inversion to save gas.
            xInt = uUNIT_SQUARED / xInt;
        }

        // Calculate the integer part of the logarithm.
        uint256 n = Common.msb(uint256(xInt / uUNIT));

        // This is the integer part of the logarithm as an SD59x18 number. The operation can't overflow
        // because n is at most 255, `UNIT` is 1e18, and the sign is either 1 or -1.
        int256 resultInt = int256(n) * uUNIT;

        // Calculate $y = x * 2^{-n}$.
        int256 y = xInt >> n;

        // If y is the unit number, the fractional part is zero.
        if (y == uUNIT) {
            return wrap(resultInt * sign);
        }

        // Calculate the fractional part via the iterative approximation.
        // The `delta >>= 1` part is equivalent to `delta /= 2`, but shifting bits is more gas efficient.
        int256 DOUBLE_UNIT = 2e18;
        for (int256 delta = uHALF_UNIT; delta > 0; delta >>= 1) {
            y = (y * y) / uUNIT;

            // Is y^2 >= 2e18 and so in the range [2e18, 4e18)?
            if (y >= DOUBLE_UNIT) {
                // Add the 2^{-m} factor to the logarithm.
                resultInt = resultInt + delta;

                // Halve y, which corresponds to z/2 in the Wikipedia article.
                y >>= 1;
            }
        }
        resultInt *= sign;
        result = wrap(resultInt);
    }
}

/// @notice Multiplies two SD59x18 numbers together, returning a new SD59x18 number.
///
/// @dev Notes:
/// - Refer to the notes in {Common.mulDiv18}.
///
/// Requirements:
/// - Refer to the requirements in {Common.mulDiv18}.
/// - None of the inputs can be `MIN_SD59x18`.
/// - The result must fit in SD59x18.
///
/// @param x The multiplicand as an SD59x18 number.
/// @param y The multiplier as an SD59x18 number.
/// @return result The product as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function mul(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();
    if (xInt == uMIN_SD59x18 || yInt == uMIN_SD59x18) {
        revert Errors.PRBMath_SD59x18_Mul_InputTooSmall();
    }

    // Get hold of the absolute values of x and y.
    uint256 xAbs;
    uint256 yAbs;
    unchecked {
        xAbs = xInt < 0 ? uint256(-xInt) : uint256(xInt);
        yAbs = yInt < 0 ? uint256(-yInt) : uint256(yInt);
    }

    // Compute the absolute value (x*y÷UNIT). The resulting value must fit in SD59x18.
    uint256 resultAbs = Common.mulDiv18(xAbs, yAbs);
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert Errors.PRBMath_SD59x18_Mul_Overflow(x, y);
    }

    // Check if x and y have the same sign using two's complement representation. The left-most bit represents the sign (1 for
    // negative, 0 for positive or zero).
    bool sameSign = (xInt ^ yInt) > -1;

    // If the inputs have the same sign, the result should be positive. Otherwise, it should be negative.
    unchecked {
        result = wrap(sameSign ? int256(resultAbs) : -int256(resultAbs));
    }
}

/// @notice Raises x to the power of y using the following formula:
///
/// $$
/// x^y = 2^{log_2{x} * y}
/// $$
///
/// @dev Notes:
/// - Refer to the notes in {exp2}, {log2}, and {mul}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {exp2}, {log2}, and {mul}.
///
/// @param x The base as an SD59x18 number.
/// @param y Exponent to raise x to, as an SD59x18 number
/// @return result x raised to power y, as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function pow(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    int256 yInt = y.unwrap();

    // If both x and y are zero, the result is `UNIT`. If just x is zero, the result is always zero.
    if (xInt == 0) {
        return yInt == 0 ? UNIT : ZERO;
    }
    // If x is `UNIT`, the result is always `UNIT`.
    else if (xInt == uUNIT) {
        return UNIT;
    }

    // If y is zero, the result is always `UNIT`.
    if (yInt == 0) {
        return UNIT;
    }
    // If y is `UNIT`, the result is always x.
    else if (yInt == uUNIT) {
        return x;
    }

    // Calculate the result using the formula.
    result = exp2(mul(log2(x), y));
}

/// @notice Raises x (an SD59x18 number) to the power y (an unsigned basic integer) using the well-known
/// algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring.
///
/// Notes:
/// - Refer to the notes in {Common.mulDiv18}.
/// - Returns `UNIT` for 0^0.
///
/// Requirements:
/// - Refer to the requirements in {abs} and {Common.mulDiv18}.
/// - The result must fit in SD59x18.
///
/// @param x The base as an SD59x18 number.
/// @param y The exponent as a uint256.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function powu(SD59x18 x, uint256 y) pure returns (SD59x18 result) {
    uint256 xAbs = uint256(abs(x).unwrap());

    // Calculate the first iteration of the loop in advance.
    uint256 resultAbs = y & 1 > 0 ? xAbs : uint256(uUNIT);

    // Equivalent to `for(y /= 2; y > 0; y /= 2)`.
    uint256 yAux = y;
    for (yAux >>= 1; yAux > 0; yAux >>= 1) {
        xAbs = Common.mulDiv18(xAbs, xAbs);

        // Equivalent to `y % 2 == 1`.
        if (yAux & 1 > 0) {
            resultAbs = Common.mulDiv18(resultAbs, xAbs);
        }
    }

    // The result must fit in SD59x18.
    if (resultAbs > uint256(uMAX_SD59x18)) {
        revert Errors.PRBMath_SD59x18_Powu_Overflow(x, y);
    }

    unchecked {
        // Is the base negative and the exponent odd? If yes, the result should be negative.
        int256 resultInt = int256(resultAbs);
        bool isNegative = x.unwrap() < 0 && y & 1 == 1;
        if (isNegative) {
            resultInt = -resultInt;
        }
        result = wrap(resultInt);
    }
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - Only the positive root is returned.
/// - The result is rounded toward zero.
///
/// Requirements:
/// - x = 0, since complex numbers are not supported.
/// - x = MAX_SD59x18 / UNIT
///
/// @param x The SD59x18 number for which to calculate the square root.
/// @return result The result as an SD59x18 number.
/// @custom:smtchecker abstract-function-nondet
function sqrt(SD59x18 x) pure returns (SD59x18 result) {
    int256 xInt = x.unwrap();
    if (xInt < 0) {
        revert Errors.PRBMath_SD59x18_Sqrt_NegativeInput(x);
    }
    if (xInt > uMAX_SD59x18 / uUNIT) {
        revert Errors.PRBMath_SD59x18_Sqrt_Overflow(x);
    }

    unchecked {
        // Multiply x by `UNIT` to account for the factor of `UNIT` picked up when multiplying two SD59x18 numbers.
        // In this case, the two numbers are both the square root.
        uint256 resultUint = Common.sqrt(uint256(xInt * uUNIT));
        result = wrap(int256(resultUint));
    }
}

File 61 of 65 : Casting.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import "../Common.sol" as Common;
import "./Errors.sol" as CastingErrors;
import { SD59x18 } from "../sd59x18/ValueType.sol";
import { UD60x18 } from "../ud60x18/ValueType.sol";
import { SD21x18 } from "./ValueType.sol";

/// @notice Casts an SD21x18 number into SD59x18.
/// @dev There is no overflow check because SD21x18 ? SD59x18.
function intoSD59x18(SD21x18 x) pure returns (SD59x18 result) {
    result = SD59x18.wrap(int256(SD21x18.unwrap(x)));
}

/// @notice Casts an SD21x18 number into UD60x18.
/// @dev Requirements:
/// - x = 0
function intoUD60x18(SD21x18 x) pure returns (UD60x18 result) {
    int128 xInt = SD21x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD21x18_ToUD60x18_Underflow(x);
    }
    result = UD60x18.wrap(uint128(xInt));
}

/// @notice Casts an SD21x18 number into uint128.
/// @dev Requirements:
/// - x = 0
function intoUint128(SD21x18 x) pure returns (uint128 result) {
    int128 xInt = SD21x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD21x18_ToUint128_Underflow(x);
    }
    result = uint128(xInt);
}

/// @notice Casts an SD21x18 number into uint256.
/// @dev Requirements:
/// - x = 0
function intoUint256(SD21x18 x) pure returns (uint256 result) {
    int128 xInt = SD21x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD21x18_ToUint256_Underflow(x);
    }
    result = uint256(uint128(xInt));
}

/// @notice Casts an SD21x18 number into uint40.
/// @dev Requirements:
/// - x = 0
/// - x = MAX_UINT40
function intoUint40(SD21x18 x) pure returns (uint40 result) {
    int128 xInt = SD21x18.unwrap(x);
    if (xInt < 0) {
        revert CastingErrors.PRBMath_SD21x18_ToUint40_Underflow(x);
    }
    if (xInt > int128(uint128(Common.MAX_UINT40))) {
        revert CastingErrors.PRBMath_SD21x18_ToUint40_Overflow(x);
    }
    result = uint40(uint128(xInt));
}

/// @notice Alias for {wrap}.
function sd21x18(int128 x) pure returns (SD21x18 result) {
    result = SD21x18.wrap(x);
}

/// @notice Unwraps an SD21x18 number into int128.
function unwrap(SD21x18 x) pure returns (int128 result) {
    result = SD21x18.unwrap(x);
}

/// @notice Wraps an int128 number into SD21x18.
function wrap(int128 x) pure returns (SD21x18 result) {
    result = SD21x18.wrap(x);
}

File 62 of 65 : Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { SD59x18 } from "./ValueType.sol";

// NOTICE: the "u" prefix stands for "unwrapped".

/// @dev Euler's number as an SD59x18 number.
SD59x18 constant E = SD59x18.wrap(2_718281828459045235);

/// @dev The maximum input permitted in {exp}.
int256 constant uEXP_MAX_INPUT = 133_084258667509499440;
SD59x18 constant EXP_MAX_INPUT = SD59x18.wrap(uEXP_MAX_INPUT);

/// @dev Any value less than this returns 0 in {exp}.
int256 constant uEXP_MIN_THRESHOLD = -41_446531673892822322;
SD59x18 constant EXP_MIN_THRESHOLD = SD59x18.wrap(uEXP_MIN_THRESHOLD);

/// @dev The maximum input permitted in {exp2}.
int256 constant uEXP2_MAX_INPUT = 192e18 - 1;
SD59x18 constant EXP2_MAX_INPUT = SD59x18.wrap(uEXP2_MAX_INPUT);

/// @dev Any value less than this returns 0 in {exp2}.
int256 constant uEXP2_MIN_THRESHOLD = -59_794705707972522261;
SD59x18 constant EXP2_MIN_THRESHOLD = SD59x18.wrap(uEXP2_MIN_THRESHOLD);

/// @dev Half the UNIT number.
int256 constant uHALF_UNIT = 0.5e18;
SD59x18 constant HALF_UNIT = SD59x18.wrap(uHALF_UNIT);

/// @dev $log_2(10)$ as an SD59x18 number.
int256 constant uLOG2_10 = 3_321928094887362347;
SD59x18 constant LOG2_10 = SD59x18.wrap(uLOG2_10);

/// @dev $log_2(e)$ as an SD59x18 number.
int256 constant uLOG2_E = 1_442695040888963407;
SD59x18 constant LOG2_E = SD59x18.wrap(uLOG2_E);

/// @dev The maximum value an SD59x18 number can have.
int256 constant uMAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967;
SD59x18 constant MAX_SD59x18 = SD59x18.wrap(uMAX_SD59x18);

/// @dev The maximum whole value an SD59x18 number can have.
int256 constant uMAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MAX_WHOLE_SD59x18 = SD59x18.wrap(uMAX_WHOLE_SD59x18);

/// @dev The minimum value an SD59x18 number can have.
int256 constant uMIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968;
SD59x18 constant MIN_SD59x18 = SD59x18.wrap(uMIN_SD59x18);

/// @dev The minimum whole value an SD59x18 number can have.
int256 constant uMIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000;
SD59x18 constant MIN_WHOLE_SD59x18 = SD59x18.wrap(uMIN_WHOLE_SD59x18);

/// @dev PI as an SD59x18 number.
SD59x18 constant PI = SD59x18.wrap(3_141592653589793238);

/// @dev The unit number, which gives the decimal precision of SD59x18.
int256 constant uUNIT = 1e18;
SD59x18 constant UNIT = SD59x18.wrap(1e18);

/// @dev The unit number squared.
int256 constant uUNIT_SQUARED = 1e36;
SD59x18 constant UNIT_SQUARED = SD59x18.wrap(uUNIT_SQUARED);

/// @dev Zero as an SD59x18 number.
SD59x18 constant ZERO = SD59x18.wrap(0);

File 63 of 65 : Errors.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

import { UD2x18 } from "./ValueType.sol";

/// @notice Thrown when trying to cast a UD2x18 number that doesn't fit in uint40.
error PRBMath_UD2x18_IntoUint40_Overflow(UD2x18 x);

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

Settings
{
  "evmVersion": "paris",
  "libraries": {},
  "metadata": {
    "useLiteralContent": true
  },
  "optimizer": {
    "enabled": true,
    "runs": 800
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  }
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"theSigner","type":"address"},{"internalType":"address","name":"theWrapper","type":"address"},{"internalType":"address[]","name":"tokens","type":"address[]"},{"internalType":"address[]","name":"_oracles","type":"address[]"},{"internalType":"uint256[]","name":"minTimeTolerances","type":"uint256[]"},{"internalType":"address","name":"initialOwner","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"DigestAlreadyUsed","type":"error"},{"inputs":[],"name":"ECDSAInvalidSignature","type":"error"},{"inputs":[{"internalType":"uint256","name":"length","type":"uint256"}],"name":"ECDSAInvalidSignatureLength","type":"error"},{"inputs":[{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"ECDSAInvalidSignatureS","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"allowance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientAllowance","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"}],"name":"ERC20InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC20InvalidApprover","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC20InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC20InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"spender","type":"address"}],"name":"ERC20InvalidSpender","type":"error"},{"inputs":[],"name":"EthTransferFailed","type":"error"},{"inputs":[],"name":"ExistingVestingDeposit","type":"error"},{"inputs":[],"name":"ExpiredMessage","type":"error"},{"inputs":[],"name":"GracePeriodNotOver","type":"error"},{"inputs":[],"name":"InsufficientInput","type":"error"},{"inputs":[],"name":"InvalidFeeSplitTooMuch","type":"error"},{"inputs":[],"name":"InvalidFeeSplitTooSoon","type":"error"},{"inputs":[],"name":"InvalidLPTokenValue","type":"error"},{"inputs":[],"name":"InvalidLockTime","type":"error"},{"inputs":[],"name":"InvalidOracle","type":"error"},{"inputs":[],"name":"InvalidSequencerFeed","type":"error"},{"inputs":[],"name":"InvariantCheckFailed","type":"error"},{"inputs":[],"name":"MarketTradeHalted","type":"error"},{"inputs":[],"name":"MismatchedArrayLengths","type":"error"},{"inputs":[],"name":"OracleNotSet","type":"error"},{"inputs":[],"name":"OracleStalePrice","type":"error"},{"inputs":[],"name":"OracleSwapDeviation","type":"error"},{"inputs":[],"name":"OracleValueDeviation","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"}],"name":"PRBMath_MulDiv18_Overflow","type":"error"},{"inputs":[{"internalType":"uint256","name":"x","type":"uint256"},{"internalType":"uint256","name":"y","type":"uint256"},{"internalType":"uint256","name":"denominator","type":"uint256"}],"name":"PRBMath_MulDiv_Overflow","type":"error"},{"inputs":[],"name":"PRBMath_SD59x18_Div_InputTooSmall","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"},{"internalType":"SD59x18","name":"y","type":"int256"}],"name":"PRBMath_SD59x18_Div_Overflow","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"}],"name":"PRBMath_SD59x18_Exp2_InputTooBig","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"}],"name":"PRBMath_SD59x18_Log_InputTooSmall","type":"error"},{"inputs":[],"name":"PRBMath_SD59x18_Mul_InputTooSmall","type":"error"},{"inputs":[{"internalType":"SD59x18","name":"x","type":"int256"},{"internalType":"SD59x18","name":"y","type":"int256"}],"name":"PRBMath_SD59x18_Mul_Overflow","type":"error"},{"inputs":[],"name":"PoolStateDeviation","type":"error"},{"inputs":[],"name":"ReentrancyGuardReentrantCall","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":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"SequencerDown","type":"error"},{"inputs":[],"name":"SignatureValidation","type":"error"},{"inputs":[],"name":"TokenDecimalsNotSupported","type":"error"},{"inputs":[],"name":"TokenNotInPool","type":"error"},{"inputs":[],"name":"UnauthorizedCaller","type":"error"},{"inputs":[],"name":"UnlockDepositFailed","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"withdrawer","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokens","type":"uint256"},{"indexed":true,"internalType":"address","name":"assetAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"assetAmount","type":"uint256"}],"name":"AssetWithdrawn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"depositor","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokens","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"lockTime","type":"uint256"}],"name":"Deposited","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"entitledFeesInDollars","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"averagePoolBalanceInDollars","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"tokensTransferred","type":"uint256"}],"name":"FeesTaken","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"by","type":"address"}],"name":"MarketHalted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"by","type":"address"}],"name":"MarketResumed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"oracleAddress","type":"address"},{"indexed":false,"internalType":"uint256","name":"minTimeTolerance","type":"uint256"}],"name":"OracleAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token","type":"address"}],"name":"OracleRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"sequencerUptimeFeed","type":"address"}],"name":"SequencerUptimeFeedAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"inAsset","type":"address"},{"indexed":true,"internalType":"address","name":"outAsset","type":"address"},{"indexed":true,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"inAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"outAmount","type":"uint256"},{"indexed":false,"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"Swapped","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"newAddress","type":"address"}],"name":"TriageAddressChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"withdrawer","type":"address"},{"indexed":false,"internalType":"uint256","name":"poolTokens","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fractionOfPool","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DESIGNATED_SIGNER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WRAPPER_CONTRACT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"oracleAddress","type":"address"},{"internalType":"uint256","name":"minTimeTolerance","type":"uint256"}],"name":"addOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"allTokensBalance","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"allTokensStateBalance","outputs":[{"internalType":"uint256[]","name":"","type":"uint256[]"},{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burnToWithdraw","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"}],"name":"canUnlockDeposit","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"},{"internalType":"uint256[]","name":"depositAmounts","type":"uint256[]"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"deposit","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"depositor","type":"address"},{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"depositSingleAsset","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getLastBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getOracleInfo","outputs":[{"internalType":"address","name":"oracleAddress","type":"address"},{"internalType":"uint256","name":"minTimeTolerance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"isToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isTradeHalted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lastBalances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastFeeWithdrawal","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nTokens","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"packedInput","type":"uint256"},{"internalType":"uint256","name":"packedOutput","type":"uint256"},{"internalType":"uint256","name":"packedGoodUntil","type":"uint256"},{"internalType":"bytes32","name":"auxData","type":"bytes32"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"vs","type":"bytes32"}],"name":"packedSwap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"packedInput","type":"uint256"},{"internalType":"uint256","name":"packedConfig","type":"uint256"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"packedTransmitAndDepositSingleAsset","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"packedInput","type":"uint256"},{"internalType":"uint256","name":"packedOutput","type":"uint256"},{"internalType":"uint256","name":"packedGoodUntil","type":"uint256"},{"internalType":"bytes32","name":"auxData","type":"bytes32"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"vs","type":"bytes32"}],"name":"packedTransmitAndSwap","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"removeOracle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"resumeTrade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"outputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"sellEthForToken","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"sellTokenForEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sequencerUptimeFeed","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"feedAddress","type":"address"}],"name":"setSequencerUptimeFeed","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newTriage","type":"address"}],"name":"setTriageRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stopTrade","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"address","name":"outputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"swap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"entitledFeesInDollars","type":"uint256"},{"internalType":"uint256","name":"averagePoolBalanceInDollars","type":"uint256"}],"name":"takeFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"i","type":"uint256"}],"name":"tokenAt","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"depositAmounts","type":"uint256[]"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"transmitAndDeposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"lockTime","type":"uint256"},{"internalType":"uint256","name":"poolTokens","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"transmitAndDepositSingleAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"transmitAndSellTokenForEth","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"inputToken","type":"address"},{"internalType":"address","name":"outputToken","type":"address"},{"internalType":"uint256","name":"inputAmount","type":"uint256"},{"internalType":"uint256","name":"outputAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"internalType":"address","name":"destinationAddress","type":"address"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"auxiliaryData","type":"bytes"}],"name":"transmitAndSwap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"triageRole","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unlockDeposit","outputs":[{"internalType":"uint256","name":"poolTokens","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"vestingDeposits","outputs":[{"internalType":"uint256","name":"lockedUntil","type":"uint256"},{"internalType":"uint256","name":"poolTokenAmount","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"tokenHolder","type":"address"},{"internalType":"uint256","name":"poolTokenAmountToBurn","type":"uint256"},{"internalType":"address","name":"assetAddress","type":"address"},{"internalType":"uint256","name":"assetAmount","type":"uint256"},{"internalType":"uint256","name":"goodUntil","type":"uint256"},{"components":[{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"internalType":"struct Signature","name":"theSignature","type":"tuple"},{"internalType":"bytes","name":"extraData","type":"bytes"}],"name":"withdrawSingleAsset","outputs":[],"stateMutability":"nonpayable","type":"function"},{"stateMutability":"payable","type":"receive"}]

60e060405234801561001057600080fd5b5060405161664438038061664483398101604081905261002f91610661565b838383888884868061006260408051808201909152600e81526d213630b232902628102a37b5b2b760911b602082015290565b6040805180820190915260078152660426c6164654c560cc1b6020820152600361008c838261080b565b506004610099828261080b565b50506001600555506001600160a01b0381166100cf57604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6100d8816103ea565b506001600160a01b03841660a05281516000905b808210156101e5576000848381518110610108576101086108c9565b60209081029190910101519050610120600b8261043c565b506000816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610161573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061018591906108df565b905060128160ff1611156101ac57604051637c10f18b60e11b815260040160405180910390fd5b6001600160a01b0382166000908152600a60205260409020805460ff191660ff8316179055836101db81610909565b94505050506100ec565b61023060405180604001604052806005815260200164426c61646560d81b815250604051806040016040528060058152602001640322e302e360dc1b8152503061045a60201b60201c565b608052505050506001600160a01b031660c052508151156103dc578151835114158061025e57508051835114155b1561027c57604051632b477e7160e11b815260040160405180910390fd5b60005b83518110156103da5760405180606001604052808483815181106102a5576102a56108c9565b60200260200101516001600160a01b031681526020018383815181106102cd576102cd6108c9565b602002602001015181526020018483815181106102ec576102ec6108c9565b60200260200101516001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610331573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061035591906108df565b60ff16815250600f6000868481518110610371576103716108c9565b6020908102919091018101516001600160a01b039081168352828201939093526040918201600020845181546001600160a01b03191694169390931783558301516001808401919091559201516002909101805460ff191660ff9092169190911790550161027f565b505b50505050505050505061095f565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6000610451836001600160a01b038416610519565b90505b92915050565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8460405160200161048e9190610930565b60405160208183030381529060405280519060200120846040516020016104b59190610930565b60408051601f1981840301815282825280516020918201209083019490945281019190915260608101919091524660808201526001600160a01b03831660a082015260c0016040516020818303038152906040528051906020012090509392505050565b600081815260018301602052604081205461056057508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610454565b506000610454565b80516001600160a01b038116811461057f57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b03811182821017156105c2576105c2610584565b604052919050565b60006001600160401b038211156105e3576105e3610584565b5060051b60200190565b600082601f8301126105fe57600080fd5b815161061161060c826105ca565b61059a565b8082825260208201915060208360051b86010192508583111561063357600080fd5b602085015b838110156106575761064981610568565b835260209283019201610638565b5095945050505050565b60008060008060008060c0878903121561067a57600080fd5b61068387610568565b955061069160208801610568565b60408801519095506001600160401b038111156106ad57600080fd5b6106b989828a016105ed565b606089015190955090506001600160401b038111156106d757600080fd5b6106e389828a016105ed565b608089015190945090506001600160401b0381111561070157600080fd5b8701601f8101891361071257600080fd5b805161072061060c826105ca565b8082825260208201915060208360051b85010192508b83111561074257600080fd5b6020840193505b82841015610764578351825260209384019390910190610749565b94506107769250505060a08801610568565b90509295509295509295565b600181811c9082168061079657607f821691505b6020821081036107b657634e487b7160e01b600052602260045260246000fd5b50919050565b601f82111561080657806000526020600020601f840160051c810160208510156107e35750805b601f840160051c820191505b8181101561080357600081556001016107ef565b50505b505050565b81516001600160401b0381111561082457610824610584565b610838816108328454610782565b846107bc565b6020601f82116001811461086c57600083156108545750848201515b600019600385901b1c1916600184901b178455610803565b600084815260208120601f198516915b8281101561089c578785015182556020948501946001909201910161087c565b50848210156108ba5786840151600019600387901b60f8161c191681555b50505050600190811b01905550565b634e487b7160e01b600052603260045260246000fd5b6000602082840312156108f157600080fd5b815160ff8116811461090257600080fd5b9392505050565b60006001820161092957634e487b7160e01b600052601160045260246000fd5b5060010190565b6000825160005b818110156109515760208186018101518583015201610937565b506000920191825250919050565b60805160a05160c051615c5b6109e9600039600081816105d401528181610f120152818161140301528181611ded01528181611e1701528181612062015281816120cb015281816122040152818161225001526125f601526000818161070f0152612b7c015260008181611f3d0152818161263201528181612f0001526131c70152615c5b6000f3fe60806040526004361061032d5760003560e01c806370a08231116101a5578063b8f44963116100ec578063d9bd8ba411610095578063eb1c64531161006f578063eb1c64531461098e578063ecc7633d146109ae578063f2fde38b146109db578063fdc85fc4146109fb57600080fd5b8063d9bd8ba414610908578063da5014c514610928578063dd62ed3e1461094857600080fd5b8063c4828729116100c6578063c4828729146108a8578063c72da66a146108c8578063ceaf4339146108e857600080fd5b8063b8f44963146107b9578063bfdb6b04146107d9578063c325a5491461085f57600080fd5b80638dda8f3f1161014e578063a726470511610128578063a726470514610766578063a7d46c2f14610786578063a9059cbb1461079957600080fd5b80638dda8f3f146106fd57806392a91a3a1461073157806395d89b411461075157600080fd5b80638414efe51161017f5780638414efe5146106b45780638baeefce146106ca5780638da5cb5b146106df57600080fd5b806370a0823114610654578063715018a61461068a578063780dd6641461069f57600080fd5b80632e7e1bd3116102745780633b26e4eb1161021d5780635aecdda5116101f75780635aecdda5146105c25780635b6f4dce1461060e578063608de8aa1461062157806365cd6db01461064157600080fd5b80633b26e4eb1461056f5780634372328a1461058f5780634cb6864c146105a257600080fd5b806334cb3d7f1161024e57806334cb3d7f14610504578063368dfc181461053a578063377a368c1461055a57600080fd5b80632e7e1bd3146104b3578063313ce567146104c8578063343add83146104e457600080fd5b80631b6a8759116102d657806326d9b5b3116102b057806326d9b5b31461046157806327a9b424146104805780632b651a6c1461049357600080fd5b80631b6a8759146104085780631dc6f5a51461041d57806323b872dd1461044157600080fd5b80630ce9a63d116103075780630ce9a63d146103b657806318160ddd146103c957806319f37361146103e857600080fd5b806306fdde0314610339578063078795ee14610364578063095ea7b31461038657600080fd5b3661033457005b600080fd5b34801561034557600080fd5b5061034e610a1b565b60405161035b9190615122565b60405180910390f35b34801561037057600080fd5b5061038461037f3660046151ac565b610aad565b005b34801561039257600080fd5b506103a66103a136600461523a565b610b6f565b604051901515815260200161035b565b6103846103c4366004615264565b610b89565b3480156103d557600080fd5b506002545b60405190815260200161035b565b3480156103f457600080fd5b506103a66104033660046152a7565b610bd2565b34801561041457600080fd5b506103da610bdf565b34801561042957600080fd5b50610432610bf0565b60405161035b939291906152c2565b34801561044d57600080fd5b506103a661045c366004615355565b610d31565b34801561046d57600080fd5b50600854600160a01b900460ff166103a6565b61038461048e366004615392565b610d57565b34801561049f57600080fd5b506103846104ae3660046153ea565b610de5565b3480156104bf57600080fd5b50610384610e69565b3480156104d457600080fd5b506040516012815260200161035b565b3480156104f057600080fd5b506103846104ff366004615492565b610eab565b34801561051057600080fd5b506103da61051f3660046152a7565b6001600160a01b031660009081526009602052604090205490565b34801561054657600080fd5b506103846105553660046154ea565b610fec565b34801561056657600080fd5b506103da611064565b34801561057b57600080fd5b5061038461058a3660046153ea565b6110ba565b61038461059d366004615548565b6110ff565b3480156105ae57600080fd5b506103846105bd366004615392565b6111e1565b3480156105ce57600080fd5b506105f67f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200161035b565b61038461061c3660046155dd565b611264565b34801561062d57600080fd5b5061038461063c36600461563e565b6112c9565b61038461064f3660046156c2565b611347565b34801561066057600080fd5b506103da61066f3660046152a7565b6001600160a01b031660009081526020819052604090205490565b34801561069657600080fd5b50610384611493565b3480156106ab57600080fd5b506104326114a7565b3480156106c057600080fd5b506103da60075481565b3480156106d657600080fd5b506103846115b8565b3480156106eb57600080fd5b506006546001600160a01b03166105f6565b34801561070957600080fd5b506105f67f000000000000000000000000000000000000000000000000000000000000000081565b34801561073d57600080fd5b506105f661074c3660046154ea565b611600565b34801561075d57600080fd5b5061034e61160d565b34801561077257600080fd5b50600e546105f6906001600160a01b031681565b610384610794366004615264565b61161c565b3480156107a557600080fd5b506103a66107b436600461523a565b61165c565b3480156107c557600080fd5b506103846107d43660046152a7565b61166a565b3480156107e557600080fd5b506108406107f43660046152a7565b6001600160a01b039081166000908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff16939092019290925291565b604080516001600160a01b03909316835260208301919091520161035b565b34801561086b57600080fd5b5061089361087a3660046152a7565b600d602052600090815260409020805460019091015482565b6040805192835260208301919091520161035b565b3480156108b457600080fd5b506103846108c3366004615355565b6116cf565b3480156108d457600080fd5b506103846108e3366004615392565b611869565b3480156108f457600080fd5b506103846109033660046152a7565b6118ae565b34801561091457600080fd5b5061038461092336600461572c565b611900565b34801561093457600080fd5b506008546105f6906001600160a01b031681565b34801561095457600080fd5b506103da61096336600461574e565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b34801561099a57600080fd5b506103a66109a93660046152a7565b611a03565b3480156109ba57600080fd5b506103da6109c93660046152a7565b60096020526000908152604090205481565b3480156109e757600080fd5b506103846109f63660046152a7565b611a33565b348015610a0757600080fd5b50610384610a163660046152a7565b611a76565b606060038054610a2a90615781565b80601f0160208091040260200160405190810160405280929190818152602001828054610a5690615781565b8015610aa35780601f10610a7857610100808354040283529160200191610aa3565b820191906000526020600020905b815481529060010190602001808311610a8657829003601f168201915b5050505050905090565b610ab5611b17565b8342811015610ad757604051639a29b6fb60e01b815260040160405180910390fd5b866001811015610afa5760405163abf20e8f60e01b815260040160405180910390fd5b610b0f6001600160a01b038b1633308c611b42565b610b63338b8b8b8b8b610b27368d90038d018d61580b565b8b8b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc492505050565b50505050505050505050565b600033610b7d818585611c2e565b60019150505b92915050565b610b91611b17565b8363ffffffff1642811015610bb957604051639a29b6fb60e01b815260040160405180910390fd5b610bc98787878787876001611c40565b50505050505050565b6000610b83600b83611ce4565b6000610beb600b611d06565b905090565b606080600080610bfe610bdf565b905060008167ffffffffffffffff811115610c1b57610c1b6157b5565b604051908082528060200260200182016040528015610c44578160200160208202803683370190505b50905060008267ffffffffffffffff811115610c6257610c626157b5565b604051908082528060200260200182016040528015610c8b578160200160208202803683370190505b50905060005b83811015610d17576000610ca482611600565b9050610cc5816001600160a01b031660009081526009602052604090205490565b848381518110610cd757610cd761586f565b60200260200101818152505080838381518110610cf657610cf661586f565b6001600160a01b039092166020928302919091019091015250600101610c91565b508181610d2360025490565b955095509550505050909192565b600033610d3f858285611d10565b610d4a858585611d89565b60019150505b9392505050565b610d5f611b17565b8463ffffffff1642811015610d8757604051639a29b6fb60e01b815260040160405180910390fd5b610dda8989898989610d9e368b90038b018b61580b565b89898080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611de892505050565b505050505050505050565b610ded611b17565b8463ffffffff1642811015610e1557604051639a29b6fb60e01b815260040160405180910390fd5b610b638a8a8a8a8a8a610e2d368c90038c018c61580b565b8a8a8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611e3e92505050565b610e71611ec5565b6008805460ff60a01b1916905560405133907f542e2be6bf739156fc5d022ffac81c0c9b281c19e6491b63bb14281433138b1790600090a2565b610eb3611b17565b87336001600160a01b03821614610edd57604051635c427cd960e01b815260040160405180910390fd5b8442811015610eff57604051639a29b6fb60e01b815260040160405180910390fd5b60006001600160a01b038916610f3657507f0000000000000000000000000000000000000000000000000000000000000000975060015b6000610f488c8c8c8c8c8c8c8c611ef0565b9050610f5381611f9a565b610f5e8a8a8d611fe5565b610f68338c61200a565b8115610f7d57610f78338a612044565b610f88565b610f888a338b612103565b896001600160a01b03168c6001600160a01b03167f41e79959bad1d45680578f8a544fb5af76d72b04090e65a51b4d0eaab959a9ab8d8c604051610fd6929190918252602082015260400190565b60405180910390a3505050505050505050505050565b6000610ff760025490565b611006836402540be40061589b565b61101091906158c8565b905061101c338361200a565b61102581612132565b604080518381526020810183905233917f92ccf450a286a957af52509bc1c9939d1a6a481783e142e41e2499f0bb66ebc6910160405180910390a25050565b600061106f33611a03565b61108c5760405163bb1c8b6560e01b815260040160405180910390fd5b50336000818152600d602052604081206001810180549183905591909155906110b790309083611d89565b90565b6110c2611b17565b8463ffffffff16428110156110ea57604051639a29b6fb60e01b815260040160405180910390fd5b610e156001600160a01b038b1633308b611b42565b611107611b17565b834281101561112957604051639a29b6fb60e01b815260040160405180910390fd5b86600181101561114c5760405163abf20e8f60e01b815260040160405180910390fd5b6111d48b8b8b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152508d92508c91508b9050611198368c90038c018c61580b565b8a8a8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506121b092505050565b5050505050505050505050565b6111e9611b17565b8463ffffffff164281101561121157604051639a29b6fb60e01b815260040160405180910390fd5b610dda8989898989611228368b90038b018b61580b565b89898080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506121fb92505050565b61126c611b17565b834281101561128e57604051639a29b6fb60e01b815260040160405180910390fd5b8660018110156112b15760405163abf20e8f60e01b815260040160405180910390fd5b6111d48b8b8b8b8b8b610b27368d90038d018d61580b565b6112d1611b17565b6000875b808210156113365760008a8a848181106112f1576112f161586f565b90506020020135905060008111156113235761132333308361131287611600565b6001600160a01b0316929190611b42565b8261132d816158ea565b935050506112d5565b610b63338b8b8b8b8b8b8b8b6110ff565b61134f611b17565b608085901c6bffffffffffffffffffffffff602087901c1662ffffff600888901c164282101561139257604051639a29b6fb60e01b815260040160405180910390fd5b60018110156113b45760405163abf20e8f60e01b815260040160405180910390fd5b6040805160608082018352600080835260208084018290529284018190528351918201845260ff8c1682529181018a905291820188905260a08b901c908b906001600160a01b038216611429577f0000000000000000000000000000000000000000000000000000000000000000915061143e565b61143e6001600160a01b038316333086611b42565b50611485338284878a8a898f8f8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc492505050565b505050505050505050505050565b61149b6122c8565b6114a560006122f5565b565b6060806000806114b5610bdf565b905060008167ffffffffffffffff8111156114d2576114d26157b5565b6040519080825280602002602001820160405280156114fb578160200160208202803683370190505b50905060008267ffffffffffffffff811115611519576115196157b5565b604051908082528060200260200182016040528015611542578160200160208202803683370190505b50905060005b83811015610d1757600061155b82611600565b905061156681612347565b8483815181106115785761157861586f565b602002602001018181525050808383815181106115975761159761586f565b6001600160a01b039092166020928302919091019091015250600101611548565b6115c0611ec5565b6008805460ff60a01b1916600160a01b17905560405133907fcabe820ce05cacdbb20404e8bba2a9cbadaa7ff6e3a3294b6d5152526765942090600090a2565b6000610b83600b836123b2565b606060048054610a2a90615781565b611624611b17565b8363ffffffff164281101561164c57604051639a29b6fb60e01b815260040160405180910390fd5b610bc98787878787876000611c40565b600033610b7d818585611d89565b6116726122c8565b61167b816123be565b600e80546001600160a01b0319166001600160a01b0383169081179091556040519081527f33fa9d54e48b14392fffa8aa3cfec14c54552fa92d5f44048005ec6437ee97649060200160405180910390a150565b6116d76122c8565b600081116116f857604051639589a27d60e01b815260040160405180910390fd5b61170183612464565b61171e57604051630732619560e01b815260040160405180910390fd5b600061172a838361246f565b90506000811161174d57604051639589a27d60e01b815260040160405180910390fd5b6040518060600160405280846001600160a01b03168152602001838152602001846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117cf9190615903565b60ff9081169091526001600160a01b038681166000818152600f6020908152604091829020865181546001600160a01b031916908616178155868201516001820155958201516002909601805460ff19169690951695909517909355825191871682529281018590527fc9c48c8a3a63b9d481d1f1dc5a7ca531d0fe9ddfd25f00f6c91090175f7b0053910160405180910390a250505050565b611871611b17565b8463ffffffff164281101561189957604051639a29b6fb60e01b815260040160405180910390fd5b6112116001600160a01b038a1633308b611b42565b6118b66122c8565b600880546001600160a01b0319166001600160a01b0383169081179091556040517f7fb818801719b0f482b3e69a97fd8c5a1bddd186808ae2a83bdf1dac62c550ec90600090a250565b6119086122c8565b60008161191a846402540be40061589b565b61192491906158c8565b905061193660146402540be4006158c8565b8111156119565760405163051fb32160e01b815260040160405180910390fd5b62093a806007546119679190615920565b42101561198757604051637bd0a7dd60e01b815260040160405180910390fd5b4260075560006402540be40061199c60025490565b6119a6908461589b565b6119b091906158c8565b90506119bc3382612544565b60408051858152602081018590529081018290527f26092d07f0187f928cdea6737c0e6d7496aea7e4d4fb32daf1ccd48793ce0b8e9060600160405180910390a150505050565b6001600160a01b0381166000908152600d60205260408120600181015415801590610d5057505442101592915050565b611a3b6122c8565b6001600160a01b038116611a6a57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b611a73816122f5565b50565b611a7e6122c8565b6001600160a01b038181166000908152600f602052604090205416611ab657604051633e1e538160e21b815260040160405180910390fd5b6001600160a01b0381166000818152600f602052604080822080546001600160a01b031916815560018101839055600201805460ff19169055517f9c8e7d83025bef8a04c664b2f753f64b8814bdb7e27291d7e50935f18cc3c7129190a250565b600854600160a01b900460ff16156114a5576040516326f4363f60e21b815260040160405180910390fd5b6040516001600160a01b038481166024830152838116604483015260648201839052611bbe9186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505061257a565b50505050565b611bcd87610bd2565b611bea57604051630732619560e01b815260040160405180910390fd5b611bf26125eb565b6000611c04898989898989898961261b565b9050611c0f81611f9a565b611c1a88888761266a565b611c23886126a3565b610dda898787612727565b611c3b838383600161277b565b505050565b6040805160608101825260008082526020820181905291810182905260a089811c928a92918a901c918a916001600160ff1b03881690611c8560ff8a901c601b615933565b6040805160608101825260ff9092168252602082018c9052810192909252509050858015611cbb57506001600160a01b03841615155b15611cd557611cd56001600160a01b038516333088611b42565b611485848387868e8e87612850565b6001600160a01b03811660009081526001830160205260408120541515610d50565b6000610b83825490565b6001600160a01b03838116600090815260016020908152604080832093861683529290522054600019811015611bbe5781811015611d7a57604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401611a61565b611bbe8484848403600061277b565b6001600160a01b038316611db357604051634b637e8f60e11b815260006004820152602401611a61565b6001600160a01b038216611ddd5760405163ec442f0560e01b815260006004820152602401611a61565b611c3b8383836128c9565b611e127f0000000000000000000000000000000000000000000000000000000000000000876129f3565b610bc97f0000000000000000000000000000000000000000000000000000000000000000888888888888885b600080611e508a8a8a8a8a8a8a612a67565b91509150611e608a8a8784612ab1565b846001600160a01b0316896001600160a01b03168b6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c8858588604051611eb19392919061594c565b60405180910390a450505050505050505050565b6008546001600160a01b031633146114a557604051635c427cd960e01b815260040160405180910390fd5b6000806000611f3485858080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250612ae992505050565b91509150611f687f00000000000000000000000000000000000000000000000000000000000000008c8c8c8c8c8888612b39565b9250611f8283611f7d3689900389018961580b565b612b75565b611f8c8282612ba0565b505098975050505050505050565b60008181526010602052604090205460ff1615611fca576040516306542de760e11b815260040160405180910390fd5b6000908152601060205260409020805460ff19166001179055565b611fed612d37565b15611c3b576000611ffe8484612d99565b9050611bbe8183612e22565b6001600160a01b03821661203457604051634b637e8f60e11b815260006004820152602401611a61565b612040826000836128c9565b5050565b61204c612e62565b604051632e1a7d4d60e01b8152600481018290527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690632e1a7d4d90602401600060405180830381600087803b1580156120ae57600080fd5b505af11580156120c2573d6000803e3d6000fd5b505050506120ef7f00000000000000000000000000000000000000000000000000000000000000006126a3565b6120f982826129f3565b6120406001600555565b61210b612e62565b61211f6001600160a01b0384168383612e8c565b612128836126a3565b611c3b6001600555565b600080600061213f610bdf565b90505b80821015611bbe57600061215583611600565b90506402540be40061217c826001600160a01b031660009081526009602052604090205490565b612186908761589b565b61219091906158c8565b935061219d813386612103565b826121a7816158ea565b93505050612142565b6121b86125eb565b60006121c988888888888888612ebd565b90506121d481611f9a565b6121de8786612f4f565b6121e6612fee565b6121f1888787612727565b5050505050505050565b60008061222d897f00000000000000000000000000000000000000000000000000000000000000008a8a8a8a8a612a67565b9150915061223a896126a3565b6122448582612044565b846001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168a6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c88585886040516122b59392919061594c565b60405180910390a4505050505050505050565b6006546001600160a01b031633146114a55760405163118cdaa760e01b8152336004820152602401611a61565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa15801561238e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b839190615974565b6000610d508383613029565b6001600160a01b0381166123e557604051631c06ca6760e01b815260040160405180910390fd5b806001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa92505050801561243f575060408051601f3d908101601f1916820190925261243c918101906159a7565b60015b61245c57604051631c06ca6760e01b815260040160405180910390fd5b505050505050565b6000610b8382610bd2565b6000806000806000866001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa1580156124b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124d991906159a7565b9450945050935093508069ffffffffffffffffffff168469ffffffffffffffffffff1614158061251257504261250f8784615920565b11155b156125305760405163a9f7344560e01b815260040160405180910390fd5b61253983613053565b979650505050505050565b6001600160a01b03821661256e5760405163ec442f0560e01b815260006004820152602401611a61565b612040600083836128c9565b600080602060008451602086016000885af18061259d576040513d6000823e3d81fd5b50506000513d915081156125b55780600114156125c2565b6001600160a01b0384163b155b15611bbe57604051635274afe760e01b81526001600160a01b0385166004820152602401611a61565b34156114a5576114a57f0000000000000000000000000000000000000000000000000000000000000000346129f3565b600080600061262984612ae9565b9150915061265e7f00000000000000000000000000000000000000000000000000000000000000008c8c8c8c8c8c898961307d565b9250611f828386612b75565b6000612674612d37565b1561267d575060015b600061268a8585846130bb565b9050811561269c5761269c8382612e22565b5050505050565b6040516370a0823160e01b81523060048201526001600160a01b038216906370a0823190602401602060405180830381865afa1580156126e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061270b9190615974565b6001600160a01b03909116600090815260096020526040902055565b612732838383613105565b60408051828152602081018490526001600160a01b038516917f73a19dd210f1a7f902193214c0ee91dd35ee5b4d920cba8d519eca65a7b488ca910160405180910390a2505050565b6001600160a01b0384166127a55760405163e602df0560e01b815260006004820152602401611a61565b6001600160a01b0383166127cf57604051634a1406b160e11b815260006004820152602401611a61565b6001600160a01b0380851660009081526001602090815260408083209387168352929052208290558015611bbe57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161284291815260200190565b60405180910390a350505050565b604080516001600160a01b0319841660208201528151600c818303018152602c909101909152829081906001600160a01b038a1661289c5761289789898989878987611de8565b610b63565b6001600160a01b0389166128b9576128978a8989898789876121fb565b610b638a8a8a8a8a888a88611e3e565b6001600160a01b0383166128f45780600260008282546128e99190615920565b909155506129669050565b6001600160a01b038316600090815260208190526040902054818110156129475760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401611a61565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b038216612982576002805482900390556129a1565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516129e691815260200190565b60405180910390a3505050565b6000826001600160a01b03168260405160006040518083038185875af1925050503d8060008114612a40576040519150601f19603f3d011682016040523d82523d6000602084013e612a45565b606091505b5050905080611c3b57604051630db2c7f160e31b815260040160405180910390fd5b6000806000612a7b8a8a8a8a8a8a8a6131c0565b9050612a8681611f9a565b612a928a8a8a8a6131fd565b9093509150612aa48a848b858a61326d565b5097509795505050505050565b612ab9612e62565b612ac2846126a3565b612ad66001600160a01b0384168383612e8c565b612adf836126a3565b611bbe6001600555565b6000606082806020019051810190612b0191906159f9565b90925090506000612b10610bdf565b905080825114612b3357604051632b477e7160e11b815260040160405180910390fd5b50915091565b600080612b4b8989898989898961341f565b60405161190160f01b8152600281019b909b5260228b015250506042909720979650505050505050565b61204082827f00000000000000000000000000000000000000000000000000000000000000006135b3565b6000612bab60025490565b905080600003612bba57505050565b82600003612bdb57604051632ab0223d60e21b815260040160405180910390fd5b6000612be5610bdf565b90506000805b82811015612ca5576000612bfe82611600565b6001600160a01b0381166000908152600a602052604081205491925090612c299060ff166012615ab7565b612c3490600a615bb7565b9050600081612c4284612347565b612c4c919061589b565b90506000670de0b6b3a7640000898681518110612c6b57612c6b61586f565b602002602001015183612c7e919061589b565b612c8891906158c8565b9050612c948187615920565b955050505050806001019050612beb565b50600083612cbb670de0b6b3a76400008461589b565b612cc591906158c8565b9050858103612cd657505050505050565b6000612710612ce6600a8961589b565b612cf091906158c8565b90506000878311612d0a57612d058389615bc6565b612d14565b612d148884615bc6565b9050818111156121f1576040516340ba9c2b60e11b815260040160405180910390fd5b600080612d42613677565b905060005b81811015612d90576000600f81612d5d84613681565b6001600160a01b0390811682526020820192909252604001600020541603612d885760009250505090565b600101612d47565b50600191505090565b6000806000612da78561368c565b915091506000612dcf866001600160a01b03166000908152600a602052604090205460ff1690565b612dda906012615ab7565b612de590600a615bb7565b90506000612df3828761589b565b90506000612e0284600a615bb7565b612e0c868461589b565b612e1691906158c8565b98975050505050505050565b6000612e35612e3060025490565b6136f8565b90506000670de0b6b3a7640000612e4c838661589b565b612e5691906158c8565b9050611bbe8184613783565b600260055403612e8557604051633ee5aeb560e01b815260040160405180910390fd5b6002600555565b6040516001600160a01b03838116602483015260448201839052611c3b91859182169063a9059cbb90606401611b77565b600080612ec8610bdf565b905087518114612eeb57604051632b477e7160e11b815260040160405180910390fd5b600080612ef785612ae9565b91509150612f2b7f00000000000000000000000000000000000000000000000000000000000000008c8c8c8c8c88886137c9565b9350612f378487612b75565b612f418282612ba0565b505050979650505050505050565b6000612f59612d37565b15612f62575060015b6000612f6c610bdf565b90506000805b82811015612fdd576000868281518110612f8e57612f8e61586f565b60200260200101511115612fd557612fc8612fa882611600565b878381518110612fba57612fba61586f565b6020026020010151866130bb565b612fd29083615920565b91505b600101612f72565b50821561269c5761269c8482612e22565b600080612ffb600b611d06565b90505b808210156120405761301761301283611600565b6126a3565b81613021816158ea565b925050612ffe565b60008260000182815481106130405761304061586f565b9060005260206000200154905092915050565b60008082121561307957604051635467221960e11b815260048101839052602401611a61565b5090565b6000806130908a8a8a8a8a8a8a8a6137db565b60405161190160f01b8152600281019c909c5260228c01525050604290982098975050505050505050565b6000806130c78561395d565b9050838110156130ea5760405163f8b3bb6160e01b815260040160405180910390fd5b82156130fd576130fa8582612d99565b91505b509392505050565b60018210156131275760405163abf20e8f60e01b815260040160405180910390fd5b6001600160a01b0383166000908152600d602052604090206001015415613161576040516329e8d8e960e11b815260040160405180910390fd5b6000604051806040016040528084603c61317b919061589b565b6131859042615920565b815260209081018490526001600160a01b0386166000908152600d82526040902082518155908201516001909101559050611bbe3083612544565b60006131f17f00000000000000000000000000000000000000000000000000000000000000008989898989896139e1565b90506125398183612b75565b60008061320986610bd2565b61322657604051630732619560e01b815260040160405180910390fd5b61322f85610bd2565b61324c57604051630732619560e01b815260040160405180910390fd5b6132558661395d565b9150613262848385613a20565b905094509492505050565b6132986040518060800160405280600081526020016000815260200160008152602001600081525090565b6001600160a01b03868116600081815260096020818152604080842054875294891683529081528382205485820152918152600a82528290205460c085901c9267ffffffffffffffff608087901c81169361ffff603089901c8116949189901c169288901c9091169061330f9060ff166012615ab7565b61331a90600a615bb7565b6040808801919091526001600160a01b038a166000908152600a60205220546133479060ff166012615ab7565b61335290600a615bb7565b606087015260408601516000906133ac9061336d908d61589b565b60408901518951899161337f9161589b565b878b606001518e613390919061589b565b8a8d606001518e602001516133a5919061589b565b8a8a613ac1565b9050806133cc5760405163473ab96d60e11b815260040160405180910390fd5b6001600160a01b038c81166000908152600f6020526040902054161580159061340e57506001600160a01b038a81166000908152600f60205260409020541615155b15611485576114858b8a8e8d613c76565b600080826040516020016134339190615bd9565b60405160208183030381529060405280519060200120905060405160200161353c907f5769746864726177616c537472756374286164647265737320746f6b656e5f6881527f6f6c6465722c75696e7432353620706f6f6c5f746f6b656e5f616d6f756e745f60208201527f746f5f6275726e2c616464726573732061737365745f616464726573732c756960408201527f6e743235362061737365745f616d6f756e742c75696e7432353620676f6f645f60608201527f756e74696c2c75696e74323536206c705f746f6b656e5f70726963652c75696e60808201527f743235365b5d207072696365732900000000000000000000000000000000000060a082015260ae0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039b8c1683830152606083019a909a529790991660808a015260a0890195909552505060c086019190915260e085015261010080850191909152815180850390910181526101209093019052815191012090565b60006135cd84846000015185602001518660400151613e12565b9050816001600160a01b0316816001600160a01b031614611bbe57613643843260405160200161361992919091825260601b6bffffffffffffffffffffffff1916602082015260340190565b60405160208183030381529060405280519060200120846000015185602001518660400151613e12565b9050816001600160a01b0316816001600160a01b031614611bbe576040516314cdc32360e31b815260040160405180910390fd5b6000610beb610bdf565b6000610b8382611600565b600080613697613e40565b6001600160a01b038084166000908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff16928401929092526136e9919061246f565b92508060400151915050915091565b600080613703613677565b90506000805b8281101561374557600061371c82613681565b90506137308161372b83613f23565b612d99565b61373a9084615920565b925050600101613709565b508315613770578361375f670de0b6b3a76400008361589b565b61376991906158c8565b925061377c565b670de0b6b3a764000092505b5050919050565b600061271061379360148461589b565b61379d91906158c8565b90506137a98183615920565b831115611c3b576040516317427d6560e31b815260040160405180910390fd5b600080612b4b89898989898989613f41565b600080826040516020016137ef9190615bd9565b6040516020818303038152906040528051906020012090506040516020016138df907f53696e676c654465706f7369745374727563742861646472657373206465706f81527f7369746f722c6164647265737320746f6b656e2c75696e7432353620616d6f7560208201527f6e742c75696e74323536206c6f636b5f74696d652c75696e7432353620706f6f60408201527f6c5f746f6b656e732c75696e7432353620676f6f645f756e74696c2c75696e7460608201527f323536206c705f746f6b656e5f70726963652c75696e743235365b5d207072696080820152636365732960e01b60a082015260a40190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039c8d16838301529a909b166060820152608081019890985260a0880196909652505060c085019290925260e08401526101008301526101208083019190915283518083039091018152610140909101909252815191012090565b6001600160a01b0381166000818152600960205260408082205490516370a0823160e01b8152306004820152919290916370a0823190602401602060405180830381865afa1580156139b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139d79190615974565b610b839190615bc6565b6000806139f28888888888886140e1565b60405161190160f01b8152600281018b905260228101829052604290209091505b9998505050505050505050565b6000838303613a30575080610d50565b600084613a42856402540be40061589b565b613a4c91906158c8565b9050613a5c620f4240603261589b565b613a6b906402540be400615920565b8110613ab1576402540be40083613a86620f4240603261589b565b613a95906402540be400615920565b613a9f919061589b565b613aa991906158c8565b915050610d50565b6402540be400613a9f848361589b565b60008080806305f5e100613ad58c8e61589b565b613adf91906158c8565b90506000613af6613af08c8461589b565b87614220565b90508015613b285780613b1183670de0b6b3a764000061589b565b613b1b91906158c8565b613b259085615920565b93505b60006305f5e100613b398a8c61589b565b613b4391906158c8565b90506000613b5a613b548a8461589b565b89614220565b90508015613b8c5780613b7583670de0b6b3a764000061589b565b613b7f91906158c8565b613b899087615920565b95505b5050505060006305f5e1008d8c613ba39190615920565b613bad908e61589b565b613bb791906158c8565b90506000613bc8613af08c8461589b565b90508015613bfa5780613be383670de0b6b3a764000061589b565b613bed91906158c8565b613bf79084615920565b92505b60006305f5e100613c0b8c8b615bc6565b613c15908c61589b565b613c1f91906158c8565b90506000613c30613b548a8461589b565b90508015613c625780613c4b83670de0b6b3a764000061589b565b613c5591906158c8565b613c5f9086615920565b94505b50505091109b9a5050505050505050505050565b600080613c828461368c565b91509150600080613c928561368c565b91509150613cc16040518060800160405280600081526020016000815260200160008152602001600081525090565b6001600160a01b0387166000908152600a602052604090205460ff16613ce8906012615ab7565b613cf390600a615bb7565b6040820152613d1a866001600160a01b03166000908152600a602052604090205460ff1690565b613d25906012615ab7565b613d3090600a615bb7565b60608201526040810151613d44908a61589b565b81526000613d53856012615ab7565b613d5e90600a615bb7565b613d68908761589b565b90506000613d77846012615ab7565b613d8290600a615bb7565b613d8c908661589b565b90506000836060015182848660000151613da6919061589b565b613db091906158c8565b613dba91906158c8565b90506000612710613dcc60c882615920565b613dd6908461589b565b613de091906158c8565b9050808c1115613e0357604051630d6974bb60e31b815260040160405180910390fd5b50505050505050505050505050565b600080600080613e2488888888614299565b925092509250613e348282614368565b50909695505050505050565b600e546001600160a01b0316613e5257565b600080600e60009054906101000a90046001600160a01b03166001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015613ea8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ecc91906159a7565b5050925092505081600014613ef35760405162032b3d60e81b815260040160405180910390fd5b6000613eff8242615bc6565b9050610e108111611c3b5760405163d15f73b560e01b815260040160405180910390fd5b6001600160a01b038116600090815260096020526040812054610b83565b60008087604051602001613f559190615bd9565b604051602081830303815290604052805190602001209050600083604051602001613f809190615bd9565b604051602081830303815290604052805190602001209050604051602001614063907f4465706f7369745374727563742861646472657373206465706f7369746f722c81527f75696e743235365b5d206465706f7369745f616d6f756e74732c75696e74323560208201527f36206c6f636b5f74696d652c75696e7432353620706f6f6c5f746f6b656e732c60408201527f75696e7432353620676f6f645f756e74696c2c75696e74323536206c705f746f60608201527f6b656e5f70726963652c75696e743235365b5d207072696365732900000000006080820152609b0190565b60408051601f198184030181528282528051602091820120908301526001600160a01b038c1690820152606081018390526080810189905260a0810188905260c0810187905260e081018690526101008101829052610120016040516020818303038152906040528051906020012092505050979650505050505050565b60006040516020016141ae907f4f66666572537472756374286164647265737320696e7075745f746f6b656e2c81527f61646472657373206f75747075745f746f6b656e2c75696e7432353620696e7060208201527f75745f616d6f756e742c75696e74323536206f75747075745f616d6f756e742c60408201527f75696e7432353620676f6f645f756e74696c2c6164647265737320646573746960608201527f6e6174696f6e5f616464726573732900000000000000000000000000000000006080820152608f0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b03998a16838301529789166060830152608082019690965260a08101949094525060c083019190915290931660e080850191909152815180850390910181526101009093019052815191012090565b60008260000361423257506000610b83565b60006142486142436110b786614421565b61444e565b90506000614274670de0b6b3a764000061426e846142686110b789614421565b906145bc565b9061467a565b905060006142846110b783614727565b905061428f81613053565b9350505050610b83565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411156142d4575060009150600390508261435e565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015614328573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166143545750600092506001915082905061435e565b9250600091508190505b9450945094915050565b600082600381111561437c5761437c615c0f565b03614385575050565b600182600381111561439957614399615c0f565b036143b75760405163f645eedf60e01b815260040160405180910390fd5b60028260038111156143cb576143cb615c0f565b036143ec5760405163fce698f760e01b815260048101829052602401611a61565b600382600381111561440057614400615c0f565b03612040576040516335e2f38360e21b815260048101829052602401611a61565b60006001600160ff1b038211156130795760405163123baf0360e11b815260048101839052602401611a61565b6000818181136144745760405163059b101b60e01b815260048101849052602401611a61565b6000670de0b6b3a7640000821261448d575060016144b3565b50600019816ec097ce7bc90715b34b9f1000000000816144af576144af6158b2565b0591505b600061453f670de0b6b3a7640000840560016fffffffffffffffffffffffffffffffff821160071b91821c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810283821d670de0b6b3a763ffff19810161456757818402612539565b671bc16d674ec800006706f05b59d3b200005b60008113156145ad57670de0b6b3a76400008380020592508183126145a5579283019260019290921d915b60011d61457a565b50505091909102949350505050565b60008282600160ff1b8214806145d55750600160ff1b81145b156145f35760405163a6070c2560e01b815260040160405180910390fd5b600080600084126146045783614609565b836000035b915060008312614619578261461e565b826000035b9050600061462c83836147de565b90506001600160ff1b038111156146605760405163120b5b4360e01b81526004810189905260248101889052604401611a61565b60001985851813613a1381614676578260000390565b8290565b60008282600160ff1b8214806146935750600160ff1b81145b156146b1576040516309fe2b4560e41b815260040160405180910390fd5b600080600084126146c257836146c7565b836000035b9150600083126146d757826146dc565b826000035b905060006146f383670de0b6b3a764000084614894565b90506001600160ff1b038111156146605760405163d49c26b360e01b81526004810189905260248101889052604401611a61565b6000818181121561478d5768033dd1780914b971141981121561474d5750600092915050565b6147866147656110b76147608460000390565b614727565b6ec097ce7bc90715b34b9f100000000081614782576147826158b2565b0590565b91506147d8565b680a688906bd8affffff8113156147b957604051626c1a0560e31b815260048101849052602401611a61565b670de0b6b3a7640000604082901b056147d46110b782614968565b9250505b50919050565b60008080600019848609848602925082811083820303915050806000036148125750670de0b6b3a764000090049050610b83565b670de0b6b3a7640000811061484457604051635173648d60e01b81526004810186905260248101859052604401611a61565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b60008080600019858709858702925082811083820303915050806000036148ce578382816148c4576148c46158b2565b0492505050610d50565b8381106148ff57604051630c740aef60e31b8152600481018790526024810186905260448101859052606401611a61565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b7780000000000000000000000000000000000000000000000067ff00000000000000821615614a89576780000000000000008216156149b05768016a09e667f3bcc9090260401c5b6740000000000000008216156149cf576801306fe0a31b7152df0260401c5b6720000000000000008216156149ee576801172b83c7d517adce0260401c5b671000000000000000821615614a0d5768010b5586cf9890f62a0260401c5b670800000000000000821615614a2c576801059b0d31585743ae0260401c5b670400000000000000821615614a4b57680102c9a3e778060ee70260401c5b670200000000000000821615614a6a5768010163da9fb33356d80260401c5b670100000000000000821615614a8957680100b1afa5abcbed610260401c5b66ff000000000000821615614b88576680000000000000821615614ab65768010058c86da1c09ea20260401c5b6640000000000000821615614ad4576801002c605e2e8cec500260401c5b6620000000000000821615614af257680100162f3904051fa10260401c5b6610000000000000821615614b10576801000b175effdc76ba0260401c5b6608000000000000821615614b2e57680100058ba01fb9f96d0260401c5b6604000000000000821615614b4c5768010002c5cc37da94920260401c5b6602000000000000821615614b6a576801000162e525ee05470260401c5b6601000000000000821615614b885768010000b17255775c040260401c5b65ff0000000000821615614c7e5765800000000000821615614bb3576801000058b91b5bc9ae0260401c5b65400000000000821615614bd057680100002c5c89d5ec6d0260401c5b65200000000000821615614bed5768010000162e43f4f8310260401c5b65100000000000821615614c0a57680100000b1721bcfc9a0260401c5b65080000000000821615614c275768010000058b90cf1e6e0260401c5b65040000000000821615614c44576801000002c5c863b73f0260401c5b65020000000000821615614c6157680100000162e430e5a20260401c5b65010000000000821615614c7e576801000000b1721835510260401c5b64ff00000000821615614d6b57648000000000821615614ca757680100000058b90c0b490260401c5b644000000000821615614cc35768010000002c5c8601cc0260401c5b642000000000821615614cdf576801000000162e42fff00260401c5b641000000000821615614cfb5768010000000b17217fbb0260401c5b640800000000821615614d17576801000000058b90bfce0260401c5b640400000000821615614d3357680100000002c5c85fe30260401c5b640200000000821615614d4f5768010000000162e42ff10260401c5b640100000000821615614d6b57680100000000b17217f80260401c5b63ff000000821615614e4f576380000000821615614d925768010000000058b90bfc0260401c5b6340000000821615614dad576801000000002c5c85fe0260401c5b6320000000821615614dc857680100000000162e42ff0260401c5b6310000000821615614de3576801000000000b17217f0260401c5b6308000000821615614dfe57680100000000058b90c00260401c5b6304000000821615614e195768010000000002c5c8600260401c5b6302000000821615614e34576801000000000162e4300260401c5b6301000000821615614e4f5768010000000000b172180260401c5b62ff0000821615614f2a5762800000821615614e74576801000000000058b90c0260401c5b62400000821615614e8e57680100000000002c5c860260401c5b62200000821615614ea85768010000000000162e430260401c5b62100000821615614ec257680100000000000b17210260401c5b62080000821615614edc5768010000000000058b910260401c5b62040000821615614ef6576801000000000002c5c80260401c5b62020000821615614f1057680100000000000162e40260401c5b62010000821615614f2a576801000000000000b1720260401c5b61ff00821615614ffc57618000821615614f4d57680100000000000058b90260401c5b614000821615614f665768010000000000002c5d0260401c5b612000821615614f7f576801000000000000162e0260401c5b611000821615614f985768010000000000000b170260401c5b610800821615614fb1576801000000000000058c0260401c5b610400821615614fca57680100000000000002c60260401c5b610200821615614fe357680100000000000001630260401c5b610100821615614ffc57680100000000000000b10260401c5b60ff8216156150c557608082161561501d57680100000000000000590260401c5b6040821615615035576801000000000000002c0260401c5b602082161561504d57680100000000000000160260401c5b6010821615615065576801000000000000000b0260401c5b600882161561507d57680100000000000000060260401c5b600482161561509557680100000000000000030260401c5b60028216156150ad57680100000000000000010260401c5b60018216156150c557680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b6000815180845260005b81811015615102576020818501810151868301820152016150e6565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000610d5060208301846150dc565b80356001600160a01b038116811461514c57600080fd5b919050565b6000606082840312156147d857600080fd5b60008083601f84011261517557600080fd5b50813567ffffffffffffffff81111561518d57600080fd5b6020830191508360208285010111156151a557600080fd5b9250929050565b600080600080600080600080610120898b0312156151c957600080fd5b6151d289615135565b9750602089013596506040890135955060608901359450608089013593506151fd8a60a08b01615151565b925061010089013567ffffffffffffffff81111561521a57600080fd5b6152268b828c01615163565b999c989b5096995094979396929594505050565b6000806040838503121561524d57600080fd5b61525683615135565b946020939093013593505050565b60008060008060008060c0878903121561527d57600080fd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b6000602082840312156152b957600080fd5b610d5082615135565b6060808252845190820181905260009060208601906080840190835b818110156152fc5783518352602093840193909201916001016152de565b50508381036020808601919091528651808352918101925086019060005b818110156153415782516001600160a01b031684526020938401939092019160010161531a565b505050604092909201929092529392505050565b60008060006060848603121561536a57600080fd5b61537384615135565b925061538160208501615135565b929592945050506040919091013590565b600080600080600080600080610120898b0312156153af57600080fd5b6153b889615135565b97506020890135965060408901359550606089013594506153db60808a01615135565b93506151fd8a60a08b01615151565b60008060008060008060008060006101408a8c03121561540957600080fd5b6154128a615135565b985061542060208b01615135565b975060408a0135965060608a0135955060808a0135945061544360a08b01615135565b93506154528b60c08c01615151565b92506101208a013567ffffffffffffffff81111561546f57600080fd5b61547b8c828d01615163565b915080935050809150509295985092959850929598565b600080600080600080600080610120898b0312156154af57600080fd5b6154b889615135565b9750602089013596506154cd60408a01615135565b955060608901359450608089013593506151fd8a60a08b01615151565b6000602082840312156154fc57600080fd5b5035919050565b60008083601f84011261551557600080fd5b50813567ffffffffffffffff81111561552d57600080fd5b6020830191508360208260051b85010111156151a557600080fd5b60008060008060008060008060006101208a8c03121561556757600080fd5b6155708a615135565b985060208a013567ffffffffffffffff81111561558c57600080fd5b6155988c828d01615503565b90995097505060408a0135955060608a0135945060808a013593506155c08b60a08c01615151565b92506101008a013567ffffffffffffffff81111561546f57600080fd5b60008060008060008060008060006101408a8c0312156155fc57600080fd5b6156058a615135565b985061561360208b01615135565b975060408a0135965060608a0135955060808a0135945060a08a013593506154528b60c08c01615151565b600080600080600080600080610100898b03121561565b57600080fd5b883567ffffffffffffffff81111561567257600080fd5b61567e8b828c01615503565b9099509750506020890135955060408901359450606089013593506156a68a60808b01615151565b925060e089013567ffffffffffffffff81111561521a57600080fd5b60008060008060008060a087890312156156db57600080fd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff81111561570e57600080fd5b61571a89828a01615163565b979a9699509497509295939492505050565b6000806040838503121561573f57600080fd5b50508035926020909101359150565b6000806040838503121561576157600080fd5b61576a83615135565b915061577860208401615135565b90509250929050565b600181811c9082168061579557607f821691505b6020821081036147d857634e487b7160e01b600052602260045260246000fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156157f4576157f46157b5565b604052919050565b60ff81168114611a7357600080fd5b6000606082840312801561581e57600080fd5b506040516060810167ffffffffffffffff81118282101715615842576158426157b5565b6040528235615850816157fc565b8152602083810135908201526040928301359281019290925250919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610b8357610b83615885565b634e487b7160e01b600052601260045260246000fd5b6000826158e557634e487b7160e01b600052601260045260246000fd5b500490565b6000600182016158fc576158fc615885565b5060010190565b60006020828403121561591557600080fd5b8151610d50816157fc565b80820180821115610b8357610b83615885565b60ff8181168382160190811115610b8357610b83615885565b83815282602082015260606040820152600061596b60608301846150dc565b95945050505050565b60006020828403121561598657600080fd5b5051919050565b805169ffffffffffffffffffff8116811461514c57600080fd5b600080600080600060a086880312156159bf57600080fd5b6159c88661598d565b602087015160408801516060890151929750909550935091506159ed6080870161598d565b90509295509295909350565b60008060408385031215615a0c57600080fd5b8251602084015190925067ffffffffffffffff811115615a2b57600080fd5b8301601f81018513615a3c57600080fd5b805167ffffffffffffffff811115615a5657615a566157b5565b8060051b615a66602082016157cb565b91825260208184018101929081019088841115615a8257600080fd5b6020850194505b83851015615aa857845180835260209586019590935090910190615a89565b80955050505050509250929050565b60ff8281168282160390811115610b8357610b83615885565b6001815b6001841115615b0b57808504811115615aef57615aef615885565b6001841615615afd57908102905b60019390931c928002615ad4565b935093915050565b600082615b2257506001610b83565b81615b2f57506000610b83565b8160018114615b455760028114615b4f57615b6b565b6001915050610b83565b60ff841115615b6057615b60615885565b50506001821b610b83565b5060208310610133831016604e8410600b8410161715615b8e575081810a610b83565b615b9b6000198484615ad0565b8060001904821115615baf57615baf615885565b029392505050565b6000610d5060ff841683615b13565b81810381811115610b8357610b83615885565b8151600090829060208501835b82811015615c04578151845260209384019390910190600101615be6565b509195945050505050565b634e487b7160e01b600052602160045260246000fdfea2646970667358221220934a1d9a423aa150a2aba40cc46c732a188ea43bba4b7c2983ce68bf5989642464736f6c634300081c003300000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6200000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000a372e7f8ba1f0377667c8c52fea2bc3e271a0e680000000000000000000000000000000000000000000000000000000000000002000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62000000000000000000000000b24e3035d1fcbc0e43cf3143c3fd92e53df2009b00000000000000000000000000000000000000000000000000000000000000020000000000000000000000007bdbdb772f4a073badd676a567c6ed82049a8eee000000000000000000000000f6630799b5387e0e9ace92a5e82673021781b44000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000e100000000000000000000000000000000000000000000000000000000000000e10

Deployed Bytecode

0x60806040526004361061032d5760003560e01c806370a08231116101a5578063b8f44963116100ec578063d9bd8ba411610095578063eb1c64531161006f578063eb1c64531461098e578063ecc7633d146109ae578063f2fde38b146109db578063fdc85fc4146109fb57600080fd5b8063d9bd8ba414610908578063da5014c514610928578063dd62ed3e1461094857600080fd5b8063c4828729116100c6578063c4828729146108a8578063c72da66a146108c8578063ceaf4339146108e857600080fd5b8063b8f44963146107b9578063bfdb6b04146107d9578063c325a5491461085f57600080fd5b80638dda8f3f1161014e578063a726470511610128578063a726470514610766578063a7d46c2f14610786578063a9059cbb1461079957600080fd5b80638dda8f3f146106fd57806392a91a3a1461073157806395d89b411461075157600080fd5b80638414efe51161017f5780638414efe5146106b45780638baeefce146106ca5780638da5cb5b146106df57600080fd5b806370a0823114610654578063715018a61461068a578063780dd6641461069f57600080fd5b80632e7e1bd3116102745780633b26e4eb1161021d5780635aecdda5116101f75780635aecdda5146105c25780635b6f4dce1461060e578063608de8aa1461062157806365cd6db01461064157600080fd5b80633b26e4eb1461056f5780634372328a1461058f5780634cb6864c146105a257600080fd5b806334cb3d7f1161024e57806334cb3d7f14610504578063368dfc181461053a578063377a368c1461055a57600080fd5b80632e7e1bd3146104b3578063313ce567146104c8578063343add83146104e457600080fd5b80631b6a8759116102d657806326d9b5b3116102b057806326d9b5b31461046157806327a9b424146104805780632b651a6c1461049357600080fd5b80631b6a8759146104085780631dc6f5a51461041d57806323b872dd1461044157600080fd5b80630ce9a63d116103075780630ce9a63d146103b657806318160ddd146103c957806319f37361146103e857600080fd5b806306fdde0314610339578063078795ee14610364578063095ea7b31461038657600080fd5b3661033457005b600080fd5b34801561034557600080fd5b5061034e610a1b565b60405161035b9190615122565b60405180910390f35b34801561037057600080fd5b5061038461037f3660046151ac565b610aad565b005b34801561039257600080fd5b506103a66103a136600461523a565b610b6f565b604051901515815260200161035b565b6103846103c4366004615264565b610b89565b3480156103d557600080fd5b506002545b60405190815260200161035b565b3480156103f457600080fd5b506103a66104033660046152a7565b610bd2565b34801561041457600080fd5b506103da610bdf565b34801561042957600080fd5b50610432610bf0565b60405161035b939291906152c2565b34801561044d57600080fd5b506103a661045c366004615355565b610d31565b34801561046d57600080fd5b50600854600160a01b900460ff166103a6565b61038461048e366004615392565b610d57565b34801561049f57600080fd5b506103846104ae3660046153ea565b610de5565b3480156104bf57600080fd5b50610384610e69565b3480156104d457600080fd5b506040516012815260200161035b565b3480156104f057600080fd5b506103846104ff366004615492565b610eab565b34801561051057600080fd5b506103da61051f3660046152a7565b6001600160a01b031660009081526009602052604090205490565b34801561054657600080fd5b506103846105553660046154ea565b610fec565b34801561056657600080fd5b506103da611064565b34801561057b57600080fd5b5061038461058a3660046153ea565b6110ba565b61038461059d366004615548565b6110ff565b3480156105ae57600080fd5b506103846105bd366004615392565b6111e1565b3480156105ce57600080fd5b506105f67f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6281565b6040516001600160a01b03909116815260200161035b565b61038461061c3660046155dd565b611264565b34801561062d57600080fd5b5061038461063c36600461563e565b6112c9565b61038461064f3660046156c2565b611347565b34801561066057600080fd5b506103da61066f3660046152a7565b6001600160a01b031660009081526020819052604090205490565b34801561069657600080fd5b50610384611493565b3480156106ab57600080fd5b506104326114a7565b3480156106c057600080fd5b506103da60075481565b3480156106d657600080fd5b506103846115b8565b3480156106eb57600080fd5b506006546001600160a01b03166105f6565b34801561070957600080fd5b506105f67f00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f881565b34801561073d57600080fd5b506105f661074c3660046154ea565b611600565b34801561075d57600080fd5b5061034e61160d565b34801561077257600080fd5b50600e546105f6906001600160a01b031681565b610384610794366004615264565b61161c565b3480156107a557600080fd5b506103a66107b436600461523a565b61165c565b3480156107c557600080fd5b506103846107d43660046152a7565b61166a565b3480156107e557600080fd5b506108406107f43660046152a7565b6001600160a01b039081166000908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff16939092019290925291565b604080516001600160a01b03909316835260208301919091520161035b565b34801561086b57600080fd5b5061089361087a3660046152a7565b600d602052600090815260409020805460019091015482565b6040805192835260208301919091520161035b565b3480156108b457600080fd5b506103846108c3366004615355565b6116cf565b3480156108d457600080fd5b506103846108e3366004615392565b611869565b3480156108f457600080fd5b506103846109033660046152a7565b6118ae565b34801561091457600080fd5b5061038461092336600461572c565b611900565b34801561093457600080fd5b506008546105f6906001600160a01b031681565b34801561095457600080fd5b506103da61096336600461574e565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b34801561099a57600080fd5b506103a66109a93660046152a7565b611a03565b3480156109ba57600080fd5b506103da6109c93660046152a7565b60096020526000908152604090205481565b3480156109e757600080fd5b506103846109f63660046152a7565b611a33565b348015610a0757600080fd5b50610384610a163660046152a7565b611a76565b606060038054610a2a90615781565b80601f0160208091040260200160405190810160405280929190818152602001828054610a5690615781565b8015610aa35780601f10610a7857610100808354040283529160200191610aa3565b820191906000526020600020905b815481529060010190602001808311610a8657829003601f168201915b5050505050905090565b610ab5611b17565b8342811015610ad757604051639a29b6fb60e01b815260040160405180910390fd5b866001811015610afa5760405163abf20e8f60e01b815260040160405180910390fd5b610b0f6001600160a01b038b1633308c611b42565b610b63338b8b8b8b8b610b27368d90038d018d61580b565b8b8b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc492505050565b50505050505050505050565b600033610b7d818585611c2e565b60019150505b92915050565b610b91611b17565b8363ffffffff1642811015610bb957604051639a29b6fb60e01b815260040160405180910390fd5b610bc98787878787876001611c40565b50505050505050565b6000610b83600b83611ce4565b6000610beb600b611d06565b905090565b606080600080610bfe610bdf565b905060008167ffffffffffffffff811115610c1b57610c1b6157b5565b604051908082528060200260200182016040528015610c44578160200160208202803683370190505b50905060008267ffffffffffffffff811115610c6257610c626157b5565b604051908082528060200260200182016040528015610c8b578160200160208202803683370190505b50905060005b83811015610d17576000610ca482611600565b9050610cc5816001600160a01b031660009081526009602052604090205490565b848381518110610cd757610cd761586f565b60200260200101818152505080838381518110610cf657610cf661586f565b6001600160a01b039092166020928302919091019091015250600101610c91565b508181610d2360025490565b955095509550505050909192565b600033610d3f858285611d10565b610d4a858585611d89565b60019150505b9392505050565b610d5f611b17565b8463ffffffff1642811015610d8757604051639a29b6fb60e01b815260040160405180910390fd5b610dda8989898989610d9e368b90038b018b61580b565b89898080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611de892505050565b505050505050505050565b610ded611b17565b8463ffffffff1642811015610e1557604051639a29b6fb60e01b815260040160405180910390fd5b610b638a8a8a8a8a8a610e2d368c90038c018c61580b565b8a8a8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611e3e92505050565b610e71611ec5565b6008805460ff60a01b1916905560405133907f542e2be6bf739156fc5d022ffac81c0c9b281c19e6491b63bb14281433138b1790600090a2565b610eb3611b17565b87336001600160a01b03821614610edd57604051635c427cd960e01b815260040160405180910390fd5b8442811015610eff57604051639a29b6fb60e01b815260040160405180910390fd5b60006001600160a01b038916610f3657507f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62975060015b6000610f488c8c8c8c8c8c8c8c611ef0565b9050610f5381611f9a565b610f5e8a8a8d611fe5565b610f68338c61200a565b8115610f7d57610f78338a612044565b610f88565b610f888a338b612103565b896001600160a01b03168c6001600160a01b03167f41e79959bad1d45680578f8a544fb5af76d72b04090e65a51b4d0eaab959a9ab8d8c604051610fd6929190918252602082015260400190565b60405180910390a3505050505050505050505050565b6000610ff760025490565b611006836402540be40061589b565b61101091906158c8565b905061101c338361200a565b61102581612132565b604080518381526020810183905233917f92ccf450a286a957af52509bc1c9939d1a6a481783e142e41e2499f0bb66ebc6910160405180910390a25050565b600061106f33611a03565b61108c5760405163bb1c8b6560e01b815260040160405180910390fd5b50336000818152600d602052604081206001810180549183905591909155906110b790309083611d89565b90565b6110c2611b17565b8463ffffffff16428110156110ea57604051639a29b6fb60e01b815260040160405180910390fd5b610e156001600160a01b038b1633308b611b42565b611107611b17565b834281101561112957604051639a29b6fb60e01b815260040160405180910390fd5b86600181101561114c5760405163abf20e8f60e01b815260040160405180910390fd5b6111d48b8b8b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152508d92508c91508b9050611198368c90038c018c61580b565b8a8a8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506121b092505050565b5050505050505050505050565b6111e9611b17565b8463ffffffff164281101561121157604051639a29b6fb60e01b815260040160405180910390fd5b610dda8989898989611228368b90038b018b61580b565b89898080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506121fb92505050565b61126c611b17565b834281101561128e57604051639a29b6fb60e01b815260040160405180910390fd5b8660018110156112b15760405163abf20e8f60e01b815260040160405180910390fd5b6111d48b8b8b8b8b8b610b27368d90038d018d61580b565b6112d1611b17565b6000875b808210156113365760008a8a848181106112f1576112f161586f565b90506020020135905060008111156113235761132333308361131287611600565b6001600160a01b0316929190611b42565b8261132d816158ea565b935050506112d5565b610b63338b8b8b8b8b8b8b8b6110ff565b61134f611b17565b608085901c6bffffffffffffffffffffffff602087901c1662ffffff600888901c164282101561139257604051639a29b6fb60e01b815260040160405180910390fd5b60018110156113b45760405163abf20e8f60e01b815260040160405180910390fd5b6040805160608082018352600080835260208084018290529284018190528351918201845260ff8c1682529181018a905291820188905260a08b901c908b906001600160a01b038216611429577f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62915061143e565b61143e6001600160a01b038316333086611b42565b50611485338284878a8a898f8f8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc492505050565b505050505050505050505050565b61149b6122c8565b6114a560006122f5565b565b6060806000806114b5610bdf565b905060008167ffffffffffffffff8111156114d2576114d26157b5565b6040519080825280602002602001820160405280156114fb578160200160208202803683370190505b50905060008267ffffffffffffffff811115611519576115196157b5565b604051908082528060200260200182016040528015611542578160200160208202803683370190505b50905060005b83811015610d1757600061155b82611600565b905061156681612347565b8483815181106115785761157861586f565b602002602001018181525050808383815181106115975761159761586f565b6001600160a01b039092166020928302919091019091015250600101611548565b6115c0611ec5565b6008805460ff60a01b1916600160a01b17905560405133907fcabe820ce05cacdbb20404e8bba2a9cbadaa7ff6e3a3294b6d5152526765942090600090a2565b6000610b83600b836123b2565b606060048054610a2a90615781565b611624611b17565b8363ffffffff164281101561164c57604051639a29b6fb60e01b815260040160405180910390fd5b610bc98787878787876000611c40565b600033610b7d818585611d89565b6116726122c8565b61167b816123be565b600e80546001600160a01b0319166001600160a01b0383169081179091556040519081527f33fa9d54e48b14392fffa8aa3cfec14c54552fa92d5f44048005ec6437ee97649060200160405180910390a150565b6116d76122c8565b600081116116f857604051639589a27d60e01b815260040160405180910390fd5b61170183612464565b61171e57604051630732619560e01b815260040160405180910390fd5b600061172a838361246f565b90506000811161174d57604051639589a27d60e01b815260040160405180910390fd5b6040518060600160405280846001600160a01b03168152602001838152602001846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117cf9190615903565b60ff9081169091526001600160a01b038681166000818152600f6020908152604091829020865181546001600160a01b031916908616178155868201516001820155958201516002909601805460ff19169690951695909517909355825191871682529281018590527fc9c48c8a3a63b9d481d1f1dc5a7ca531d0fe9ddfd25f00f6c91090175f7b0053910160405180910390a250505050565b611871611b17565b8463ffffffff164281101561189957604051639a29b6fb60e01b815260040160405180910390fd5b6112116001600160a01b038a1633308b611b42565b6118b66122c8565b600880546001600160a01b0319166001600160a01b0383169081179091556040517f7fb818801719b0f482b3e69a97fd8c5a1bddd186808ae2a83bdf1dac62c550ec90600090a250565b6119086122c8565b60008161191a846402540be40061589b565b61192491906158c8565b905061193660146402540be4006158c8565b8111156119565760405163051fb32160e01b815260040160405180910390fd5b62093a806007546119679190615920565b42101561198757604051637bd0a7dd60e01b815260040160405180910390fd5b4260075560006402540be40061199c60025490565b6119a6908461589b565b6119b091906158c8565b90506119bc3382612544565b60408051858152602081018590529081018290527f26092d07f0187f928cdea6737c0e6d7496aea7e4d4fb32daf1ccd48793ce0b8e9060600160405180910390a150505050565b6001600160a01b0381166000908152600d60205260408120600181015415801590610d5057505442101592915050565b611a3b6122c8565b6001600160a01b038116611a6a57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b611a73816122f5565b50565b611a7e6122c8565b6001600160a01b038181166000908152600f602052604090205416611ab657604051633e1e538160e21b815260040160405180910390fd5b6001600160a01b0381166000818152600f602052604080822080546001600160a01b031916815560018101839055600201805460ff19169055517f9c8e7d83025bef8a04c664b2f753f64b8814bdb7e27291d7e50935f18cc3c7129190a250565b600854600160a01b900460ff16156114a5576040516326f4363f60e21b815260040160405180910390fd5b6040516001600160a01b038481166024830152838116604483015260648201839052611bbe9186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505061257a565b50505050565b611bcd87610bd2565b611bea57604051630732619560e01b815260040160405180910390fd5b611bf26125eb565b6000611c04898989898989898961261b565b9050611c0f81611f9a565b611c1a88888761266a565b611c23886126a3565b610dda898787612727565b611c3b838383600161277b565b505050565b6040805160608101825260008082526020820181905291810182905260a089811c928a92918a901c918a916001600160ff1b03881690611c8560ff8a901c601b615933565b6040805160608101825260ff9092168252602082018c9052810192909252509050858015611cbb57506001600160a01b03841615155b15611cd557611cd56001600160a01b038516333088611b42565b611485848387868e8e87612850565b6001600160a01b03811660009081526001830160205260408120541515610d50565b6000610b83825490565b6001600160a01b03838116600090815260016020908152604080832093861683529290522054600019811015611bbe5781811015611d7a57604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401611a61565b611bbe8484848403600061277b565b6001600160a01b038316611db357604051634b637e8f60e11b815260006004820152602401611a61565b6001600160a01b038216611ddd5760405163ec442f0560e01b815260006004820152602401611a61565b611c3b8383836128c9565b611e127f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62876129f3565b610bc97f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62888888888888885b600080611e508a8a8a8a8a8a8a612a67565b91509150611e608a8a8784612ab1565b846001600160a01b0316896001600160a01b03168b6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c8858588604051611eb19392919061594c565b60405180910390a450505050505050505050565b6008546001600160a01b031633146114a557604051635c427cd960e01b815260040160405180910390fd5b6000806000611f3485858080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250612ae992505050565b91509150611f687f597a4374bafbb595c980a613ed1b42b24b82bad0156856dd6fe2e5f33e3081b38c8c8c8c8c8888612b39565b9250611f8283611f7d3689900389018961580b565b612b75565b611f8c8282612ba0565b505098975050505050505050565b60008181526010602052604090205460ff1615611fca576040516306542de760e11b815260040160405180910390fd5b6000908152601060205260409020805460ff19166001179055565b611fed612d37565b15611c3b576000611ffe8484612d99565b9050611bbe8183612e22565b6001600160a01b03821661203457604051634b637e8f60e11b815260006004820152602401611a61565b612040826000836128c9565b5050565b61204c612e62565b604051632e1a7d4d60e01b8152600481018290527f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626001600160a01b031690632e1a7d4d90602401600060405180830381600087803b1580156120ae57600080fd5b505af11580156120c2573d6000803e3d6000fd5b505050506120ef7f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626126a3565b6120f982826129f3565b6120406001600555565b61210b612e62565b61211f6001600160a01b0384168383612e8c565b612128836126a3565b611c3b6001600555565b600080600061213f610bdf565b90505b80821015611bbe57600061215583611600565b90506402540be40061217c826001600160a01b031660009081526009602052604090205490565b612186908761589b565b61219091906158c8565b935061219d813386612103565b826121a7816158ea565b93505050612142565b6121b86125eb565b60006121c988888888888888612ebd565b90506121d481611f9a565b6121de8786612f4f565b6121e6612fee565b6121f1888787612727565b5050505050505050565b60008061222d897f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab628a8a8a8a8a612a67565b9150915061223a896126a3565b6122448582612044565b846001600160a01b03167f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab626001600160a01b03168a6001600160a01b03167f4be05c8d54f5e056ab2cfa033e9f582057001268c3e28561bb999d35d2c8f2c88585886040516122b59392919061594c565b60405180910390a4505050505050505050565b6006546001600160a01b031633146114a55760405163118cdaa760e01b8152336004820152602401611a61565b600680546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b6040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa15801561238e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b839190615974565b6000610d508383613029565b6001600160a01b0381166123e557604051631c06ca6760e01b815260040160405180910390fd5b806001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa92505050801561243f575060408051601f3d908101601f1916820190925261243c918101906159a7565b60015b61245c57604051631c06ca6760e01b815260040160405180910390fd5b505050505050565b6000610b8382610bd2565b6000806000806000866001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa1580156124b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124d991906159a7565b9450945050935093508069ffffffffffffffffffff168469ffffffffffffffffffff1614158061251257504261250f8784615920565b11155b156125305760405163a9f7344560e01b815260040160405180910390fd5b61253983613053565b979650505050505050565b6001600160a01b03821661256e5760405163ec442f0560e01b815260006004820152602401611a61565b612040600083836128c9565b600080602060008451602086016000885af18061259d576040513d6000823e3d81fd5b50506000513d915081156125b55780600114156125c2565b6001600160a01b0384163b155b15611bbe57604051635274afe760e01b81526001600160a01b0385166004820152602401611a61565b34156114a5576114a57f000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62346129f3565b600080600061262984612ae9565b9150915061265e7f597a4374bafbb595c980a613ed1b42b24b82bad0156856dd6fe2e5f33e3081b38c8c8c8c8c8c898961307d565b9250611f828386612b75565b6000612674612d37565b1561267d575060015b600061268a8585846130bb565b9050811561269c5761269c8382612e22565b5050505050565b6040516370a0823160e01b81523060048201526001600160a01b038216906370a0823190602401602060405180830381865afa1580156126e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061270b9190615974565b6001600160a01b03909116600090815260096020526040902055565b612732838383613105565b60408051828152602081018490526001600160a01b038516917f73a19dd210f1a7f902193214c0ee91dd35ee5b4d920cba8d519eca65a7b488ca910160405180910390a2505050565b6001600160a01b0384166127a55760405163e602df0560e01b815260006004820152602401611a61565b6001600160a01b0383166127cf57604051634a1406b160e11b815260006004820152602401611a61565b6001600160a01b0380851660009081526001602090815260408083209387168352929052208290558015611bbe57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161284291815260200190565b60405180910390a350505050565b604080516001600160a01b0319841660208201528151600c818303018152602c909101909152829081906001600160a01b038a1661289c5761289789898989878987611de8565b610b63565b6001600160a01b0389166128b9576128978a8989898789876121fb565b610b638a8a8a8a8a888a88611e3e565b6001600160a01b0383166128f45780600260008282546128e99190615920565b909155506129669050565b6001600160a01b038316600090815260208190526040902054818110156129475760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401611a61565b6001600160a01b03841660009081526020819052604090209082900390555b6001600160a01b038216612982576002805482900390556129a1565b6001600160a01b03821660009081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516129e691815260200190565b60405180910390a3505050565b6000826001600160a01b03168260405160006040518083038185875af1925050503d8060008114612a40576040519150601f19603f3d011682016040523d82523d6000602084013e612a45565b606091505b5050905080611c3b57604051630db2c7f160e31b815260040160405180910390fd5b6000806000612a7b8a8a8a8a8a8a8a6131c0565b9050612a8681611f9a565b612a928a8a8a8a6131fd565b9093509150612aa48a848b858a61326d565b5097509795505050505050565b612ab9612e62565b612ac2846126a3565b612ad66001600160a01b0384168383612e8c565b612adf836126a3565b611bbe6001600555565b6000606082806020019051810190612b0191906159f9565b90925090506000612b10610bdf565b905080825114612b3357604051632b477e7160e11b815260040160405180910390fd5b50915091565b600080612b4b8989898989898961341f565b60405161190160f01b8152600281019b909b5260228b015250506042909720979650505050505050565b61204082827f00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f86135b3565b6000612bab60025490565b905080600003612bba57505050565b82600003612bdb57604051632ab0223d60e21b815260040160405180910390fd5b6000612be5610bdf565b90506000805b82811015612ca5576000612bfe82611600565b6001600160a01b0381166000908152600a602052604081205491925090612c299060ff166012615ab7565b612c3490600a615bb7565b9050600081612c4284612347565b612c4c919061589b565b90506000670de0b6b3a7640000898681518110612c6b57612c6b61586f565b602002602001015183612c7e919061589b565b612c8891906158c8565b9050612c948187615920565b955050505050806001019050612beb565b50600083612cbb670de0b6b3a76400008461589b565b612cc591906158c8565b9050858103612cd657505050505050565b6000612710612ce6600a8961589b565b612cf091906158c8565b90506000878311612d0a57612d058389615bc6565b612d14565b612d148884615bc6565b9050818111156121f1576040516340ba9c2b60e11b815260040160405180910390fd5b600080612d42613677565b905060005b81811015612d90576000600f81612d5d84613681565b6001600160a01b0390811682526020820192909252604001600020541603612d885760009250505090565b600101612d47565b50600191505090565b6000806000612da78561368c565b915091506000612dcf866001600160a01b03166000908152600a602052604090205460ff1690565b612dda906012615ab7565b612de590600a615bb7565b90506000612df3828761589b565b90506000612e0284600a615bb7565b612e0c868461589b565b612e1691906158c8565b98975050505050505050565b6000612e35612e3060025490565b6136f8565b90506000670de0b6b3a7640000612e4c838661589b565b612e5691906158c8565b9050611bbe8184613783565b600260055403612e8557604051633ee5aeb560e01b815260040160405180910390fd5b6002600555565b6040516001600160a01b03838116602483015260448201839052611c3b91859182169063a9059cbb90606401611b77565b600080612ec8610bdf565b905087518114612eeb57604051632b477e7160e11b815260040160405180910390fd5b600080612ef785612ae9565b91509150612f2b7f597a4374bafbb595c980a613ed1b42b24b82bad0156856dd6fe2e5f33e3081b38c8c8c8c8c88886137c9565b9350612f378487612b75565b612f418282612ba0565b505050979650505050505050565b6000612f59612d37565b15612f62575060015b6000612f6c610bdf565b90506000805b82811015612fdd576000868281518110612f8e57612f8e61586f565b60200260200101511115612fd557612fc8612fa882611600565b878381518110612fba57612fba61586f565b6020026020010151866130bb565b612fd29083615920565b91505b600101612f72565b50821561269c5761269c8482612e22565b600080612ffb600b611d06565b90505b808210156120405761301761301283611600565b6126a3565b81613021816158ea565b925050612ffe565b60008260000182815481106130405761304061586f565b9060005260206000200154905092915050565b60008082121561307957604051635467221960e11b815260048101839052602401611a61565b5090565b6000806130908a8a8a8a8a8a8a8a6137db565b60405161190160f01b8152600281019c909c5260228c01525050604290982098975050505050505050565b6000806130c78561395d565b9050838110156130ea5760405163f8b3bb6160e01b815260040160405180910390fd5b82156130fd576130fa8582612d99565b91505b509392505050565b60018210156131275760405163abf20e8f60e01b815260040160405180910390fd5b6001600160a01b0383166000908152600d602052604090206001015415613161576040516329e8d8e960e11b815260040160405180910390fd5b6000604051806040016040528084603c61317b919061589b565b6131859042615920565b815260209081018490526001600160a01b0386166000908152600d82526040902082518155908201516001909101559050611bbe3083612544565b60006131f17f597a4374bafbb595c980a613ed1b42b24b82bad0156856dd6fe2e5f33e3081b38989898989896139e1565b90506125398183612b75565b60008061320986610bd2565b61322657604051630732619560e01b815260040160405180910390fd5b61322f85610bd2565b61324c57604051630732619560e01b815260040160405180910390fd5b6132558661395d565b9150613262848385613a20565b905094509492505050565b6132986040518060800160405280600081526020016000815260200160008152602001600081525090565b6001600160a01b03868116600081815260096020818152604080842054875294891683529081528382205485820152918152600a82528290205460c085901c9267ffffffffffffffff608087901c81169361ffff603089901c8116949189901c169288901c9091169061330f9060ff166012615ab7565b61331a90600a615bb7565b6040808801919091526001600160a01b038a166000908152600a60205220546133479060ff166012615ab7565b61335290600a615bb7565b606087015260408601516000906133ac9061336d908d61589b565b60408901518951899161337f9161589b565b878b606001518e613390919061589b565b8a8d606001518e602001516133a5919061589b565b8a8a613ac1565b9050806133cc5760405163473ab96d60e11b815260040160405180910390fd5b6001600160a01b038c81166000908152600f6020526040902054161580159061340e57506001600160a01b038a81166000908152600f60205260409020541615155b15611485576114858b8a8e8d613c76565b600080826040516020016134339190615bd9565b60405160208183030381529060405280519060200120905060405160200161353c907f5769746864726177616c537472756374286164647265737320746f6b656e5f6881527f6f6c6465722c75696e7432353620706f6f6c5f746f6b656e5f616d6f756e745f60208201527f746f5f6275726e2c616464726573732061737365745f616464726573732c756960408201527f6e743235362061737365745f616d6f756e742c75696e7432353620676f6f645f60608201527f756e74696c2c75696e74323536206c705f746f6b656e5f70726963652c75696e60808201527f743235365b5d207072696365732900000000000000000000000000000000000060a082015260ae0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039b8c1683830152606083019a909a529790991660808a015260a0890195909552505060c086019190915260e085015261010080850191909152815180850390910181526101209093019052815191012090565b60006135cd84846000015185602001518660400151613e12565b9050816001600160a01b0316816001600160a01b031614611bbe57613643843260405160200161361992919091825260601b6bffffffffffffffffffffffff1916602082015260340190565b60405160208183030381529060405280519060200120846000015185602001518660400151613e12565b9050816001600160a01b0316816001600160a01b031614611bbe576040516314cdc32360e31b815260040160405180910390fd5b6000610beb610bdf565b6000610b8382611600565b600080613697613e40565b6001600160a01b038084166000908152600f602090815260409182902082516060810184528154909416808552600182015492850183905260029091015460ff16928401929092526136e9919061246f565b92508060400151915050915091565b600080613703613677565b90506000805b8281101561374557600061371c82613681565b90506137308161372b83613f23565b612d99565b61373a9084615920565b925050600101613709565b508315613770578361375f670de0b6b3a76400008361589b565b61376991906158c8565b925061377c565b670de0b6b3a764000092505b5050919050565b600061271061379360148461589b565b61379d91906158c8565b90506137a98183615920565b831115611c3b576040516317427d6560e31b815260040160405180910390fd5b600080612b4b89898989898989613f41565b600080826040516020016137ef9190615bd9565b6040516020818303038152906040528051906020012090506040516020016138df907f53696e676c654465706f7369745374727563742861646472657373206465706f81527f7369746f722c6164647265737320746f6b656e2c75696e7432353620616d6f7560208201527f6e742c75696e74323536206c6f636b5f74696d652c75696e7432353620706f6f60408201527f6c5f746f6b656e732c75696e7432353620676f6f645f756e74696c2c75696e7460608201527f323536206c705f746f6b656e5f70726963652c75696e743235365b5d207072696080820152636365732960e01b60a082015260a40190565b60408051808303601f190181528282528051602091820120818401526001600160a01b039c8d16838301529a909b166060820152608081019890985260a0880196909652505060c085019290925260e08401526101008301526101208083019190915283518083039091018152610140909101909252815191012090565b6001600160a01b0381166000818152600960205260408082205490516370a0823160e01b8152306004820152919290916370a0823190602401602060405180830381865afa1580156139b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139d79190615974565b610b839190615bc6565b6000806139f28888888888886140e1565b60405161190160f01b8152600281018b905260228101829052604290209091505b9998505050505050505050565b6000838303613a30575080610d50565b600084613a42856402540be40061589b565b613a4c91906158c8565b9050613a5c620f4240603261589b565b613a6b906402540be400615920565b8110613ab1576402540be40083613a86620f4240603261589b565b613a95906402540be400615920565b613a9f919061589b565b613aa991906158c8565b915050610d50565b6402540be400613a9f848361589b565b60008080806305f5e100613ad58c8e61589b565b613adf91906158c8565b90506000613af6613af08c8461589b565b87614220565b90508015613b285780613b1183670de0b6b3a764000061589b565b613b1b91906158c8565b613b259085615920565b93505b60006305f5e100613b398a8c61589b565b613b4391906158c8565b90506000613b5a613b548a8461589b565b89614220565b90508015613b8c5780613b7583670de0b6b3a764000061589b565b613b7f91906158c8565b613b899087615920565b95505b5050505060006305f5e1008d8c613ba39190615920565b613bad908e61589b565b613bb791906158c8565b90506000613bc8613af08c8461589b565b90508015613bfa5780613be383670de0b6b3a764000061589b565b613bed91906158c8565b613bf79084615920565b92505b60006305f5e100613c0b8c8b615bc6565b613c15908c61589b565b613c1f91906158c8565b90506000613c30613b548a8461589b565b90508015613c625780613c4b83670de0b6b3a764000061589b565b613c5591906158c8565b613c5f9086615920565b94505b50505091109b9a5050505050505050505050565b600080613c828461368c565b91509150600080613c928561368c565b91509150613cc16040518060800160405280600081526020016000815260200160008152602001600081525090565b6001600160a01b0387166000908152600a602052604090205460ff16613ce8906012615ab7565b613cf390600a615bb7565b6040820152613d1a866001600160a01b03166000908152600a602052604090205460ff1690565b613d25906012615ab7565b613d3090600a615bb7565b60608201526040810151613d44908a61589b565b81526000613d53856012615ab7565b613d5e90600a615bb7565b613d68908761589b565b90506000613d77846012615ab7565b613d8290600a615bb7565b613d8c908661589b565b90506000836060015182848660000151613da6919061589b565b613db091906158c8565b613dba91906158c8565b90506000612710613dcc60c882615920565b613dd6908461589b565b613de091906158c8565b9050808c1115613e0357604051630d6974bb60e31b815260040160405180910390fd5b50505050505050505050505050565b600080600080613e2488888888614299565b925092509250613e348282614368565b50909695505050505050565b600e546001600160a01b0316613e5257565b600080600e60009054906101000a90046001600160a01b03166001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015613ea8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ecc91906159a7565b5050925092505081600014613ef35760405162032b3d60e81b815260040160405180910390fd5b6000613eff8242615bc6565b9050610e108111611c3b5760405163d15f73b560e01b815260040160405180910390fd5b6001600160a01b038116600090815260096020526040812054610b83565b60008087604051602001613f559190615bd9565b604051602081830303815290604052805190602001209050600083604051602001613f809190615bd9565b604051602081830303815290604052805190602001209050604051602001614063907f4465706f7369745374727563742861646472657373206465706f7369746f722c81527f75696e743235365b5d206465706f7369745f616d6f756e74732c75696e74323560208201527f36206c6f636b5f74696d652c75696e7432353620706f6f6c5f746f6b656e732c60408201527f75696e7432353620676f6f645f756e74696c2c75696e74323536206c705f746f60608201527f6b656e5f70726963652c75696e743235365b5d207072696365732900000000006080820152609b0190565b60408051601f198184030181528282528051602091820120908301526001600160a01b038c1690820152606081018390526080810189905260a0810188905260c0810187905260e081018690526101008101829052610120016040516020818303038152906040528051906020012092505050979650505050505050565b60006040516020016141ae907f4f66666572537472756374286164647265737320696e7075745f746f6b656e2c81527f61646472657373206f75747075745f746f6b656e2c75696e7432353620696e7060208201527f75745f616d6f756e742c75696e74323536206f75747075745f616d6f756e742c60408201527f75696e7432353620676f6f645f756e74696c2c6164647265737320646573746960608201527f6e6174696f6e5f616464726573732900000000000000000000000000000000006080820152608f0190565b60408051808303601f190181528282528051602091820120818401526001600160a01b03998a16838301529789166060830152608082019690965260a08101949094525060c083019190915290931660e080850191909152815180850390910181526101009093019052815191012090565b60008260000361423257506000610b83565b60006142486142436110b786614421565b61444e565b90506000614274670de0b6b3a764000061426e846142686110b789614421565b906145bc565b9061467a565b905060006142846110b783614727565b905061428f81613053565b9350505050610b83565b600080807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411156142d4575060009150600390508261435e565b604080516000808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015614328573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166143545750600092506001915082905061435e565b9250600091508190505b9450945094915050565b600082600381111561437c5761437c615c0f565b03614385575050565b600182600381111561439957614399615c0f565b036143b75760405163f645eedf60e01b815260040160405180910390fd5b60028260038111156143cb576143cb615c0f565b036143ec5760405163fce698f760e01b815260048101829052602401611a61565b600382600381111561440057614400615c0f565b03612040576040516335e2f38360e21b815260048101829052602401611a61565b60006001600160ff1b038211156130795760405163123baf0360e11b815260048101839052602401611a61565b6000818181136144745760405163059b101b60e01b815260048101849052602401611a61565b6000670de0b6b3a7640000821261448d575060016144b3565b50600019816ec097ce7bc90715b34b9f1000000000816144af576144af6158b2565b0591505b600061453f670de0b6b3a7640000840560016fffffffffffffffffffffffffffffffff821160071b91821c67ffffffffffffffff811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211871b91821c969096119490961792909217171791909117919091171790565b9050670de0b6b3a7640000810283821d670de0b6b3a763ffff19810161456757818402612539565b671bc16d674ec800006706f05b59d3b200005b60008113156145ad57670de0b6b3a76400008380020592508183126145a5579283019260019290921d915b60011d61457a565b50505091909102949350505050565b60008282600160ff1b8214806145d55750600160ff1b81145b156145f35760405163a6070c2560e01b815260040160405180910390fd5b600080600084126146045783614609565b836000035b915060008312614619578261461e565b826000035b9050600061462c83836147de565b90506001600160ff1b038111156146605760405163120b5b4360e01b81526004810189905260248101889052604401611a61565b60001985851813613a1381614676578260000390565b8290565b60008282600160ff1b8214806146935750600160ff1b81145b156146b1576040516309fe2b4560e41b815260040160405180910390fd5b600080600084126146c257836146c7565b836000035b9150600083126146d757826146dc565b826000035b905060006146f383670de0b6b3a764000084614894565b90506001600160ff1b038111156146605760405163d49c26b360e01b81526004810189905260248101889052604401611a61565b6000818181121561478d5768033dd1780914b971141981121561474d5750600092915050565b6147866147656110b76147608460000390565b614727565b6ec097ce7bc90715b34b9f100000000081614782576147826158b2565b0590565b91506147d8565b680a688906bd8affffff8113156147b957604051626c1a0560e31b815260048101849052602401611a61565b670de0b6b3a7640000604082901b056147d46110b782614968565b9250505b50919050565b60008080600019848609848602925082811083820303915050806000036148125750670de0b6b3a764000090049050610b83565b670de0b6b3a7640000811061484457604051635173648d60e01b81526004810186905260248101859052604401611a61565b6000670de0b6b3a764000085870962040000818503049310909103600160ee1b02919091177faccb18165bd6fe31ae1cf318dc5b51eee0e1ba569b88cd74c1773b91fac106690291505092915050565b60008080600019858709858702925082811083820303915050806000036148ce578382816148c4576148c46158b2565b0492505050610d50565b8381106148ff57604051630c740aef60e31b8152600481018790526024810186905260448101859052606401611a61565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b7780000000000000000000000000000000000000000000000067ff00000000000000821615614a89576780000000000000008216156149b05768016a09e667f3bcc9090260401c5b6740000000000000008216156149cf576801306fe0a31b7152df0260401c5b6720000000000000008216156149ee576801172b83c7d517adce0260401c5b671000000000000000821615614a0d5768010b5586cf9890f62a0260401c5b670800000000000000821615614a2c576801059b0d31585743ae0260401c5b670400000000000000821615614a4b57680102c9a3e778060ee70260401c5b670200000000000000821615614a6a5768010163da9fb33356d80260401c5b670100000000000000821615614a8957680100b1afa5abcbed610260401c5b66ff000000000000821615614b88576680000000000000821615614ab65768010058c86da1c09ea20260401c5b6640000000000000821615614ad4576801002c605e2e8cec500260401c5b6620000000000000821615614af257680100162f3904051fa10260401c5b6610000000000000821615614b10576801000b175effdc76ba0260401c5b6608000000000000821615614b2e57680100058ba01fb9f96d0260401c5b6604000000000000821615614b4c5768010002c5cc37da94920260401c5b6602000000000000821615614b6a576801000162e525ee05470260401c5b6601000000000000821615614b885768010000b17255775c040260401c5b65ff0000000000821615614c7e5765800000000000821615614bb3576801000058b91b5bc9ae0260401c5b65400000000000821615614bd057680100002c5c89d5ec6d0260401c5b65200000000000821615614bed5768010000162e43f4f8310260401c5b65100000000000821615614c0a57680100000b1721bcfc9a0260401c5b65080000000000821615614c275768010000058b90cf1e6e0260401c5b65040000000000821615614c44576801000002c5c863b73f0260401c5b65020000000000821615614c6157680100000162e430e5a20260401c5b65010000000000821615614c7e576801000000b1721835510260401c5b64ff00000000821615614d6b57648000000000821615614ca757680100000058b90c0b490260401c5b644000000000821615614cc35768010000002c5c8601cc0260401c5b642000000000821615614cdf576801000000162e42fff00260401c5b641000000000821615614cfb5768010000000b17217fbb0260401c5b640800000000821615614d17576801000000058b90bfce0260401c5b640400000000821615614d3357680100000002c5c85fe30260401c5b640200000000821615614d4f5768010000000162e42ff10260401c5b640100000000821615614d6b57680100000000b17217f80260401c5b63ff000000821615614e4f576380000000821615614d925768010000000058b90bfc0260401c5b6340000000821615614dad576801000000002c5c85fe0260401c5b6320000000821615614dc857680100000000162e42ff0260401c5b6310000000821615614de3576801000000000b17217f0260401c5b6308000000821615614dfe57680100000000058b90c00260401c5b6304000000821615614e195768010000000002c5c8600260401c5b6302000000821615614e34576801000000000162e4300260401c5b6301000000821615614e4f5768010000000000b172180260401c5b62ff0000821615614f2a5762800000821615614e74576801000000000058b90c0260401c5b62400000821615614e8e57680100000000002c5c860260401c5b62200000821615614ea85768010000000000162e430260401c5b62100000821615614ec257680100000000000b17210260401c5b62080000821615614edc5768010000000000058b910260401c5b62040000821615614ef6576801000000000002c5c80260401c5b62020000821615614f1057680100000000000162e40260401c5b62010000821615614f2a576801000000000000b1720260401c5b61ff00821615614ffc57618000821615614f4d57680100000000000058b90260401c5b614000821615614f665768010000000000002c5d0260401c5b612000821615614f7f576801000000000000162e0260401c5b611000821615614f985768010000000000000b170260401c5b610800821615614fb1576801000000000000058c0260401c5b610400821615614fca57680100000000000002c60260401c5b610200821615614fe357680100000000000001630260401c5b610100821615614ffc57680100000000000000b10260401c5b60ff8216156150c557608082161561501d57680100000000000000590260401c5b6040821615615035576801000000000000002c0260401c5b602082161561504d57680100000000000000160260401c5b6010821615615065576801000000000000000b0260401c5b600882161561507d57680100000000000000060260401c5b600482161561509557680100000000000000030260401c5b60028216156150ad57680100000000000000010260401c5b60018216156150c557680100000000000000010260401c5b670de0b6b3a76400000260409190911c60bf031c90565b6000815180845260005b81811015615102576020818501810151868301820152016150e6565b506000602082860101526020601f19601f83011685010191505092915050565b602081526000610d5060208301846150dc565b80356001600160a01b038116811461514c57600080fd5b919050565b6000606082840312156147d857600080fd5b60008083601f84011261517557600080fd5b50813567ffffffffffffffff81111561518d57600080fd5b6020830191508360208285010111156151a557600080fd5b9250929050565b600080600080600080600080610120898b0312156151c957600080fd5b6151d289615135565b9750602089013596506040890135955060608901359450608089013593506151fd8a60a08b01615151565b925061010089013567ffffffffffffffff81111561521a57600080fd5b6152268b828c01615163565b999c989b5096995094979396929594505050565b6000806040838503121561524d57600080fd5b61525683615135565b946020939093013593505050565b60008060008060008060c0878903121561527d57600080fd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b6000602082840312156152b957600080fd5b610d5082615135565b6060808252845190820181905260009060208601906080840190835b818110156152fc5783518352602093840193909201916001016152de565b50508381036020808601919091528651808352918101925086019060005b818110156153415782516001600160a01b031684526020938401939092019160010161531a565b505050604092909201929092529392505050565b60008060006060848603121561536a57600080fd5b61537384615135565b925061538160208501615135565b929592945050506040919091013590565b600080600080600080600080610120898b0312156153af57600080fd5b6153b889615135565b97506020890135965060408901359550606089013594506153db60808a01615135565b93506151fd8a60a08b01615151565b60008060008060008060008060006101408a8c03121561540957600080fd5b6154128a615135565b985061542060208b01615135565b975060408a0135965060608a0135955060808a0135945061544360a08b01615135565b93506154528b60c08c01615151565b92506101208a013567ffffffffffffffff81111561546f57600080fd5b61547b8c828d01615163565b915080935050809150509295985092959850929598565b600080600080600080600080610120898b0312156154af57600080fd5b6154b889615135565b9750602089013596506154cd60408a01615135565b955060608901359450608089013593506151fd8a60a08b01615151565b6000602082840312156154fc57600080fd5b5035919050565b60008083601f84011261551557600080fd5b50813567ffffffffffffffff81111561552d57600080fd5b6020830191508360208260051b85010111156151a557600080fd5b60008060008060008060008060006101208a8c03121561556757600080fd5b6155708a615135565b985060208a013567ffffffffffffffff81111561558c57600080fd5b6155988c828d01615503565b90995097505060408a0135955060608a0135945060808a013593506155c08b60a08c01615151565b92506101008a013567ffffffffffffffff81111561546f57600080fd5b60008060008060008060008060006101408a8c0312156155fc57600080fd5b6156058a615135565b985061561360208b01615135565b975060408a0135965060608a0135955060808a0135945060a08a013593506154528b60c08c01615151565b600080600080600080600080610100898b03121561565b57600080fd5b883567ffffffffffffffff81111561567257600080fd5b61567e8b828c01615503565b9099509750506020890135955060408901359450606089013593506156a68a60808b01615151565b925060e089013567ffffffffffffffff81111561521a57600080fd5b60008060008060008060a087890312156156db57600080fd5b86359550602087013594506040870135935060608701359250608087013567ffffffffffffffff81111561570e57600080fd5b61571a89828a01615163565b979a9699509497509295939492505050565b6000806040838503121561573f57600080fd5b50508035926020909101359150565b6000806040838503121561576157600080fd5b61576a83615135565b915061577860208401615135565b90509250929050565b600181811c9082168061579557607f821691505b6020821081036147d857634e487b7160e01b600052602260045260246000fd5b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156157f4576157f46157b5565b604052919050565b60ff81168114611a7357600080fd5b6000606082840312801561581e57600080fd5b506040516060810167ffffffffffffffff81118282101715615842576158426157b5565b6040528235615850816157fc565b8152602083810135908201526040928301359281019290925250919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082028115828204841417610b8357610b83615885565b634e487b7160e01b600052601260045260246000fd5b6000826158e557634e487b7160e01b600052601260045260246000fd5b500490565b6000600182016158fc576158fc615885565b5060010190565b60006020828403121561591557600080fd5b8151610d50816157fc565b80820180821115610b8357610b83615885565b60ff8181168382160190811115610b8357610b83615885565b83815282602082015260606040820152600061596b60608301846150dc565b95945050505050565b60006020828403121561598657600080fd5b5051919050565b805169ffffffffffffffffffff8116811461514c57600080fd5b600080600080600060a086880312156159bf57600080fd5b6159c88661598d565b602087015160408801516060890151929750909550935091506159ed6080870161598d565b90509295509295909350565b60008060408385031215615a0c57600080fd5b8251602084015190925067ffffffffffffffff811115615a2b57600080fd5b8301601f81018513615a3c57600080fd5b805167ffffffffffffffff811115615a5657615a566157b5565b8060051b615a66602082016157cb565b91825260208184018101929081019088841115615a8257600080fd5b6020850194505b83851015615aa857845180835260209586019590935090910190615a89565b80955050505050509250929050565b60ff8281168282160390811115610b8357610b83615885565b6001815b6001841115615b0b57808504811115615aef57615aef615885565b6001841615615afd57908102905b60019390931c928002615ad4565b935093915050565b600082615b2257506001610b83565b81615b2f57506000610b83565b8160018114615b455760028114615b4f57615b6b565b6001915050610b83565b60ff841115615b6057615b60615885565b50506001821b610b83565b5060208310610133831016604e8410600b8410161715615b8e575081810a610b83565b615b9b6000198484615ad0565b8060001904821115615baf57615baf615885565b029392505050565b6000610d5060ff841683615b13565b81810381811115610b8357610b83615885565b8151600090829060208501835b82811015615c04578151845260209384019390910190600101615be6565b509195945050505050565b634e487b7160e01b600052602160045260246000fdfea2646970667358221220934a1d9a423aa150a2aba40cc46c732a188ea43bba4b7c2983ce68bf5989642464736f6c634300081c0033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab6200000000000000000000000000000000000000000000000000000000000000c000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000180000000000000000000000000a372e7f8ba1f0377667c8c52fea2bc3e271a0e680000000000000000000000000000000000000000000000000000000000000002000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62000000000000000000000000b24e3035d1fcbc0e43cf3143c3fd92e53df2009b00000000000000000000000000000000000000000000000000000000000000020000000000000000000000007bdbdb772f4a073badd676a567c6ed82049a8eee000000000000000000000000f6630799b5387e0e9ace92a5e82673021781b44000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000e100000000000000000000000000000000000000000000000000000000000000e10

-----Decoded View---------------
Arg [0] : theSigner (address): 0x08938a61BA9523298dbCAceE0cda5B371FB7f1F8
Arg [1] : theWrapper (address): 0xEE7D8BCFb72bC1880D0Cf19822eB0A2e6577aB62
Arg [2] : tokens (address[]): 0xEE7D8BCFb72bC1880D0Cf19822eB0A2e6577aB62,0xb24e3035d1FCBC0E43CF3143C3Fd92E53df2009b
Arg [3] : _oracles (address[]): 0x7BdBDB772f4a073BadD676A567C6ED82049a8eEE,0xF6630799b5387e0E9ACe92a5E82673021781B440
Arg [4] : minTimeTolerances (uint256[]): 3600,3600
Arg [5] : initialOwner (address): 0xA372e7f8bA1F0377667C8c52FEA2BC3E271a0e68

-----Encoded View---------------
15 Constructor Arguments found :
Arg [0] : 00000000000000000000000008938a61ba9523298dbcacee0cda5b371fb7f1f8
Arg [1] : 000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62
Arg [2] : 00000000000000000000000000000000000000000000000000000000000000c0
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000120
Arg [4] : 0000000000000000000000000000000000000000000000000000000000000180
Arg [5] : 000000000000000000000000a372e7f8ba1f0377667c8c52fea2bc3e271a0e68
Arg [6] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [7] : 000000000000000000000000ee7d8bcfb72bc1880d0cf19822eb0a2e6577ab62
Arg [8] : 000000000000000000000000b24e3035d1fcbc0e43cf3143c3fd92e53df2009b
Arg [9] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [10] : 0000000000000000000000007bdbdb772f4a073badd676a567c6ed82049a8eee
Arg [11] : 000000000000000000000000f6630799b5387e0e9ace92a5e82673021781b440
Arg [12] : 0000000000000000000000000000000000000000000000000000000000000002
Arg [13] : 0000000000000000000000000000000000000000000000000000000000000e10
Arg [14] : 0000000000000000000000000000000000000000000000000000000000000e10


Block Transaction Difficulty 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
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

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.