ETH Price: $3,587.90 (-2.64%)

Contract

0xBA510f10E3095B83a0F33aa9ad2544E22570a87C
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

Latest 25 internal transactions (View All)

Advanced mode:
Parent Transaction Hash Block From To
212966012024-11-29 23:24:112 days ago1732922651
0xBA510f10...22570a87C
0 ETH
211333722024-11-07 4:25:3525 days ago1730953535
0xBA510f10...22570a87C
0 ETH
211191422024-11-05 4:44:3527 days ago1730781875
0xBA510f10...22570a87C
0 ETH
209991562024-10-19 10:55:5944 days ago1729335359
0xBA510f10...22570a87C
0 ETH
209467742024-10-12 3:14:3551 days ago1728702875
0xBA510f10...22570a87C
0 ETH
209461072024-10-12 0:59:3551 days ago1728694775
0xBA510f10...22570a87C
0 ETH
209459622024-10-12 0:30:2351 days ago1728693023
0xBA510f10...22570a87C
0 ETH
209459622024-10-12 0:30:2351 days ago1728693023
0xBA510f10...22570a87C
0 ETH
209459482024-10-12 0:27:2351 days ago1728692843
0xBA510f10...22570a87C
0 ETH
209459482024-10-12 0:27:2351 days ago1728692843
0xBA510f10...22570a87C
0 ETH
209459322024-10-12 0:24:1151 days ago1728692651
0xBA510f10...22570a87C
0 ETH
209459312024-10-12 0:23:5951 days ago1728692639
0xBA510f10...22570a87C
0 ETH
209459312024-10-12 0:23:5951 days ago1728692639
0xBA510f10...22570a87C
0 ETH
209459262024-10-12 0:22:5951 days ago1728692579
0xBA510f10...22570a87C
0 ETH
209459252024-10-12 0:22:4751 days ago1728692567
0xBA510f10...22570a87C
0 ETH
209459252024-10-12 0:22:4751 days ago1728692567
0xBA510f10...22570a87C
0 ETH
209459122024-10-12 0:20:1151 days ago1728692411
0xBA510f10...22570a87C
0 ETH
209459112024-10-12 0:19:5951 days ago1728692399
0xBA510f10...22570a87C
0 ETH
209458542024-10-12 0:08:3551 days ago1728691715
0xBA510f10...22570a87C
0 ETH
209458532024-10-12 0:08:2351 days ago1728691703
0xBA510f10...22570a87C
0 ETH
209458532024-10-12 0:08:2351 days ago1728691703
0xBA510f10...22570a87C
0 ETH
209257922024-10-09 4:58:1154 days ago1728449891
0xBA510f10...22570a87C
0 ETH
209257062024-10-09 4:40:5954 days ago1728448859
0xBA510f10...22570a87C
0 ETH
209256882024-10-09 4:37:2354 days ago1728448643
0xBA510f10...22570a87C
0 ETH
209256852024-10-09 4:36:4754 days ago1728448607
0xBA510f10...22570a87C
0 ETH
View All Internal Transactions
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MultiFlowPump

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 1000 runs

Other Settings:
default evmVersion
File 1 of 49 : MultiFlowPump.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IPump} from "src/interfaces/pumps/IPump.sol";
import {IMultiFlowPumpErrors} from "src/interfaces/pumps/IMultiFlowPumpErrors.sol";
import {IWell} from "src/interfaces/IWell.sol";
import {IInstantaneousPump} from "src/interfaces/pumps/IInstantaneousPump.sol";
import {ICumulativePump} from "src/interfaces/pumps/ICumulativePump.sol";
import {ABDKMathQuad} from "src/libraries/ABDKMathQuad.sol";
import {LibBytes16} from "src/libraries/LibBytes16.sol";
import {LibLastReserveBytes} from "src/libraries/LibLastReserveBytes.sol";

/**
 * @title MultiFlowPump
 * @author Publius
 * @notice Stores a geometric EMA and cumulative geometric SMA for each reserve.
 * @dev A Pump designed for use in Beanstalk with 2 tokens.
 *
 * This Pump has 3 main features:
 *  1. Multi-block MEV resistence reserves
 *  2. MEV-resistant Geometric EMA intended for instantaneous reserve queries
 *  3. MEV-resistant Cumulative Geometric intended for SMA reserve queries
 *
 * Note: If an `update` call is made with a reserve of 0, the Geometric mean oracles will be set to 0.
 * Each Well is responsible for ensuring that an `update` call cannot be made with a reserve of 0.
 */
contract MultiFlowPump is IPump, IMultiFlowPumpErrors, IInstantaneousPump, ICumulativePump {
    using LibLastReserveBytes for bytes32;
    using LibBytes16 for bytes32;
    using ABDKMathQuad for bytes16;
    using ABDKMathQuad for uint256;

    bytes16 public immutable LOG_MAX_INCREASE;
    bytes16 public immutable LOG_MAX_DECREASE;
    bytes16 public immutable ALPHA;
    uint256 public immutable CAP_INTERVAL;

    struct PumpState {
        uint40 lastTimestamp;
        bytes16[] lastReserves;
        bytes16[] emaReserves;
        bytes16[] cumulativeReserves;
    }

    /**
     * @param _maxPercentIncrease The maximum percent increase allowed in a single block. Must be in quadruple precision format (See {ABDKMathQuad}).
     * @param _maxPercentDecrease The maximum percent decrease allowed in a single block. Must be in quadruple precision format (See {ABDKMathQuad}).
     * @param _capInterval How often to increase the magnitude of the cap on the change in reserve in seconds.
     * @param _alpha The geometric EMA constant. Must be in quadruple precision format (See {ABDKMathQuad}).
     *
     * @dev The Pump will not flow and should definitely be considered invalid if the following constraints are not met:
     * - 0% < _maxPercentIncrease
     * - 0% < _maxPercentDecrease <= 100%
     * - 0 < ALPHA <= 1
     * - _capInterval > 0
     * The above constraints are not checked in the constructor for gas efficiency reasons.
     * When evaluating the manipulation resistance of an instance of a Multi Flow Pump for use as an oracle, stricter
     * constraints should be used.
     */
    constructor(bytes16 _maxPercentIncrease, bytes16 _maxPercentDecrease, uint256 _capInterval, bytes16 _alpha) {
        LOG_MAX_INCREASE = ABDKMathQuad.ONE.add(_maxPercentIncrease).log_2();
        LOG_MAX_DECREASE = ABDKMathQuad.ONE.sub(_maxPercentDecrease).log_2();
        CAP_INTERVAL = _capInterval;
        ALPHA = _alpha;
    }

    //////////////////// PUMP ////////////////////

    function update(uint256[] calldata reserves, bytes calldata) external {
        uint256 numberOfReserves = reserves.length;
        PumpState memory pumpState;

        // All reserves are stored starting at the msg.sender address slot in storage.
        bytes32 slot = _getSlotForAddress(msg.sender);

        // Read: Last Timestamp & Last Reserves
        (, pumpState.lastTimestamp, pumpState.lastReserves) = slot.readLastReserves();

        // If the last timestamp is 0, then the pump has never been used before.
        if (pumpState.lastTimestamp == 0) {
            _init(slot, uint40(block.timestamp), reserves);
            return;
        }

        bytes16 alphaN;
        bytes16 deltaTimestampBytes;
        bytes16 capExponent;
        // Isolate in brackets to prevent stack too deep errors
        {
            uint256 deltaTimestamp = _getDeltaTimestamp(pumpState.lastTimestamp);
            // If no time has passed, don't update the pump reserves.
            if (deltaTimestamp == 0) return;
            alphaN = ALPHA.powu(deltaTimestamp);
            deltaTimestampBytes = deltaTimestamp.fromUInt();
            // Round up in case CAP_INTERVAL > block time to guarantee capExponent > 0 if time has passed since the last update.
            capExponent = ((deltaTimestamp - 1) / CAP_INTERVAL + 1).fromUInt();
        }

        // Read: Cumulative & EMA Reserves
        // Start at the slot after `pumpState.lastReserves`
        uint256 numSlots = _getSlotsOffset(numberOfReserves);
        assembly {
            slot := add(slot, numSlots)
        }
        pumpState.emaReserves = slot.readBytes16(numberOfReserves);
        assembly {
            slot := add(slot, numSlots)
        }
        pumpState.cumulativeReserves = slot.readBytes16(numberOfReserves);

        uint256 _reserve;
        for (uint256 i; i < numberOfReserves; ++i) {
            // Use a minimum of 1 for reserve. Geometric means will be set to 0 if a reserve is 0.
            _reserve = reserves[i];
            pumpState.lastReserves[i] =
                _capReserve(pumpState.lastReserves[i], (_reserve > 0 ? _reserve : 1).fromUIntToLog2(), capExponent);
            pumpState.emaReserves[i] =
                pumpState.lastReserves[i].mul((ABDKMathQuad.ONE.sub(alphaN))).add(pumpState.emaReserves[i].mul(alphaN));
            pumpState.cumulativeReserves[i] =
                pumpState.cumulativeReserves[i].add(pumpState.lastReserves[i].mul(deltaTimestampBytes));
        }

        // Write: Cumulative & EMA Reserves
        // Order matters: work backwards to avoid using a new memory var to count up
        slot.storeBytes16(pumpState.cumulativeReserves);
        assembly {
            slot := sub(slot, numSlots)
        }
        slot.storeBytes16(pumpState.emaReserves);
        assembly {
            slot := sub(slot, numSlots)
        }

        // Write: Last Timestamp & Last Reserves
        slot.storeLastReserves(uint40(block.timestamp), pumpState.lastReserves);
    }

    /**
     * @dev On first update for a particular Well, initialize oracle with
     * reserves data.
     */
    function _init(bytes32 slot, uint40 lastTimestamp, uint256[] memory reserves) internal {
        uint256 numberOfReserves = reserves.length;
        bytes16[] memory byteReserves = new bytes16[](numberOfReserves);

        // Skip {_capReserve} since we have no prior reference

        for (uint256 i; i < numberOfReserves; ++i) {
            uint256 _reserve = reserves[i];
            if (_reserve == 0) return;
            byteReserves[i] = _reserve.fromUIntToLog2();
        }

        // Write: Last Timestamp & Last Reserves
        slot.storeLastReserves(lastTimestamp, byteReserves);

        // Write: EMA Reserves
        // Start at the slot after `byteReserves`
        uint256 numSlots = _getSlotsOffset(numberOfReserves);
        assembly {
            slot := add(slot, numSlots)
        }
        slot.storeBytes16(byteReserves); // EMA Reserves
    }

    //////////////////// LAST RESERVES ////////////////////

    /**
     * @dev Reads the last capped reserves from the Pump from storage.
     */
    function readLastCappedReserves(address well) public view returns (uint256[] memory lastCappedReserves) {
        (uint8 numberOfReserves,, bytes16[] memory lastReserves) = _getSlotForAddress(well).readLastReserves();
        if (numberOfReserves == 0) {
            revert NotInitialized();
        }
        lastCappedReserves = new uint256[](numberOfReserves);
        for (uint256 i; i < numberOfReserves; ++i) {
            lastCappedReserves[i] = lastReserves[i].pow_2ToUInt();
        }
    }

    /**
     * @dev Reads the capped reserves from the Pump updated to the current block using the current reserves of `well`.
     */
    function readCappedReserves(address well) external view returns (uint256[] memory cappedReserves) {
        bytes32 slot = _getSlotForAddress(well);
        uint256[] memory currentReserves = IWell(well).getReserves();
        (uint8 numberOfReserves, uint40 lastTimestamp, bytes16[] memory lastReserves) = slot.readLastReserves();
        if (numberOfReserves == 0) {
            revert NotInitialized();
        }
        uint256 deltaTimestamp = _getDeltaTimestamp(lastTimestamp);
        cappedReserves = new uint256[](numberOfReserves);
        if (deltaTimestamp == 0) {
            for (uint256 i; i < numberOfReserves; ++i) {
                cappedReserves[i] = lastReserves[i].pow_2ToUInt();
            }
            return cappedReserves;
        }

        bytes16 capExponent = ((deltaTimestamp - 1) / CAP_INTERVAL + 1).fromUInt();

        for (uint256 i; i < numberOfReserves; ++i) {
            cappedReserves[i] =
                _capReserve(lastReserves[i], currentReserves[i].fromUIntToLog2(), capExponent).pow_2ToUInt();
        }
    }

    /**
     * @dev Adds a cap to the reserve value to prevent extreme changes.
     *
     *  Linear space:
     *     max reserve = (last reserve) * ((1 + MAX_PERCENT_CHANGE_PER_BLOCK) ^ capExponent)
     *
     *  Log space:
     *     log2(max reserve) = log2(last reserve) + capExponent*log2(1 + MAX_PERCENT_CHANGE_PER_BLOCK)
     *
     *     `bytes16 lastReserve`      <- log2(last reserve)
     *     `bytes16 capExponent`      <- cap exponent
     *     `bytes16 LOG_MAX_INCREASE` <- log2(1 + MAX_PERCENT_CHANGE_PER_BLOCK)
     *
     *     ∴ `maxReserve = lastReserve + capExponent*LOG_MAX_INCREASE`
     *
     */
    function _capReserve(
        bytes16 lastReserve,
        bytes16 reserve,
        bytes16 capExponent
    ) internal view returns (bytes16 cappedReserve) {
        // Reserve decreasing (lastReserve > reserve)
        if (lastReserve.cmp(reserve) == 1) {
            bytes16 minReserve = lastReserve.add(capExponent.mul(LOG_MAX_DECREASE));
            // if reserve < minimum reserve, set reserve to minimum reserve
            if (minReserve.cmp(reserve) == 1) reserve = minReserve;
        }
        // Reserve increasing or staying the same (lastReserve <= reserve)
        else {
            bytes16 maxReserve = lastReserve.add(capExponent.mul(LOG_MAX_INCREASE));
            // If reserve > maximum reserve, set reserve to maximum reserve
            if (reserve.cmp(maxReserve) == 1) reserve = maxReserve;
        }
        cappedReserve = reserve;
    }

    //////////////////// EMA RESERVES ////////////////////

    function readLastInstantaneousReserves(address well) external view returns (uint256[] memory emaReserves) {
        bytes32 slot = _getSlotForAddress(well);
        uint8 numberOfReserves = slot.readNumberOfReserves();
        if (numberOfReserves == 0) {
            revert NotInitialized();
        }
        uint256 offset = _getSlotsOffset(numberOfReserves);
        assembly {
            slot := add(slot, offset)
        }
        bytes16[] memory byteReserves = slot.readBytes16(numberOfReserves);
        emaReserves = new uint256[](numberOfReserves);
        for (uint256 i; i < numberOfReserves; ++i) {
            emaReserves[i] = byteReserves[i].pow_2ToUInt();
        }
    }

    function readInstantaneousReserves(
        address well,
        bytes memory
    ) external view returns (uint256[] memory emaReserves) {
        bytes32 slot = _getSlotForAddress(well);
        uint256[] memory reserves = IWell(well).getReserves();
        (uint8 numberOfReserves, uint40 lastTimestamp, bytes16[] memory lastReserves) = slot.readLastReserves();
        if (numberOfReserves == 0) {
            revert NotInitialized();
        }
        uint256 offset = _getSlotsOffset(numberOfReserves);
        assembly {
            slot := add(slot, offset)
        }
        bytes16[] memory lastEmaReserves = slot.readBytes16(numberOfReserves);
        uint256 deltaTimestamp = _getDeltaTimestamp(lastTimestamp);
        emaReserves = new uint256[](numberOfReserves);
        // If no time has passed, return last EMA reserves.
        if (deltaTimestamp == 0) {
            for (uint256 i; i < numberOfReserves; ++i) {
                emaReserves[i] = lastEmaReserves[i].pow_2ToUInt();
            }
            return emaReserves;
        }
        bytes16 capExponent = ((deltaTimestamp - 1) / CAP_INTERVAL + 1).fromUInt();
        bytes16 alphaN = ALPHA.powu(deltaTimestamp);
        for (uint256 i; i < numberOfReserves; ++i) {
            lastReserves[i] = _capReserve(lastReserves[i], reserves[i].fromUIntToLog2(), capExponent);
            emaReserves[i] =
                lastReserves[i].mul((ABDKMathQuad.ONE.sub(alphaN))).add(lastEmaReserves[i].mul(alphaN)).pow_2ToUInt();
        }
    }

    //////////////////// CUMULATIVE RESERVES ////////////////////

    /**
     * @notice Read the latest cumulative reserves of `well`.
     */
    function readLastCumulativeReserves(address well) external view returns (bytes16[] memory cumulativeReserves) {
        bytes32 slot = _getSlotForAddress(well);
        uint8 numberOfReserves = slot.readNumberOfReserves();
        if (numberOfReserves == 0) {
            revert NotInitialized();
        }
        uint256 offset = _getSlotsOffset(numberOfReserves) << 1;
        assembly {
            slot := add(slot, offset)
        }
        cumulativeReserves = slot.readBytes16(numberOfReserves);
    }

    function readCumulativeReserves(
        address well,
        bytes memory
    ) external view returns (bytes memory cumulativeReserves) {
        bytes16[] memory byteCumulativeReserves = _readCumulativeReserves(well);
        cumulativeReserves = abi.encode(byteCumulativeReserves);
    }

    function _readCumulativeReserves(address well) internal view returns (bytes16[] memory cumulativeReserves) {
        bytes32 slot = _getSlotForAddress(well);
        uint256[] memory reserves = IWell(well).getReserves();
        (uint8 numberOfReserves, uint40 lastTimestamp, bytes16[] memory lastReserves) = slot.readLastReserves();
        if (numberOfReserves == 0) {
            revert NotInitialized();
        }
        uint256 offset = _getSlotsOffset(numberOfReserves) << 1;
        assembly {
            slot := add(slot, offset)
        }
        cumulativeReserves = slot.readBytes16(numberOfReserves);
        uint256 deltaTimestamp = _getDeltaTimestamp(lastTimestamp);
        // If no time has passed, return last cumulative reserves.
        if (deltaTimestamp == 0) {
            return cumulativeReserves;
        }
        bytes16 deltaTimestampBytes = deltaTimestamp.fromUInt();
        bytes16 capExponent = ((deltaTimestamp - 1) / CAP_INTERVAL + 1).fromUInt();
        // Currently, there is so support for overflow.
        for (uint256 i; i < cumulativeReserves.length; ++i) {
            lastReserves[i] = _capReserve(lastReserves[i], reserves[i].fromUIntToLog2(), capExponent);
            cumulativeReserves[i] = cumulativeReserves[i].add(lastReserves[i].mul(deltaTimestampBytes));
        }
    }

    function readTwaReserves(
        address well,
        bytes calldata startCumulativeReserves,
        uint256 startTimestamp,
        bytes memory
    ) public view returns (uint256[] memory twaReserves, bytes memory cumulativeReserves) {
        bytes16[] memory byteCumulativeReserves = _readCumulativeReserves(well);
        bytes16[] memory byteStartCumulativeReserves = abi.decode(startCumulativeReserves, (bytes16[]));
        twaReserves = new uint256[](byteCumulativeReserves.length);

        // Overflow is desired on `startTimestamp`, so SafeCast is not used.
        bytes16 deltaTimestamp = _getDeltaTimestamp(uint40(startTimestamp)).fromUInt();
        if (deltaTimestamp == bytes16(0)) {
            revert NoTimePassed();
        }
        for (uint256 i; i < byteCumulativeReserves.length; ++i) {
            // Currently, there is no support for overflow.
            twaReserves[i] =
                (byteCumulativeReserves[i].sub(byteStartCumulativeReserves[i])).div(deltaTimestamp).pow_2ToUInt();
        }
        cumulativeReserves = abi.encode(byteCumulativeReserves);
    }

    //////////////////// HELPERS ////////////////////

    /**
     * @dev Convert an `address` into a `bytes32` by zero padding the right 12 bytes.
     */
    function _getSlotForAddress(address addressValue) internal pure returns (bytes32 _slot) {
        _slot = bytes32(bytes20(addressValue)); // Because right padded, no collision on adjacent
    }

    /**
     * @dev Get the starting byte of the slot that contains the `n`th element of an array.
     */
    function _getSlotsOffset(uint256 numberOfReserves) internal pure returns (uint256 _slotsOffset) {
        _slotsOffset = ((numberOfReserves - 1) / 2 + 1) << 5;
    }

    /**
     * @dev Get the delta between the current and provided timestamp as a `uint256`.
     */
    function _getDeltaTimestamp(uint40 lastTimestamp) internal view returns (uint256 _deltaTimestamp) {
        return uint256(uint40(block.timestamp) - lastTimestamp);
    }
}

File 2 of 49 : IERC5267Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.0;

interface IERC5267Upgradeable {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}

File 3 of 49 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils//AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

File 4 of 49 : ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "../proxy/utils//Initializable.sol";

/**
 * @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 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 ReentrancyGuardUpgradeable is Initializable {
    // 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;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 5 of 49 : ERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils//ContextUpgradeable.sol";
import "../../proxy/utils//Initializable.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}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * 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 ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
    mapping(address => uint256) private _balances;

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

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC20_init_unchained(name_, symbol_);
    }

    function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

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

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override 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 override returns (uint8) {
        return 18;
    }

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

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override 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 `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

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

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` 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 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * 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 `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `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.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` 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.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[45] private __gap;
}

File 6 of 49 : ERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./IERC20PermitUpgradeable.sol";
import "../ERC20Upgradeable.sol";
import "../../../utils//cryptography/ECDSAUpgradeable.sol";
import "../../../utils//cryptography/EIP712Upgradeable.sol";
import "../../../utils//CountersUpgradeable.sol";
import "../../../proxy/utils//Initializable.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 *
 * @custom:storage-size 51
 */
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
    using CountersUpgradeable for CountersUpgradeable.Counter;

    mapping(address => CountersUpgradeable.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    function __ERC20Permit_init(string memory name) internal onlyInitializing {
        __EIP712_init_unchained(name, "1");
    }

    function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSAUpgradeable.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        CountersUpgradeable.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 7 of 49 : IERC20MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20Upgradeable.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
    /**
     * @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 8 of 49 : IERC20PermitUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20PermitUpgradeable {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 9 of 49 : IERC20Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Upgradeable {
    /**
     * @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 amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}

File 10 of 49 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 11 of 49 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils//Initializable.sol";

/**
 * @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 ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 12 of 49 : CountersUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library CountersUpgradeable {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 13 of 49 : ECDSAUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../StringsUpgradeable.sol";

/**
 * @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 ECDSAUpgradeable {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode 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 {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]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        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.
            /// @solidity memory-safe-assembly
            assembly {
                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);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        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[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        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.
     *
     * _Available since v4.2._
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
        // 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);
        }

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

        return (signer, RecoverError.NoError);
    }

    /**
     * @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) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

File 14 of 49 : EIP712Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.8;

import "./ECDSAUpgradeable.sol";
import "../../interfaces/IERC5267Upgradeable.sol";
import "../../proxy/utils//Initializable.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * _Available since v3.4._
 *
 * @custom:storage-size 52
 */
abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable {
    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    /// @custom:oz-renamed-from _HASHED_NAME
    bytes32 private _hashedName;
    /// @custom:oz-renamed-from _HASHED_VERSION
    bytes32 private _hashedVersion;

    string private _name;
    string private _version;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
        __EIP712_init_unchained(name, version);
    }

    function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
        _name = name;
        _version = version;

        // Reset prior values in storage if upgrading
        _hashedName = 0;
        _hashedVersion = 0;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        return _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {EIP-5267}.
     *
     * _Available since v4.9._
     */
    function eip712Domain()
        public
        view
        virtual
        override
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
        // and the EIP712 domain is not reliable, as it will be missing name and version.
        require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized");

        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Name() internal virtual view returns (string memory) {
        return _name;
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
     * are a concern.
     */
    function _EIP712Version() internal virtual view returns (string memory) {
        return _version;
    }

    /**
     * @dev The hash of the name parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
     */
    function _EIP712NameHash() internal view returns (bytes32) {
        string memory name = _EIP712Name();
        if (bytes(name).length > 0) {
            return keccak256(bytes(name));
        } else {
            // If the name is empty, the contract may have been upgraded without initializing the new storage.
            // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
            bytes32 hashedName = _hashedName;
            if (hashedName != 0) {
                return hashedName;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev The hash of the version parameter for the EIP712 domain.
     *
     * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
     */
    function _EIP712VersionHash() internal view returns (bytes32) {
        string memory version = _EIP712Version();
        if (bytes(version).length > 0) {
            return keccak256(bytes(version));
        } else {
            // If the version is empty, the contract may have been upgraded without initializing the new storage.
            // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
            bytes32 hashedVersion = _hashedVersion;
            if (hashedVersion != 0) {
                return hashedVersion;
            } else {
                return keccak256("");
            }
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[48] private __gap;
}

File 15 of 49 : MathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library MathUpgradeable {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

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

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

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

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

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

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

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

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

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

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

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

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

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

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

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

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

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

File 16 of 49 : SignedMathUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMathUpgradeable {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return 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 {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

File 17 of 49 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

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

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.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, MathUpgradeable.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) {
        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] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        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 Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

File 18 of 49 : ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

    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
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // 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 19 of 49 : IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 20 of 49 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

    /**
     * @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` 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 amount) external returns (bool);
}

File 21 of 49 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils//Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 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 {
    using Address for address;

    /**
     * @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.encodeWithSelector(token.transfer.selector, 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.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 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.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @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.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

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

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @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).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @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 silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

File 22 of 49 : Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 23 of 49 : Aquifer.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {ReentrancyGuard} from "lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol";

import {IAquifer} from "src/interfaces/IAquifer.sol";
import {IWell} from "src/Well.sol";
import {LibClone} from "src/libraries/LibClone.sol";

/**
 * @title Aquifer
 * @author Publius, Silo Chad, Brean
 * @notice Aquifer is a permissionless Well registry and factory.
 * @dev Aquifer deploys Wells by cloning a pre-deployed Well implementation.
 */
contract Aquifer is IAquifer, ReentrancyGuard {
    using LibClone for address;

    // A mapping of Well address to the Well implementation addresses
    // Mapping gets set on Well deployment
    mapping(address => address) public wellImplementation;

    constructor() ReentrancyGuard() {}

    /**
     * @dev
     * Use `salt == 0` to deploy a new Well with `create`
     * Use `salt > 0` to deploy a new Well with `create2`
     */
    function boreWell(
        address implementation,
        bytes calldata immutableData,
        bytes calldata initFunctionCall,
        bytes32 salt
    ) external nonReentrant returns (address well) {
        if (immutableData.length > 0) {
            if (salt != bytes32(0)) {
                // Encode the salt with the `msg.sender` address to prevent frontrunning attack
                salt = keccak256(abi.encode(msg.sender, salt));
                well = implementation.cloneDeterministic(immutableData, salt);
            } else {
                well = implementation.clone(immutableData);
            }
        } else {
            if (salt != bytes32(0)) {
                // Encode the salt with the `msg.sender` address to prevent frontrunning attack
                salt = keccak256(abi.encode(msg.sender, salt));
                well = implementation.cloneDeterministic(salt);
            } else {
                well = implementation.clone();
            }
        }

        if (initFunctionCall.length > 0) {
            (bool success, bytes memory returnData) = well.call(initFunctionCall);
            if (!success) {
                // Next 5 lines are based on https://ethereum.stackexchange.com/a/83577
                if (returnData.length < 68) revert InitFailed("");
                assembly {
                    returnData := add(returnData, 0x04)
                }
                revert InitFailed(abi.decode(returnData, (string)));
            }
        }

        if (!IWell(well).isInitialized()) {
            revert WellNotInitialized();
        }

        // The Aquifer address MUST be set, either (a) via immutable data during cloning,
        // or (b) as a storage variable during an init function call. In either case,
        // the address MUST match the address of the Aquifer that performed deployment.
        if (IWell(well).aquifer() != address(this)) {
            revert InvalidConfig();
        }

        // Save implementation
        wellImplementation[well] = implementation;

        emit BoreWell(
            well,
            implementation,
            IWell(well).tokens(),
            IWell(well).wellFunction(),
            IWell(well).pumps(),
            IWell(well).wellData()
        );
    }

    function predictWellAddress(
        address implementation,
        bytes calldata immutableData,
        bytes32 salt
    ) external view returns (address well) {
        // Aquifer doesn't support using a salt of 0 to deploy a Well at a deterministic address.
        if (salt == bytes32(0)) {
            revert InvalidSalt();
        }
        salt = keccak256(abi.encode(msg.sender, salt));
        if (immutableData.length > 0) {
            well = implementation.predictDeterministicAddress(immutableData, salt, address(this));
        } else {
            well = implementation.predictDeterministicAddress(salt, address(this));
        }
    }
}

File 24 of 49 : ConstantProduct.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IBeanstalkWellFunction} from "src/interfaces/IBeanstalkWellFunction.sol";
import {ProportionalLPToken} from "src/functions/ProportionalLPToken.sol";
import {LibMath} from "src/libraries/LibMath.sol";

/**
 * @title ConstantProduct
 * @author Publius
 * @notice Constant product pricing function for Wells with N tokens.
 * @dev Constant Product Wells use the formula:
 *  `π(b_i) = (s / n)^n`
 *
 * Where:
 *  `s` is the supply of LP tokens
 *  `b_i` is the reserve at index `i`
 *  `n` is the number of tokens in the Well
 *
 * Note: Using too many tokens in a Constant Product Well may result in overflow.
 */
contract ConstantProduct is ProportionalLPToken, IBeanstalkWellFunction {
    using LibMath for uint256;

    /// @dev `s = π(b_i)^(1/n) * n`
    function calcLpTokenSupply(
        uint256[] calldata reserves,
        bytes calldata
    ) external pure override returns (uint256 lpTokenSupply) {
        lpTokenSupply = _prodX(reserves).nthRoot(reserves.length) * reserves.length;
    }

    /// @dev `b_j = (s / n)^n / π_{i!=j}(b_i)`
    function calcReserve(
        uint256[] calldata reserves,
        uint256 j,
        uint256 lpTokenSupply,
        bytes calldata
    ) external pure override returns (uint256 reserve) {
        uint256 n = reserves.length;
        reserve = (lpTokenSupply / n) ** n;
        for (uint256 i; i < n; ++i) {
            if (i != j) reserve = reserve / reserves[i];
        }
    }

    function name() external pure override returns (string memory) {
        return "Constant Product";
    }

    function symbol() external pure override returns (string memory) {
        return "CP";
    }

    /// @dev calculate the mathematical product of an array of uint256[]
    function _prodX(uint256[] memory xs) private pure returns (uint256 pX) {
        pX = xs[0];
        uint256 length = xs.length;
        for (uint256 i = 1; i < length; ++i) {
            pX = pX * xs[i];
        }
    }

    /// @dev `b_j = (π(b_i) * r_j / (Σ_{i != j}(r_i)/(n-1)))^(1/n)`
    function calcReserveAtRatioSwap(
        uint256[] calldata reserves,
        uint256 j,
        uint256[] calldata ratios,
        bytes calldata
    ) external pure override returns (uint256 reserve) {
        uint256 sumRatio = 0;
        for (uint256 i; i < reserves.length; ++i) {
            if (i != j) sumRatio += ratios[i];
        }
        sumRatio /= reserves.length - 1;
        reserve = _prodX(reserves) * ratios[j] / sumRatio;
        reserve = reserve.nthRoot(reserves.length);
    }

    /// @dev `b_j = Σ_{i != j}(b_i * r_j / r_i) / (n-1)`
    function calcReserveAtRatioLiquidity(
        uint256[] calldata reserves,
        uint256 j,
        uint256[] calldata ratios,
        bytes calldata
    ) external pure override returns (uint256 reserve) {
        for (uint256 i; i < reserves.length; ++i) {
            if (i != j) {
                reserve += ratios[j] * reserves[i] / ratios[i];
            }
        }
        reserve /= reserves.length - 1;
    }
}

File 25 of 49 : ConstantProduct2.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IBeanstalkWellFunction} from "src/interfaces/IBeanstalkWellFunction.sol";
import {ProportionalLPToken2} from "src/functions/ProportionalLPToken2.sol";
import {LibMath} from "src/libraries/LibMath.sol";

/**
 * @title ConstantProduct2
 * @author Publius
 * @notice Gas efficient Constant Product pricing function for Wells with 2 tokens.
 * @dev Constant Product Wells with 2 tokens use the formula:
 *  `b_0 * b_1 = s^2`
 *
 * Where:
 *  `s` is the supply of LP tokens
 *  `b_i` is the reserve at index `i`
 */
contract ConstantProduct2 is ProportionalLPToken2, IBeanstalkWellFunction {
    using LibMath for uint256;

    uint256 constant EXP_PRECISION = 1e12;

    /**
     * @dev `s = (b_0 * b_1)^(1/2)`
     *
     * When does this function overflow?
     * ---------------------------------
     *
     * Let N be the length of the reserves array, and P be the precision multiplier
     * defined in `EXP_PRECISION`.
     *
     * Assuming all tokens in reserves are at their maximum value simultaneously,
     * this function will overflow when:
     *
     *  (10^X)^N * P >= MAX_UINT256 (~10^77)
     *  10^(X*N) >= 10^77/P
     *  (X*N)*ln(10) >= 77*ln(10) - ln(P)
     *
     *  ∴ X >= (1/N) * (77 - ln(P)/ln(10))
     *
     * ConstantProduct2 sets the constraints `N = 2` and `EXP_PRECISION = 1e12`,
     * resulting in an upper bound of X = 32.5.
     *
     * In other words, {calcLpTokenSupply} overflows if all reserves are simultaneously
     * >= 10^32.5, or about 100 trillion if tokens are measured to 18 decimal precision.
     *
     * The further apart the reserve values, the greater the loss of precision in the `sqrt` function.
     */
    function calcLpTokenSupply(
        uint256[] calldata reserves,
        bytes calldata
    ) external pure override returns (uint256 lpTokenSupply) {
        lpTokenSupply = (reserves[0] * reserves[1] * EXP_PRECISION).sqrt();
    }

    /// @dev `b_j = s^2 / b_{i | i != j}`
    /// @dev rounds up
    function calcReserve(
        uint256[] calldata reserves,
        uint256 j,
        uint256 lpTokenSupply,
        bytes calldata
    ) external pure override returns (uint256 reserve) {
        if (j >= 2) {
            revert InvalidJArgument();
        }
        // Note: potential optimization is to use unchecked math here
        reserve = lpTokenSupply ** 2;
        reserve = LibMath.roundUpDiv(reserve, reserves[j == 1 ? 0 : 1] * EXP_PRECISION);
    }

    function name() external pure override returns (string memory) {
        return "Constant Product 2";
    }

    function symbol() external pure override returns (string memory) {
        return "CP2";
    }

    /// @dev `b_j = (b_0 * b_1 * r_j / r_i)^(1/2)`
    /// Note: Always rounds down
    function calcReserveAtRatioSwap(
        uint256[] calldata reserves,
        uint256 j,
        uint256[] calldata ratios,
        bytes calldata
    ) external pure override returns (uint256 reserve) {
        uint256 i = j == 1 ? 0 : 1;
        // use 512 muldiv for last mul to avoid overflow
        reserve = (reserves[i] * reserves[j]).mulDiv(ratios[j], ratios[i]).sqrt();
    }

    /// @dev `b_j = b_i * r_j / r_i`
    /// Note: Always rounds down
    function calcReserveAtRatioLiquidity(
        uint256[] calldata reserves,
        uint256 j,
        uint256[] calldata ratios,
        bytes calldata
    ) external pure override returns (uint256 reserve) {
        uint256 i = j == 1 ? 0 : 1;
        reserve = reserves[i] * ratios[j] / ratios[i];
    }
}

File 26 of 49 : ProportionalLPToken.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IWellFunction} from "src/interfaces/IWellFunction.sol";

/**
 * @title ProportionalLPToken
 * @notice Defines a proportional relationship between the supply of LP tokens
 * and the amount of each underlying token for an N-token Well.
 * @dev When removing `s` LP tokens with a Well with `S` LP token supply, the user
 * recieves `s * b_i / S` of each underlying token.
 */
abstract contract ProportionalLPToken is IWellFunction {
    function calcLPTokenUnderlying(
        uint256 lpTokenAmount,
        uint256[] calldata reserves,
        uint256 lpTokenSupply,
        bytes calldata
    ) external pure returns (uint256[] memory underlyingAmounts) {
        underlyingAmounts = new uint256[](reserves.length);
        for (uint256 i; i < reserves.length; ++i) {
            underlyingAmounts[i] = lpTokenAmount * reserves[i] / lpTokenSupply;
        }
    }
}

File 27 of 49 : ProportionalLPToken2.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IWellFunction} from "src/interfaces/IWellFunction.sol";

/**
 * @title ProportionalLPToken2
 * @notice Defines a proportional relationship between the supply of LP tokens
 * and the amount of each underlying token for a two-token Well.
 * @dev When removing `s` LP tokens with a Well with `S` LP token supply, the user
 * recieves `s * b_i / S` of each underlying token.
 */
abstract contract ProportionalLPToken2 is IWellFunction {
    function calcLPTokenUnderlying(
        uint256 lpTokenAmount,
        uint256[] calldata reserves,
        uint256 lpTokenSupply,
        bytes calldata
    ) external pure returns (uint256[] memory underlyingAmounts) {
        underlyingAmounts = new uint256[](2);
        underlyingAmounts[0] = lpTokenAmount * reserves[0] / lpTokenSupply;
        underlyingAmounts[1] = lpTokenAmount * reserves[1] / lpTokenSupply;
    }
}

File 28 of 49 : IChainlinkAggregator.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

interface IChainlinkAggregator {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function version() external view returns (uint256);

    // getRoundData and latestRoundData should both raise "No data present"
    // if they do not have data to report, instead of returning unset values
    // which could be misinterpreted as actual reported values.
    function getRoundData(uint80 _roundId)
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

File 29 of 49 : IWETH.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

/**
 * @title IWETH
 * @author Publius
 */
interface IWETH is IERC20 {
    function deposit() external payable;
    function withdraw(uint256) external;
}

File 30 of 49 : IAquifer.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IERC20, SafeERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IWell, Call} from "src/interfaces/IWell.sol";

/**
 * @title IAquifer
 * @author Publius
 * @notice Interface for the Aquifer, a permissionless Well deployer and registry.
 */
interface IAquifer {
    /**
     * @notice Thrown when the {init} function call on the Well reverts.
     */
    error InitFailed(string reason);

    /**
     * @notice Thrown when the user attempts to bore a Well with invalid configuration.
     */
    error InvalidConfig();

    /**
     * @notice Thrown a Well is bored, but not initialized.
     */
    error WellNotInitialized();

    /**
     * @notice Thrown when the user attempts to predict a Well's deterministic address with a salt of 0.
     */
    error InvalidSalt();

    /**
     * @notice Emitted when a Well is deployed.
     * @param well The address of the new Well
     * @param implementation The Well implementation address
     * @param tokens The tokens in the Well
     * @param wellFunction The Well function
     * @param pumps The pumps to bore in the Well
     * @param wellData The Well data to implement into the Well
     */
    event BoreWell(
        address well, address implementation, IERC20[] tokens, Call wellFunction, Call[] pumps, bytes wellData
    );

    /**
     * @notice Deploys a Well.
     * @param implementation The Well implementation to clone.
     * @param immutableData The data to append to the bytecode of the contract.
     * @param initFunctionCall The function call to initialize the Well. Set to empty bytes for no call.
     * @param salt The salt to deploy the Well with (`bytes32(0)` for none). See {LibClone}.
     * @return wellAddress The address of the new Well
     */
    function boreWell(
        address implementation,
        bytes calldata immutableData,
        bytes calldata initFunctionCall,
        bytes32 salt
    ) external returns (address wellAddress);

    /**
     * @notice Returns the implementation that a given Well was deployed with.
     * @param well The Well to get the implementation of
     * @return implementation The address of the implementation of a Well.
     * @dev Always verify that a Well was deployed by a trusted Aquifer using a trusted implementation before using.
     * If `wellImplementation == address(0)`, then the Aquifer did not deploy the Well.
     */
    function wellImplementation(address well) external view returns (address implementation);
}

File 31 of 49 : IBeanstalkWellFunction.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IWellFunction} from "src/interfaces/IWellFunction.sol";

/**
 * @title IBeanstalkWellFunction
 * @notice Defines all necessary functions for Beanstalk to support a Well Function in addition to functions defined in the primary interface.
 * This includes 2 functions to solve for a given reserve value suc that the average price between
 * the given reserve and all other reserves equals the average of the input ratios.
 * `calcReserveAtRatioSwap` assumes the target ratios are reached through executing a swap.
 * `calcReserveAtRatioLiquidity` assumes the target ratios are reached through adding/removing liquidity.
 */
interface IBeanstalkWellFunction is IWellFunction {
    /**
     * @notice Calculates the `j` reserve such that `π_{i | i != j} (d reserves_j / d reserves_i) = π_{i | i != j}(ratios_j / ratios_i)`.
     * assumes that reserve_j is being swapped for other reserves in the Well.
     * @dev used by Beanstalk to calculate the deltaB every Season
     * @param reserves The reserves of the Well
     * @param j The index of the reserve to solve for
     * @param ratios The ratios of reserves to solve for
     * @param data Well function data provided on every call
     * @return reserve The resulting reserve at the jth index
     */
    function calcReserveAtRatioSwap(
        uint256[] calldata reserves,
        uint256 j,
        uint256[] calldata ratios,
        bytes calldata data
    ) external view returns (uint256 reserve);

    /**
     * @notice Calculates the `j` reserve such that `π_{i | i != j} (d reserves_j / d reserves_i) = π_{i | i != j}(ratios_j / ratios_i)`.
     * assumes that reserve_j is being added or removed in exchange for LP Tokens.
     * @dev used by Beanstalk to calculate the max deltaB that can be converted in/out of a Well.
     * @param reserves The reserves of the Well
     * @param j The index of the reserve to solve for
     * @param ratios The ratios of reserves to solve for
     * @param data Well function data provided on every call
     * @return reserve The resulting reserve at the jth index
     */
    function calcReserveAtRatioLiquidity(
        uint256[] calldata reserves,
        uint256 j,
        uint256[] calldata ratios,
        bytes calldata data
    ) external view returns (uint256 reserve);
}

File 32 of 49 : IWell.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

/**
 * @title Call is the struct that contains the target address and extra calldata of a generic call.
 */
struct Call {
    address target; // The address the call is executed on.
    bytes data; // Extra calldata to be passed during the call
}

/**
 * @title IWell is the interface for the Well contract.
 *
 * In order for a Well to be verified using a permissionless on-chain registry, a Well Implementation should:
 * - Not be able to self-destruct (Aquifer's registry would be vulnerable to a metamorphic contract attack)
 * - Not be able to change its tokens, Well Function, Pumps and Well Data
 */
interface IWell {
    /**
     * @notice Emitted when a Swap occurs.
     * @param fromToken The token swapped from
     * @param toToken The token swapped to
     * @param amountIn The amount of `fromToken` transferred into the Well
     * @param amountOut The amount of `toToken` transferred out of the Well
     * @param recipient The address that received `toToken`
     */
    event Swap(IERC20 fromToken, IERC20 toToken, uint256 amountIn, uint256 amountOut, address recipient);

    /**
     * @notice Emitted when liquidity is added to the Well.
     * @param tokenAmountsIn The amount of each token added to the Well
     * @param lpAmountOut The amount of LP tokens minted
     * @param recipient The address that received the LP tokens
     */
    event AddLiquidity(uint256[] tokenAmountsIn, uint256 lpAmountOut, address recipient);

    /**
     * @notice Emitted when liquidity is removed from the Well as multiple underlying tokens.
     * @param lpAmountIn The amount of LP tokens burned
     * @param tokenAmountsOut The amount of each underlying token removed
     * @param recipient The address that received the underlying tokens
     * @dev Gas cost scales with `n` tokens.
     */
    event RemoveLiquidity(uint256 lpAmountIn, uint256[] tokenAmountsOut, address recipient);

    /**
     * @notice Emitted when liquidity is removed from the Well as a single underlying token.
     * @param lpAmountIn The amount of LP tokens burned
     * @param tokenOut The underlying token removed
     * @param tokenAmountOut The amount of `tokenOut` removed
     * @param recipient The address that received the underlying tokens
     * @dev Emitting a separate event when removing liquidity as a single token
     * saves gas, since `tokenAmountsOut` in {RemoveLiquidity} must emit a value
     * for each token in the Well.
     */
    event RemoveLiquidityOneToken(uint256 lpAmountIn, IERC20 tokenOut, uint256 tokenAmountOut, address recipient);

    /**
     * @notice Emitted when a Shift occurs.
     * @param reserves The ending reserves after a shift
     * @param toToken The token swapped to
     * @param amountOut The amount of `toToken` transferred out of the Well
     * @param recipient The address that received `toToken`
     */
    event Shift(uint256[] reserves, IERC20 toToken, uint256 amountOut, address recipient);

    /**
     * @notice Emitted when a Sync occurs.
     * @param reserves The ending reserves after a sync
     * @param lpAmountOut The amount of LP tokens received from the sync.
     * @param recipient The address that received the LP tokens
     */
    event Sync(uint256[] reserves, uint256 lpAmountOut, address recipient);

    //////////////////// WELL DEFINITION ////////////////////

    /**
     * @notice Returns a list of ERC20 tokens supported by the Well.
     */
    function tokens() external view returns (IERC20[] memory);

    /**
     * @notice Returns the Well function as a Call struct.
     * @dev Contains the address of the Well function contract and extra data to
     * pass during calls.
     *
     * **Well functions** define a relationship between the reserves of the
     * tokens in the Well and the number of LP tokens.
     *
     * A Well function MUST implement {IWellFunction}.
     */
    function wellFunction() external view returns (Call memory);

    /**
     * @notice Returns the Pumps attached to the Well as Call structs.
     * @dev Contains the addresses of the Pumps contract and extra data to pass
     * during calls.
     *
     * **Pumps** are on-chain oracles that are updated every time the Well is
     * interacted with.
     *
     * A Pump is not required for Well operation. For Wells without a Pump:
     * `pumps().length = 0`.
     *
     * An attached Pump MUST implement {IPump}.
     */
    function pumps() external view returns (Call[] memory);

    /**
     * @notice Returns the Well data that the Well was bored with.
     * @dev The existence and signature of Well data is determined by each individual implementation.
     */
    function wellData() external view returns (bytes memory);

    /**
     * @notice Returns the Aquifer that created this Well.
     * @dev Wells can be permissionlessly bored in an Aquifer.
     *
     * Aquifers stores the implementation that was used to bore the Well.
     */
    function aquifer() external view returns (address);

    /**
     * @notice Returns the tokens, Well Function, Pumps and Well Data associated
     * with the Well as well as the Aquifer that deployed the Well.
     */
    function well()
        external
        view
        returns (
            IERC20[] memory _tokens,
            Call memory _wellFunction,
            Call[] memory _pumps,
            bytes memory _wellData,
            address _aquifer
        );

    //////////////////// SWAP: FROM ////////////////////

    /**
     * @notice Swaps from an exact amount of `fromToken` to a minimum amount of `toToken`.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountIn The amount of `fromToken` to spend
     * @param minAmountOut The minimum amount of `toToken` to receive
     * @param recipient The address to receive `toToken`
     * @param deadline The timestamp after which this operation is invalid
     * @return amountOut The amount of `toToken` received
     */
    function swapFrom(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 amountOut);

    /**
     * @notice Swaps from an exact amount of `fromToken` to a minimum amount of `toToken` and supports fee on transfer tokens.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountIn The amount of `fromToken` to spend
     * @param minAmountOut The minimum amount of `toToken` to take from the Well. Note that if `toToken` charges a fee on transfer, `recipient` will receive less than this amount.
     * @param recipient The address to receive `toToken`
     * @param deadline The timestamp after which this operation is invalid
     * @return amountOut The amount of `toToken` transferred from the Well. Note that if `toToken` charges a fee on transfer, `recipient` may receive less than this amount.
     * @dev Can also be used for tokens without a fee on transfer, but is less gas efficient.
     */
    function swapFromFeeOnTransfer(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 amountOut);

    /**
     * @notice Gets the amount of one token received for swapping an amount of another token.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountIn The amount of `fromToken` to spend
     * @return amountOut The amount of `toToken` to receive
     */
    function getSwapOut(IERC20 fromToken, IERC20 toToken, uint256 amountIn) external view returns (uint256 amountOut);

    //////////////////// SWAP: TO ////////////////////

    /**
     * @notice Swaps from a maximum amount of `fromToken` to an exact amount of `toToken`.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param maxAmountIn The maximum amount of `fromToken` to spend
     * @param amountOut The amount of `toToken` to receive
     * @param recipient The address to receive `toToken`
     * @param deadline The timestamp after which this operation is invalid
     * @return amountIn The amount of `toToken` received
     */
    function swapTo(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 maxAmountIn,
        uint256 amountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 amountIn);

    /**
     * @notice Gets the amount of one token that must be spent to receive an amount of another token during a swap.
     * @param fromToken The token to swap from
     * @param toToken The token to swap to
     * @param amountOut The amount of `toToken` desired
     * @return amountIn The amount of `fromToken` that must be spent
     */
    function getSwapIn(IERC20 fromToken, IERC20 toToken, uint256 amountOut) external view returns (uint256 amountIn);

    //////////////////// SHIFT ////////////////////

    /**
     * @notice Shifts at least `minAmountOut` excess tokens held by the Well into `tokenOut` and delivers to `recipient`.
     * @param tokenOut The token to shift into
     * @param minAmountOut The minimum amount of `tokenOut` to receive
     * @param recipient The address to receive the token
     * @return amountOut The amount of `tokenOut` received
     * @dev Can be used in a multicall using a contract like Pipeline to perform gas efficient swaps.
     * No deadline is needed since this function does not use the user's assets. If adding liquidity in a multicall,
     * then a deadline check can be added to the multicall.
     */
    function shift(IERC20 tokenOut, uint256 minAmountOut, address recipient) external returns (uint256 amountOut);

    /**
     * @notice Calculates the amount of the token out received from shifting excess tokens held by the Well.
     * @param tokenOut The token to shift into
     * @return amountOut The amount of `tokenOut` received
     */
    function getShiftOut(IERC20 tokenOut) external returns (uint256 amountOut);

    //////////////////// ADD LIQUIDITY ////////////////////

    /**
     * @notice Adds liquidity to the Well as multiple tokens in any ratio.
     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}
     * @param minLpAmountOut The minimum amount of LP tokens to receive
     * @param recipient The address to receive the LP tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return lpAmountOut The amount of LP tokens received
     */
    function addLiquidity(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 lpAmountOut);

    /**
     * @notice Adds liquidity to the Well as multiple tokens in any ratio and supports
     * fee on transfer tokens.
     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}
     * @param minLpAmountOut The minimum amount of LP tokens to receive
     * @param recipient The address to receive the LP tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return lpAmountOut The amount of LP tokens received
     * @dev Can also be used for tokens without a fee on transfer, but is less gas efficient.
     */
    function addLiquidityFeeOnTransfer(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 lpAmountOut);

    /**
     * @notice Gets the amount of LP tokens received from adding liquidity as multiple tokens in any ratio.
     * @param tokenAmountsIn The amount of each token to add; MUST match the indexing of {Well.tokens}
     * @return lpAmountOut The amount of LP tokens received
     */
    function getAddLiquidityOut(uint256[] memory tokenAmountsIn) external view returns (uint256 lpAmountOut);

    //////////////////// REMOVE LIQUIDITY: BALANCED ////////////////////

    /**
     * @notice Removes liquidity from the Well as all underlying tokens in a balanced ratio.
     * @param lpAmountIn The amount of LP tokens to burn
     * @param minTokenAmountsOut The minimum amount of each underlying token to receive; MUST match the indexing of {Well.tokens}
     * @param recipient The address to receive the underlying tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return tokenAmountsOut The amount of each underlying token received
     */
    function removeLiquidity(
        uint256 lpAmountIn,
        uint256[] calldata minTokenAmountsOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256[] memory tokenAmountsOut);

    /**
     * @notice Gets the amount of each underlying token received from removing liquidity in a balanced ratio.
     * @param lpAmountIn The amount of LP tokens to burn
     * @return tokenAmountsOut The amount of each underlying token received
     */
    function getRemoveLiquidityOut(uint256 lpAmountIn) external view returns (uint256[] memory tokenAmountsOut);

    //////////////////// REMOVE LIQUIDITY: ONE TOKEN ////////////////////

    /**
     * @notice Removes liquidity from the Well as a single underlying token.
     * @param lpAmountIn The amount of LP tokens to burn
     * @param tokenOut The underlying token to receive
     * @param minTokenAmountOut The minimum amount of `tokenOut` to receive
     * @param recipient The address to receive the underlying tokens
     * @param deadline The timestamp after which this operation is invalid
     * @return tokenAmountOut The amount of `tokenOut` received
     */
    function removeLiquidityOneToken(
        uint256 lpAmountIn,
        IERC20 tokenOut,
        uint256 minTokenAmountOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 tokenAmountOut);

    /**
     * @notice Gets the amount received from removing liquidity from the Well as a single underlying token.
     * @param lpAmountIn The amount of LP tokens to burn
     * @param tokenOut The underlying token to receive
     * @return tokenAmountOut The amount of `tokenOut` received
     *
     */
    function getRemoveLiquidityOneTokenOut(
        uint256 lpAmountIn,
        IERC20 tokenOut
    ) external view returns (uint256 tokenAmountOut);

    //////////////////// REMOVE LIQUIDITY: IMBALANCED ////////////////////

    /**
     * @notice Removes liquidity from the Well as multiple underlying tokens in any ratio.
     * @param maxLpAmountIn The maximum amount of LP tokens to burn
     * @param tokenAmountsOut The amount of each underlying token to receive; MUST match the indexing of {Well.tokens}
     * @param recipient The address to receive the underlying tokens
     * @return lpAmountIn The amount of LP tokens burned
     */
    function removeLiquidityImbalanced(
        uint256 maxLpAmountIn,
        uint256[] calldata tokenAmountsOut,
        address recipient,
        uint256 deadline
    ) external returns (uint256 lpAmountIn);

    /**
     * @notice Gets the amount of LP tokens to burn from removing liquidity as multiple underlying tokens in any ratio.
     * @param tokenAmountsOut The amount of each underlying token to receive; MUST match the indexing of {Well.tokens}
     * @return lpAmountIn The amount of LP tokens burned
     */
    function getRemoveLiquidityImbalancedIn(uint256[] calldata tokenAmountsOut)
        external
        view
        returns (uint256 lpAmountIn);

    //////////////////// RESERVES ////////////////////

    /**
     * @notice Syncs the Well's reserves with the Well's balances of underlying tokens. If the reserves
     * increase, mints at least `minLpAmountOut` LP Tokens to `recipient`.
     * @param recipient The address to receive the LP tokens
     * @param minLpAmountOut The minimum amount of LP tokens to receive
     * @return lpAmountOut The amount of LP tokens received
     * @dev Can be used in a multicall using a contract like Pipeline to perform gas efficient additions of liquidity.
     * No deadline is needed since this function does not use the user's assets. If adding liquidity in a multicall,
     * then a deadline check can be added to the multicall.
     * If `sync` decreases the Well's reserves, then no LP tokens are minted and `lpAmountOut` must be 0.
     */
    function sync(address recipient, uint256 minLpAmountOut) external returns (uint256 lpAmountOut);

    /**
     * @notice Calculates the amount of LP Tokens received from syncing the Well's reserves with the Well's balances.
     * @return lpAmountOut The amount of LP tokens received
     */
    function getSyncOut() external view returns (uint256 lpAmountOut);

    /**
     * @notice Sends excess tokens held by the Well to the `recipient`.
     * @param recipient The address to send the tokens
     * @return skimAmounts The amount of each token skimmed
     * @dev No deadline is needed since this function does not use the user's assets.
     */
    function skim(address recipient) external returns (uint256[] memory skimAmounts);

    /**
     * @notice Gets the reserves of each token held by the Well.
     */
    function getReserves() external view returns (uint256[] memory reserves);

    /**
     * @notice Returns whether or not the Well is initialized if it requires initialization.
     * If a Well does not require initialization, it should always return `true`.
     */
    function isInitialized() external view returns (bool);
}

File 33 of 49 : IWellErrors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";

/**
 * @title IWellErrors defines all Well errors.
 * @dev The errors are separated into a different interface as not all Well
 * implementations may share the same errors.
 */
interface IWellErrors {
    /**
     * @notice Thrown when an operation would deliver fewer tokens than `minAmountOut`.
     */
    error SlippageOut(uint256 amountOut, uint256 minAmountOut);

    /**
     * @notice Thrown when an operation would require more tokens than `maxAmountIn`.
     */
    error SlippageIn(uint256 amountIn, uint256 maxAmountIn);

    /**
     * @notice Thrown if one or more tokens used in the operation are not supported by the Well.
     */
    error InvalidTokens();

    /**
     * @notice Thrown if this operation would cause an incorrect change in Well reserves.
     */
    error InvalidReserves();

    /**
     * @notice Thrown when a Well is bored with duplicate tokens.
     */
    error DuplicateTokens(IERC20 token);

    /**
     * @notice Thrown if an operation is executed after the provided `deadline` has passed.
     */
    error Expired();
}

File 34 of 49 : IWellFunction.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title IWellFunction
 * @notice Defines a relationship between token reserves and LP token supply.
 * @dev Well Functions can contain arbitrary logic, but should be deterministic
 * if expected to be used alongside a Pump. When interacing with a Well or
 * Well Function, always verify that the Well Function is valid.
 */
interface IWellFunction {
    /**
     * @notice Thrown if the user inputs a `j` value is out of bounds.
     */
    error InvalidJArgument();

    /**
     * @notice Calculates the `j`th reserve given a list of `reserves` and `lpTokenSupply`.
     * @param reserves A list of token reserves. The jth reserve will be ignored, but a placeholder must be provided.
     * @param j The index of the reserve to solve for
     * @param lpTokenSupply The supply of LP tokens
     * @param data Extra Well function data provided on every call
     * @return reserve The resulting reserve at the jth index
     * @dev Should round up to ensure that Well reserves are marginally higher to enforce calcLpTokenSupply(...) >= totalSupply()
     */
    function calcReserve(
        uint256[] memory reserves,
        uint256 j,
        uint256 lpTokenSupply,
        bytes calldata data
    ) external view returns (uint256 reserve);

    /**
     * @notice Gets the LP token supply given a list of reserves.
     * @param reserves A list of token reserves
     * @param data Extra Well function data provided on every call
     * @return lpTokenSupply The resulting supply of LP tokens
     * @dev Should round down to ensure so that the Well Token supply is marignally lower to enforce calcLpTokenSupply(...) >= totalSupply()
     */
    function calcLpTokenSupply(
        uint256[] memory reserves,
        bytes calldata data
    ) external view returns (uint256 lpTokenSupply);

    /**
     * @notice Calculates the amount of each reserve token underlying a given amount of LP tokens.
     * @param lpTokenAmount An amount of LP tokens
     * @param reserves A list of token reserves
     * @param lpTokenSupply The current supply of LP tokens
     * @param data Extra Well function data provided on every call
     * @return underlyingAmounts The amount of each reserve token that underlies the LP tokens
     * @dev The constraint totalSupply() <= calcLPTokenSupply(...) must be held in the case where
     * `lpTokenAmount` LP tokens are burned in exchanged for `underlyingAmounts`. If the constraint
     * does not hold, then the Well Function is invalid.
     */
    function calcLPTokenUnderlying(
        uint256 lpTokenAmount,
        uint256[] memory reserves,
        uint256 lpTokenSupply,
        bytes calldata data
    ) external view returns (uint256[] memory underlyingAmounts);

    /**
     * @notice Returns the name of the Well function.
     */
    function name() external view returns (string memory);

    /**
     * @notice Returns the symbol of the Well function.
     */
    function symbol() external view returns (string memory);
}

File 35 of 49 : ICumulativePump.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title ICumulativePump
 * @notice Provides an interface for Pumps which calculate time-weighted average
 * reserves through the use of a cumulative reserve.
 */
interface ICumulativePump {
    /**
     * @notice Reads the current cumulative reserves from the Pump
     * @param well The address of the Well
     * @param data data specific to the Well
     * @return cumulativeReserves The cumulative reserves from the Pump
     */
    function readCumulativeReserves(
        address well,
        bytes memory data
    ) external view returns (bytes memory cumulativeReserves);

    /**
     * @notice Reads the current cumulative reserves from the Pump
     * @param well The address of the Well
     * @param startCumulativeReserves The cumulative reserves to start the TWA from
     * @param startTimestamp The timestamp to start the TWA from
     * @param data data specific to the Well
     * @return twaReserves The time weighted average reserves from start timestamp to now
     * @return cumulativeReserves The current cumulative reserves from the Pump at the current timestamp
     */
    function readTwaReserves(
        address well,
        bytes calldata startCumulativeReserves,
        uint256 startTimestamp,
        bytes memory data
    ) external view returns (uint256[] memory twaReserves, bytes memory cumulativeReserves);
}

File 36 of 49 : IInstantaneousPump.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title Instantaneous Pumps provide an Oracle for instantaneous reserves.
 */
interface IInstantaneousPump {
    /**
     * @notice Reads instantaneous reserves from the Pump
     * @param well The address of the Well
     * @return reserves The instantaneous balanecs tracked by the Pump
     */
    function readInstantaneousReserves(
        address well,
        bytes memory data
    ) external view returns (uint256[] memory reserves);
}

File 37 of 49 : IMultiFlowPumpErrors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title IMultiFlowPumpErrors defines the errors for the MultiFlowPump.
 * @dev The errors are separated into a different interface as not all Pump
 * implementations may share the same errors.
 */
interface IMultiFlowPumpErrors {
    error NotInitialized();

    error NoTimePassed();
}

File 38 of 49 : IPump.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title IPump defines the interface for a Pump.
 *
 * @dev Pumps are on-chain oracles that are updated upon each interaction with a {IWell}.
 * When reading a Pump, always verify the Pump's functionality.
 */
interface IPump {
    /**
     * @notice Updates the Pump with the given reserves.
     * @param reserves The previous reserves of the tokens in the Well.
     * @param data data specific to the Well
     * @dev Pumps are updated every time a user swaps, adds liquidity, or
     * removes liquidity from a Well.
     */
    function update(uint256[] calldata reserves, bytes calldata data) external;
}

File 39 of 49 : ABDKMathQuad.sol
// SPDX-License-Identifier: BSD-4-Clause
/*
 * ABDK Math Quad Smart Contract Library.  Copyright © 2019 by ABDK Consulting.
 * Author: Mikhail Vladimirov <[email protected]>
 */
pragma solidity ^0.8.20;

/**
 * Smart contract library of mathematical functions operating with IEEE 754
 * quadruple-precision binary floating-point numbers (quadruple precision
 * numbers).  As long as quadruple precision numbers are 16-bytes long, they are
 * represented by bytes16 type.
 */
library ABDKMathQuad {
    /*
    * 0.
    */
    bytes16 internal constant POSITIVE_ZERO = 0x00000000000000000000000000000000;

    /*
    * -0.
    */
    bytes16 private constant NEGATIVE_ZERO = 0x80000000000000000000000000000000;

    /*
    * +Infinity.
    */
    bytes16 internal constant POSITIVE_INFINITY = 0x7FFF0000000000000000000000000000;

    /*
    * -Infinity.
    */
    bytes16 private constant NEGATIVE_INFINITY = 0xFFFF0000000000000000000000000000;

    /*
    * Canonical NaN value.
    */
    bytes16 private constant NaN = 0x7FFF8000000000000000000000000000;

    /*
    * One.
    */
    bytes16 internal constant ONE = 0x3fff0000000000000000000000000000;

    /**
     * Convert signed 256-bit integer number into quadruple precision number.
     *
     * @param x signed 256-bit integer number
     * @return quadruple precision number
     */
    function fromInt(int x) internal pure returns (bytes16) {
        unchecked {
            if (x == 0) {
                return bytes16(0);
            } else {
                // We rely on overflow behavior here
                uint256 result = uint256(x > 0 ? x : -x);

                uint256 msb = mostSignificantBit(result);
                if (msb < 112) result <<= 112 - msb;
                else if (msb > 112) result >>= msb - 112;

                result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16_383 + msb << 112;
                if (x < 0) result |= 0x80000000000000000000000000000000;

                return bytes16(uint128(result));
            }
        }
    }

    /**
     * Convert quadruple precision number into signed 256-bit integer number
     * rounding towards zero.  Revert on overflow.
     *
     * @param x quadruple precision number
     * @return signed 256-bit integer number
     */
    function toInt(bytes16 x) internal pure returns (int) {
        unchecked {
            uint256 exponent = uint128(x) >> 112 & 0x7FFF;

            require(exponent <= 16_638); // Overflow
            if (exponent < 16_383) return 0; // Underflow

            uint256 result = uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 0x10000000000000000000000000000;

            if (exponent < 16_495) result >>= 16_495 - exponent;
            else if (exponent > 16_495) result <<= exponent - 16_495;

            if (uint128(x) >= 0x80000000000000000000000000000000) {
                // Negative
                require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
                return -int(result); // We rely on overflow behavior here
            } else {
                require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
                return int(result);
            }
        }
    }

    /**
     * Convert unsigned 256-bit integer number into quadruple precision number.
     *
     * @param x unsigned 256-bit integer number
     * @return quadruple precision number
     */
    function fromUIntToLog2(uint256 x) internal pure returns (bytes16) {
        unchecked {
            if (x == 0) {
                return bytes16(0);
            } else {
                uint256 result = x;

                uint256 msb = mostSignificantBit(result);
                if (msb < 112) result <<= 112 - msb;
                else if (msb > 112) result >>= msb - 112;

                result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16_383 + msb << 112;
                // return bytes16(uint128(result));

                // log_2 stuff
                // x here should be replaced with result 
                if (uint128(result) > 0x80000000000000000000000000000000) {
                    return NaN;
                } else if (bytes16(uint128(result)) == 0x3FFF0000000000000000000000000000) {
                    return POSITIVE_ZERO;
                } else {
                    uint256 xExponent = uint128(result) >> 112 & 0x7FFF;
                    if (xExponent == 0x7FFF) {
                        return bytes16(uint128(result));
                    } else {
                        uint256 xSignifier = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                        if (xExponent == 0) xExponent = 1;
                        else xSignifier |= 0x10000000000000000000000000000;

                        if (xSignifier == 0) return NEGATIVE_INFINITY;

                        bool resultNegative;
                        uint256 resultExponent = 16_495;
                        uint256 resultSignifier;

                        if (xExponent >= 0x3FFF) {
                            resultNegative = false;
                            resultSignifier = xExponent - 0x3FFF;
                            xSignifier <<= 15;
                        } else {
                            resultNegative = true;
                            if (xSignifier >= 0x10000000000000000000000000000) {
                                resultSignifier = 0x3FFE - xExponent;
                                xSignifier <<= 15;
                            } else {
                                msb = mostSignificantBit(xSignifier);
                                resultSignifier = 16_493 - msb;
                                xSignifier <<= 127 - msb;
                            }
                        }

                        if (xSignifier == 0x80000000000000000000000000000000) {
                            if (resultNegative) resultSignifier += 1;
                            uint256 shift = 112 - mostSignificantBit(resultSignifier);
                            resultSignifier <<= shift;
                            resultExponent -= shift;
                        } else {
                            uint256 bb = resultNegative ? 1 : 0;
                            while (resultSignifier < 0x10000000000000000000000000000) {
                                resultSignifier <<= 1;
                                resultExponent -= 1;

                                xSignifier *= xSignifier;
                                uint256 b = xSignifier >> 255;
                                resultSignifier += b ^ bb;
                                xSignifier >>= 127 + b;
                            }
                        }

                        return bytes16(
                            uint128(
                                (resultNegative ? 0x80000000000000000000000000000000 : 0) | resultExponent << 112
                                    | resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF
                            )
                        );
                    }
                }
            }
        }
    }

    function fromUInt(uint256 x) internal pure returns (bytes16){
        unchecked {
            if (x == 0) {
                return bytes16(0);
            } else {
                uint256 result = x;

                uint256 msb = mostSignificantBit(result);
                if (msb < 112) result <<= 112 - msb;
                else if (msb > 112) result >>= msb - 112;

                result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16_383 + msb << 112;

                return bytes16(uint128(result));             
            }
        }
    }

    /**
     * Convert quadruple precision number into unsigned 256-bit integer number
     * rounding towards zero.  Revert on underflow.  Note, that negative floating
     * point numbers in range (-1.0 .. 0.0) may be converted to unsigned integer
     * without error, because they are rounded to zero.
     *
     * @param x quadruple precision number
     * @return unsigned 256-bit integer number
     */
    function toUInt(bytes16 x) internal pure returns (uint256) {
        unchecked {
            uint256 exponent = uint128(x) >> 112 & 0x7FFF;

            if (exponent < 16_383) return 0; // Underflow

            require(uint128(x) < 0x80000000000000000000000000000000); // Negative

            require(exponent <= 16_638); // Overflow
            uint256 result = uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 0x10000000000000000000000000000;

            if (exponent < 16_495) result >>= 16_495 - exponent;
            else if (exponent > 16_495) result <<= exponent - 16_495;

            return result;
        }
    }

    /**
     * Convert signed 128.128 bit fixed point number into quadruple precision
     * number.
     *
     * @param x signed 128.128 bit fixed point number
     * @return quadruple precision number
     */
    function from128x128(int x) internal pure returns (bytes16) {
        unchecked {
            if (x == 0) {
                return bytes16(0);
            } else {
                // We rely on overflow behavior here
                uint256 result = uint256(x > 0 ? x : -x);

                uint256 msb = mostSignificantBit(result);
                if (msb < 112) result <<= 112 - msb;
                else if (msb > 112) result >>= msb - 112;

                result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16_255 + msb << 112;
                if (x < 0) result |= 0x80000000000000000000000000000000;

                return bytes16(uint128(result));
            }
        }
    }

    /**
     * Convert quadruple precision number into signed 128.128 bit fixed point
     * number.  Revert on overflow.
     *
     * @param x quadruple precision number
     * @return signed 128.128 bit fixed point number
     */
    function to128x128(bytes16 x) internal pure returns (int) {
        unchecked {
            uint256 exponent = uint128(x) >> 112 & 0x7FFF;

            require(exponent <= 16_510); // Overflow
            if (exponent < 16_255) return 0; // Underflow

            uint256 result = uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 0x10000000000000000000000000000;

            if (exponent < 16_367) result >>= 16_367 - exponent;
            else if (exponent > 16_367) result <<= exponent - 16_367;

            if (uint128(x) >= 0x80000000000000000000000000000000) {
                // Negative
                require(result <= 0x8000000000000000000000000000000000000000000000000000000000000000);
                return -int(result); // We rely on overflow behavior here
            } else {
                require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
                return int(result);
            }
        }
    }

    /**
     * Convert signed 64.64 bit fixed point number into quadruple precision
     * number.
     *
     * @param x signed 64.64 bit fixed point number
     * @return quadruple precision number
     */
    function from64x64(int128 x) internal pure returns (bytes16) {
        unchecked {
            if (x == 0) {
                return bytes16(0);
            } else {
                // We rely on overflow behavior here
                uint256 result = uint128(x > 0 ? x : -x);

                uint256 msb = mostSignificantBit(result);
                if (msb < 112) result <<= 112 - msb;
                else if (msb > 112) result >>= msb - 112;

                result = result & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 16_319 + msb << 112;
                if (x < 0) result |= 0x80000000000000000000000000000000;

                return bytes16(uint128(result));
            }
        }
    }

    /**
     * Convert quadruple precision number into signed 64.64 bit fixed point
     * number.  Revert on overflow.
     *
     * @param x quadruple precision number
     * @return signed 64.64 bit fixed point number
     */
    function to64x64(bytes16 x) internal pure returns (int128) {
        unchecked {
            uint256 exponent = uint128(x) >> 112 & 0x7FFF;

            require(exponent <= 16_446); // Overflow
            if (exponent < 16_319) return 0; // Underflow

            uint256 result = uint256(uint128(x)) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 0x10000000000000000000000000000;

            if (exponent < 16_431) result >>= 16_431 - exponent;
            else if (exponent > 16_431) result <<= exponent - 16_431;

            if (uint128(x) >= 0x80000000000000000000000000000000) {
                // Negative
                require(result <= 0x80000000000000000000000000000000);
                return -int128(int(result)); // We rely on overflow behavior here
            } else {
                require(result <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
                return int128(int(result));
            }
        }
    }

    /**
     * Convert octuple precision number into quadruple precision number.
     *
     * @param x octuple precision number
     * @return quadruple precision number
     */
    function fromOctuple(bytes32 x) internal pure returns (bytes16) {
        unchecked {
            bool negative = x & 0x8000000000000000000000000000000000000000000000000000000000000000 > 0;

            uint256 exponent = uint256(x) >> 236 & 0x7FFFF;
            uint256 significand = uint256(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            if (exponent == 0x7FFFF) {
                if (significand > 0) return NaN;
                else return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
            }

            if (exponent > 278_526) {
                return negative ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
            } else if (exponent < 245_649) {
                return negative ? NEGATIVE_ZERO : POSITIVE_ZERO;
            } else if (exponent < 245_761) {
                significand =
                    (significand | 0x100000000000000000000000000000000000000000000000000000000000) >> 245_885 - exponent;
                exponent = 0;
            } else {
                significand >>= 124;
                exponent -= 245_760;
            }

            uint128 result = uint128(significand | exponent << 112);
            if (negative) result |= 0x80000000000000000000000000000000;

            return bytes16(result);
        }
    }

    /**
     * Convert quadruple precision number into octuple precision number.
     *
     * @param x quadruple precision number
     * @return octuple precision number
     */
    function toOctuple(bytes16 x) internal pure returns (bytes32) {
        unchecked {
            uint256 exponent = uint128(x) >> 112 & 0x7FFF;

            uint256 result = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            if (exponent == 0x7FFF) {
                exponent = 0x7FFFF;
            } // Infinity or NaN
            else if (exponent == 0) {
                if (result > 0) {
                    uint256 msb = mostSignificantBit(result);
                    result = result << 236 - msb & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    exponent = 245_649 + msb;
                }
            } else {
                result <<= 124;
                exponent += 245_760;
            }

            result |= exponent << 236;
            if (uint128(x) >= 0x80000000000000000000000000000000) {
                result |= 0x8000000000000000000000000000000000000000000000000000000000000000;
            }

            return bytes32(result);
        }
    }

    /**
     * Convert double precision number into quadruple precision number.
     *
     * @param x double precision number
     * @return quadruple precision number
     */
    function fromDouble(bytes8 x) internal pure returns (bytes16) {
        unchecked {
            uint256 exponent = uint64(x) >> 52 & 0x7FF;

            uint256 result = uint64(x) & 0xFFFFFFFFFFFFF;

            if (exponent == 0x7FF) {
                exponent = 0x7FFF;
            } // Infinity or NaN
            else if (exponent == 0) {
                if (result > 0) {
                    uint256 msb = mostSignificantBit(result);
                    result = result << 112 - msb & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    exponent = 15_309 + msb;
                }
            } else {
                result <<= 60;
                exponent += 15_360;
            }

            result |= exponent << 112;
            if (x & 0x8000000000000000 > 0) {
                result |= 0x80000000000000000000000000000000;
            }

            return bytes16(uint128(result));
        }
    }

    /**
     * Convert quadruple precision number into double precision number.
     *
     * @param x quadruple precision number
     * @return double precision number
     */
    function toDouble(bytes16 x) internal pure returns (bytes8) {
        unchecked {
            bool negative = uint128(x) >= 0x80000000000000000000000000000000;

            uint256 exponent = uint128(x) >> 112 & 0x7FFF;
            uint256 significand = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            if (exponent == 0x7FFF) {
                if (significand > 0) {
                    return 0x7FF8000000000000;
                } // NaN
                else {
                    return negative
                        ? bytes8(0xFFF0000000000000) // -Infinity
                        : bytes8(0x7FF0000000000000);
                } // Infinity
            }

            if (exponent > 17_406) {
                return negative
                    ? bytes8(0xFFF0000000000000) // -Infinity
                    : bytes8(0x7FF0000000000000);
            } // Infinity
            else if (exponent < 15_309) {
                return negative
                    ? bytes8(0x8000000000000000) // -0
                    : bytes8(0x0000000000000000);
            } // 0
            else if (exponent < 15_361) {
                significand = (significand | 0x10000000000000000000000000000) >> 15_421 - exponent;
                exponent = 0;
            } else {
                significand >>= 60;
                exponent -= 15_360;
            }

            uint64 result = uint64(significand | exponent << 52);
            if (negative) result |= 0x8000000000000000;

            return bytes8(result);
        }
    }

    /**
     * Test whether given quadruple precision number is NaN.
     *
     * @param x quadruple precision number
     * @return true if x is NaN, false otherwise
     */
    function isNaN(bytes16 x) internal pure returns (bool) {
        unchecked {
            return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF > 0x7FFF0000000000000000000000000000;
        }
    }

    /**
     * Test whether given quadruple precision number is positive or negative
     * infinity.
     *
     * @param x quadruple precision number
     * @return true if x is positive or negative infinity, false otherwise
     */
    function isInfinity(bytes16 x) internal pure returns (bool) {
        unchecked {
            return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0x7FFF0000000000000000000000000000;
        }
    }

    /**
     * Calculate sign of x, i.e. -1 if x is negative, 0 if x if zero, and 1 if x
     * is positive.  Note that sign (-0) is zero.  Revert if x is NaN.
     *
     * @param x quadruple precision number
     * @return sign of x
     */
    function sign(bytes16 x) internal pure returns (int8) {
        unchecked {
            uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN

            if (absoluteX == 0) return 0;
            else if (uint128(x) >= 0x80000000000000000000000000000000) return -1;
            else return 1;
        }
    }

    /**
     * Calculate sign (x - y).  Revert if either argument is NaN, or both
     * arguments are infinities of the same sign.
     *
     * @param x quadruple precision number
     * @param y quadruple precision number
     * @return sign (x - y)
     */
    function cmp(bytes16 x, bytes16 y) internal pure returns (int8) {
        unchecked {
            uint128 absoluteX = uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            require(absoluteX <= 0x7FFF0000000000000000000000000000); // Not NaN

            uint128 absoluteY = uint128(y) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            require(absoluteY <= 0x7FFF0000000000000000000000000000); // Not NaN

            // Not infinities of the same sign
            require(x != y || absoluteX < 0x7FFF0000000000000000000000000000);

            if (x == y) {
                return 0;
            } else {
                bool negativeX = uint128(x) >= 0x80000000000000000000000000000000;
                bool negativeY = uint128(y) >= 0x80000000000000000000000000000000;

                if (negativeX) {
                    if (negativeY) return absoluteX > absoluteY ? -1 : int8(1);
                    else return -1;
                } else {
                    if (negativeY) return 1;
                    else return absoluteX > absoluteY ? int8(1) : -1;
                }
            }
        }
    }

    /**
     * Test whether x equals y.  NaN, infinity, and -infinity are not equal to
     * anything.
     *
     * @param x quadruple precision number
     * @param y quadruple precision number
     * @return true if x equals to y, false otherwise
     */
    function eq(bytes16 x, bytes16 y) internal pure returns (bool) {
        unchecked {
            if (x == y) {
                return uint128(x) & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF < 0x7FFF0000000000000000000000000000;
            } else {
                return false;
            }
        }
    }

    /**
     * Calculate x + y.  Special values behave in the following way:
     *
     * NaN + x = NaN for any x.
     * Infinity + x = Infinity for any finite x.
     * -Infinity + x = -Infinity for any finite x.
     * Infinity + Infinity = Infinity.
     * -Infinity + -Infinity = -Infinity.
     * Infinity + -Infinity = -Infinity + Infinity = NaN.
     *
     * @param x quadruple precision number
     * @param y quadruple precision number
     * @return quadruple precision number
     */
    function add(bytes16 x, bytes16 y) internal pure returns (bytes16) {
        unchecked {
            uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
            uint256 yExponent = uint128(y) >> 112 & 0x7FFF;

            if (xExponent == 0x7FFF) {
                if (yExponent == 0x7FFF) {
                    if (x == y) return x;
                    else return NaN;
                } else {
                    return x;
                }
            } else if (yExponent == 0x7FFF) {
                return y;
            } else {
                bool xSign = uint128(x) >= 0x80000000000000000000000000000000;
                uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (xExponent == 0) xExponent = 1;
                else xSignifier |= 0x10000000000000000000000000000;

                bool ySign = uint128(y) >= 0x80000000000000000000000000000000;
                uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (yExponent == 0) yExponent = 1;
                else ySignifier |= 0x10000000000000000000000000000;

                if (xSignifier == 0) {
                    return y == NEGATIVE_ZERO ? POSITIVE_ZERO : y;
                } else if (ySignifier == 0) {
                    return x == NEGATIVE_ZERO ? POSITIVE_ZERO : x;
                } else {
                    int delta = int(xExponent) - int(yExponent);

                    if (xSign == ySign) {
                        if (delta > 112) {
                            return x;
                        } else if (delta > 0) {
                            ySignifier >>= uint256(delta);
                        } else if (delta < -112) {
                            return y;
                        } else if (delta < 0) {
                            xSignifier >>= uint256(-delta);
                            xExponent = yExponent;
                        }

                        xSignifier += ySignifier;

                        if (xSignifier >= 0x20000000000000000000000000000) {
                            xSignifier >>= 1;
                            xExponent += 1;
                        }

                        if (xExponent == 0x7FFF) {
                            return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
                        } else {
                            if (xSignifier < 0x10000000000000000000000000000) xExponent = 0;
                            else xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

                            return bytes16(
                                uint128(
                                    (xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier
                                )
                            );
                        }
                    } else {
                        if (delta > 0) {
                            xSignifier <<= 1;
                            xExponent -= 1;
                        } else if (delta < 0) {
                            ySignifier <<= 1;
                            xExponent = yExponent - 1;
                        }

                        if (delta > 112) ySignifier = 1;
                        else if (delta > 1) ySignifier = (ySignifier - 1 >> uint256(delta - 1)) + 1;
                        else if (delta < -112) xSignifier = 1;
                        else if (delta < -1) xSignifier = (xSignifier - 1 >> uint256(-delta - 1)) + 1;

                        if (xSignifier >= ySignifier) {
                            xSignifier -= ySignifier;
                        } else {
                            xSignifier = ySignifier - xSignifier;
                            xSign = ySign;
                        }

                        if (xSignifier == 0) {
                            return POSITIVE_ZERO;
                        }

                        uint256 msb = mostSignificantBit(xSignifier);

                        if (msb == 113) {
                            xSignifier = xSignifier >> 1 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                            xExponent += 1;
                        } else if (msb < 112) {
                            uint256 shift = 112 - msb;
                            if (xExponent > shift) {
                                xSignifier = xSignifier << shift & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                                xExponent -= shift;
                            } else {
                                xSignifier <<= xExponent - 1;
                                xExponent = 0;
                            }
                        } else {
                            xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                        }

                        if (xExponent == 0x7FFF) {
                            return xSign ? NEGATIVE_INFINITY : POSITIVE_INFINITY;
                        } else {
                            return bytes16(
                                uint128(
                                    (xSign ? 0x80000000000000000000000000000000 : 0) | (xExponent << 112) | xSignifier
                                )
                            );
                        }
                    }
                }
            }
        }
    }

    /**
     * Calculate x - y.  Special values behave in the following way:
     *
     * NaN - x = NaN for any x.
     * Infinity - x = Infinity for any finite x.
     * -Infinity - x = -Infinity for any finite x.
     * Infinity - -Infinity = Infinity.
     * -Infinity - Infinity = -Infinity.
     * Infinity - Infinity = -Infinity - -Infinity = NaN.
     *
     * @param x quadruple precision number
     * @param y quadruple precision number
     * @return quadruple precision number
     */
    function sub(bytes16 x, bytes16 y) internal pure returns (bytes16) {
        unchecked {
            return add(x, y ^ 0x80000000000000000000000000000000);
        }
    }

    /**
     * Calculate x * y.  Special values behave in the following way:
     *
     * NaN * x = NaN for any x.
     * Infinity * x = Infinity for any finite positive x.
     * Infinity * x = -Infinity for any finite negative x.
     * -Infinity * x = -Infinity for any finite positive x.
     * -Infinity * x = Infinity for any finite negative x.
     * Infinity * 0 = NaN.
     * -Infinity * 0 = NaN.
     * Infinity * Infinity = Infinity.
     * Infinity * -Infinity = -Infinity.
     * -Infinity * Infinity = -Infinity.
     * -Infinity * -Infinity = Infinity.
     *
     * @param x quadruple precision number
     * @param y quadruple precision number
     * @return quadruple precision number
     */
    function mul(bytes16 x, bytes16 y) internal pure returns (bytes16) {
        unchecked {
            uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
            uint256 yExponent = uint128(y) >> 112 & 0x7FFF;

            if (xExponent == 0x7FFF) {
                if (yExponent == 0x7FFF) {
                    if (x == y) return x ^ y & 0x80000000000000000000000000000000;
                    else if (x ^ y == 0x80000000000000000000000000000000) return x | y;
                    else return NaN;
                } else {
                    if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
                    else return x ^ y & 0x80000000000000000000000000000000;
                }
            } else if (yExponent == 0x7FFF) {
                if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
                else return y ^ x & 0x80000000000000000000000000000000;
            } else {
                uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (xExponent == 0) xExponent = 1;
                else xSignifier |= 0x10000000000000000000000000000;

                uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (yExponent == 0) yExponent = 1;
                else ySignifier |= 0x10000000000000000000000000000;

                xSignifier *= ySignifier;
                if (xSignifier == 0) {
                    return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO;
                }

                xExponent += yExponent;

                uint256 msb = xSignifier >= 0x200000000000000000000000000000000000000000000000000000000
                    ? 225
                    : xSignifier >= 0x100000000000000000000000000000000000000000000000000000000
                        ? 224
                        : mostSignificantBit(xSignifier);

                if (xExponent + msb < 16_496) {
                    // Underflow
                    xExponent = 0;
                    xSignifier = 0;
                } else if (xExponent + msb < 16_608) {
                    // Subnormal
                    if (xExponent < 16_496) {
                        xSignifier >>= 16_496 - xExponent;
                    } else if (xExponent > 16_496) {
                        xSignifier <<= xExponent - 16_496;
                    }
                    xExponent = 0;
                } else if (xExponent + msb > 49_373) {
                    xExponent = 0x7FFF;
                    xSignifier = 0;
                } else {
                    if (msb > 112) {
                        xSignifier >>= msb - 112;
                    } else if (msb < 112) {
                        xSignifier <<= 112 - msb;
                    }

                    xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

                    xExponent = xExponent + msb - 16_607;
                }

                return bytes16(
                    uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | xExponent << 112 | xSignifier)
                );
            }
        }
    }

    /**
     * Calculate x / y.  Special values behave in the following way:
     *
     * NaN / x = NaN for any x.
     * x / NaN = NaN for any x.
     * Infinity / x = Infinity for any finite non-negative x.
     * Infinity / x = -Infinity for any finite negative x including -0.
     * -Infinity / x = -Infinity for any finite non-negative x.
     * -Infinity / x = Infinity for any finite negative x including -0.
     * x / Infinity = 0 for any finite non-negative x.
     * x / -Infinity = -0 for any finite non-negative x.
     * x / Infinity = -0 for any finite non-negative x including -0.
     * x / -Infinity = 0 for any finite non-negative x including -0.
     *
     * Infinity / Infinity = NaN.
     * Infinity / -Infinity = -NaN.
     * -Infinity / Infinity = -NaN.
     * -Infinity / -Infinity = NaN.
     *
     * Division by zero behaves in the following way:
     *
     * x / 0 = Infinity for any finite positive x.
     * x / -0 = -Infinity for any finite positive x.
     * x / 0 = -Infinity for any finite negative x.
     * x / -0 = Infinity for any finite negative x.
     * 0 / 0 = NaN.
     * 0 / -0 = NaN.
     * -0 / 0 = NaN.
     * -0 / -0 = NaN.
     *
     * @param x quadruple precision number
     * @param y quadruple precision number
     * @return quadruple precision number
     */
    function div(bytes16 x, bytes16 y) internal pure returns (bytes16) {
        unchecked {
            uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
            uint256 yExponent = uint128(y) >> 112 & 0x7FFF;

            if (xExponent == 0x7FFF) {
                if (yExponent == 0x7FFF) return NaN;
                else return x ^ y & 0x80000000000000000000000000000000;
            } else if (yExponent == 0x7FFF) {
                if (y & 0x0000FFFFFFFFFFFFFFFFFFFFFFFFFFFF != 0) return NaN;
                else return POSITIVE_ZERO | (x ^ y) & 0x80000000000000000000000000000000;
            } else if (y & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) {
                if (x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF == 0) return NaN;
                else return POSITIVE_INFINITY | (x ^ y) & 0x80000000000000000000000000000000;
            } else {
                uint256 ySignifier = uint128(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (yExponent == 0) yExponent = 1;
                else ySignifier |= 0x10000000000000000000000000000;

                uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (xExponent == 0) {
                    if (xSignifier != 0) {
                        uint256 shift = 226 - mostSignificantBit(xSignifier);

                        xSignifier <<= shift;

                        xExponent = 1;
                        yExponent += shift - 114;
                    }
                } else {
                    xSignifier = (xSignifier | 0x10000000000000000000000000000) << 114;
                }

                xSignifier = xSignifier / ySignifier;
                if (xSignifier == 0) {
                    return (x ^ y) & 0x80000000000000000000000000000000 > 0 ? NEGATIVE_ZERO : POSITIVE_ZERO;
                }

                assert(xSignifier >= 0x1000000000000000000000000000);

                uint256 msb = xSignifier >= 0x80000000000000000000000000000
                    ? mostSignificantBit(xSignifier)
                    : xSignifier >= 0x40000000000000000000000000000
                        ? 114
                        : xSignifier >= 0x20000000000000000000000000000 ? 113 : 112;

                if (xExponent + msb > yExponent + 16_497) {
                    // Overflow
                    xExponent = 0x7FFF;
                    xSignifier = 0;
                } else if (xExponent + msb + 16_380 < yExponent) {
                    // Underflow
                    xExponent = 0;
                    xSignifier = 0;
                } else if (xExponent + msb + 16_268 < yExponent) {
                    // Subnormal
                    if (xExponent + 16_380 > yExponent) {
                        xSignifier <<= xExponent + 16_380 - yExponent;
                    } else if (xExponent + 16_380 < yExponent) {
                        xSignifier >>= yExponent - xExponent - 16_380;
                    }

                    xExponent = 0;
                } else {
                    // Normal
                    if (msb > 112) {
                        xSignifier >>= msb - 112;
                    }

                    xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

                    xExponent = xExponent + msb + 16_269 - yExponent;
                }

                return bytes16(
                    uint128(uint128((x ^ y) & 0x80000000000000000000000000000000) | xExponent << 112 | xSignifier)
                );
            }
        }
    }

    /**
     * Calculate -x.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function neg(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            return x ^ 0x80000000000000000000000000000000;
        }
    }

    /**
     * Calculate |x|.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function abs(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            return x & 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
        }
    }

    /**
     * Calculate square root of x.  Return NaN on negative x excluding -0.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function sqrt(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            if (uint128(x) > 0x80000000000000000000000000000000) {
                return NaN;
            } else {
                uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
                if (xExponent == 0x7FFF) {
                    return x;
                } else {
                    uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    if (xExponent == 0) xExponent = 1;
                    else xSignifier |= 0x10000000000000000000000000000;

                    if (xSignifier == 0) return POSITIVE_ZERO;

                    bool oddExponent = xExponent & 0x1 == 0;
                    xExponent = xExponent + 16_383 >> 1;

                    if (oddExponent) {
                        if (xSignifier >= 0x10000000000000000000000000000) {
                            xSignifier <<= 113;
                        } else {
                            uint256 msb = mostSignificantBit(xSignifier);
                            uint256 shift = (226 - msb) & 0xFE;
                            xSignifier <<= shift;
                            xExponent -= shift - 112 >> 1;
                        }
                    } else {
                        if (xSignifier >= 0x10000000000000000000000000000) {
                            xSignifier <<= 112;
                        } else {
                            uint256 msb = mostSignificantBit(xSignifier);
                            uint256 shift = (225 - msb) & 0xFE;
                            xSignifier <<= shift;
                            xExponent -= shift - 112 >> 1;
                        }
                    }

                    uint256 r = 0x10000000000000000000000000000;
                    r = (r + xSignifier / r) >> 1;
                    r = (r + xSignifier / r) >> 1;
                    r = (r + xSignifier / r) >> 1;
                    r = (r + xSignifier / r) >> 1;
                    r = (r + xSignifier / r) >> 1;
                    r = (r + xSignifier / r) >> 1;
                    r = (r + xSignifier / r) >> 1; // Seven iterations should be enough
                    uint256 r1 = xSignifier / r;
                    if (r1 < r) r = r1;

                    return bytes16(uint128(xExponent << 112 | r & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF));
                }
            }
        }
    }

    /**
     * Calculate binary logarithm of x.  Return NaN on negative x excluding -0.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function log_2(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            if (uint128(x) > 0x80000000000000000000000000000000) {
                return NaN;
            } else if (x == 0x3FFF0000000000000000000000000000) {
                return POSITIVE_ZERO;
            } else {
                uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
                if (xExponent == 0x7FFF) {
                    return x;
                } else {
                    uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    if (xExponent == 0) xExponent = 1;
                    else xSignifier |= 0x10000000000000000000000000000;

                    if (xSignifier == 0) return NEGATIVE_INFINITY;

                    bool resultNegative;
                    uint256 resultExponent = 16_495;
                    uint256 resultSignifier;

                    if (xExponent >= 0x3FFF) {
                        resultNegative = false;
                        resultSignifier = xExponent - 0x3FFF;
                        xSignifier <<= 15;
                    } else {
                        resultNegative = true;
                        if (xSignifier >= 0x10000000000000000000000000000) {
                            resultSignifier = 0x3FFE - xExponent;
                            xSignifier <<= 15;
                        } else {
                            uint256 msb = mostSignificantBit(xSignifier);
                            resultSignifier = 16_493 - msb;
                            xSignifier <<= 127 - msb;
                        }
                    }

                    if (xSignifier == 0x80000000000000000000000000000000) {
                        if (resultNegative) resultSignifier += 1;
                        uint256 shift = 112 - mostSignificantBit(resultSignifier);
                        resultSignifier <<= shift;
                        resultExponent -= shift;
                    } else {
                        uint256 bb = resultNegative ? 1 : 0;
                        while (resultSignifier < 0x10000000000000000000000000000) {
                            resultSignifier <<= 1;
                            resultExponent -= 1;

                            xSignifier *= xSignifier;
                            uint256 b = xSignifier >> 255;
                            resultSignifier += b ^ bb;
                            xSignifier >>= 127 + b;
                        }
                    }

                    return bytes16(
                        uint128(
                            (resultNegative ? 0x80000000000000000000000000000000 : 0) | resultExponent << 112
                                | resultSignifier & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF
                        )
                    );
                }
            }
        }
    }

    /**
     * Calculate natural logarithm of x.  Return NaN on negative x excluding -0.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function ln(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            return mul(log_2(x), 0x3FFE62E42FEFA39EF35793C7673007E5);
        }
    }

    /**
     * Calculate 2^x.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function pow_2(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
            uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
            uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;

            if (xExponent == 0x7FFF && xSignifier != 0) {
                return NaN;
            } else if (xExponent > 16_397) {
                return xNegative ? POSITIVE_ZERO : POSITIVE_INFINITY;
            } else if (xExponent < 16_255) {
                return 0x3FFF0000000000000000000000000000;
            } else {
                if (xExponent == 0) xExponent = 1;
                else xSignifier |= 0x10000000000000000000000000000;

                if (xExponent > 16_367) {
                    xSignifier <<= xExponent - 16_367;
                } else if (xExponent < 16_367) {
                    xSignifier >>= 16_367 - xExponent;
                }

                if (xNegative && xSignifier > 0x406E00000000000000000000000000000000) {
                    return POSITIVE_ZERO;
                }

                if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
                    return POSITIVE_INFINITY;
                }

                uint256 resultExponent = xSignifier >> 128;
                xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (xNegative && xSignifier != 0) {
                    xSignifier = ~xSignifier;
                    resultExponent += 1;
                }

                uint256 resultSignifier = 0x80000000000000000000000000000000;
                if (xSignifier & 0x80000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
                }
                if (xSignifier & 0x40000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
                }
                if (xSignifier & 0x20000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
                }
                if (xSignifier & 0x10000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
                }
                if (xSignifier & 0x8000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
                }
                if (xSignifier & 0x4000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
                }
                if (xSignifier & 0x1000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
                }
                if (xSignifier & 0x800000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
                }
                if (xSignifier & 0x400000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
                }
                if (xSignifier & 0x200000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
                }
                if (xSignifier & 0x100000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
                }
                if (xSignifier & 0x80000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
                }
                if (xSignifier & 0x40000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
                }
                if (xSignifier & 0x20000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000162E525EE054754457D5995292026 >> 128;
                }
                if (xSignifier & 0x10000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
                }
                if (xSignifier & 0x8000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
                }
                if (xSignifier & 0x4000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000162E43F4F831060E02D839A9D16D >> 128;
                }
                if (xSignifier & 0x1000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
                }
                if (xSignifier & 0x800000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
                }
                if (xSignifier & 0x400000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
                }
                if (xSignifier & 0x200000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
                }
                if (xSignifier & 0x100000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
                }
                if (xSignifier & 0x80000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
                }
                if (xSignifier & 0x40000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
                }
                if (xSignifier & 0x20000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
                }
                if (xSignifier & 0x10000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
                }
                if (xSignifier & 0x8000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
                }
                if (xSignifier & 0x4000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
                }
                if (xSignifier & 0x1000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
                }
                if (xSignifier & 0x800000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
                }
                if (xSignifier & 0x400000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
                }
                if (xSignifier & 0x200000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000162E42FEFB2FED257559BDAA >> 128;
                }
                if (xSignifier & 0x100000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
                }
                if (xSignifier & 0x80000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
                }
                if (xSignifier & 0x40000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
                }
                if (xSignifier & 0x20000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
                }
                if (xSignifier & 0x10000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000B17217F7D20CF927C8E94C >> 128;
                }
                if (xSignifier & 0x8000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
                }
                if (xSignifier & 0x4000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000002C5C85FDF477B662B26945 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000162E42FEFA3AE53369388C >> 128;
                }
                if (xSignifier & 0x1000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000B17217F7D1D351A389D40 >> 128;
                }
                if (xSignifier & 0x800000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
                }
                if (xSignifier & 0x400000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
                }
                if (xSignifier & 0x200000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000162E42FEFA39FE95583C2 >> 128;
                }
                if (xSignifier & 0x100000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
                }
                if (xSignifier & 0x80000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
                }
                if (xSignifier & 0x40000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000002C5C85FDF473E242EA38 >> 128;
                }
                if (xSignifier & 0x20000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000162E42FEFA39F02B772C >> 128;
                }
                if (xSignifier & 0x10000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
                }
                if (xSignifier & 0x8000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
                }
                if (xSignifier & 0x4000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000002C5C85FDF473DEA871F >> 128;
                }
                if (xSignifier & 0x2000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000162E42FEFA39EF44D91 >> 128;
                }
                if (xSignifier & 0x1000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000B17217F7D1CF79E949 >> 128;
                }
                if (xSignifier & 0x800000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
                }
                if (xSignifier & 0x400000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
                }
                if (xSignifier & 0x200000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000162E42FEFA39EF366F >> 128;
                }
                if (xSignifier & 0x100000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000B17217F7D1CF79AFA >> 128;
                }
                if (xSignifier & 0x80000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
                }
                if (xSignifier & 0x40000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
                }
                if (xSignifier & 0x20000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000162E42FEFA39EF358 >> 128;
                }
                if (xSignifier & 0x10000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000B17217F7D1CF79AB >> 128;
                }
                if (xSignifier & 0x8000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5 >> 128;
                }
                if (xSignifier & 0x4000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000002C5C85FDF473DE6A >> 128;
                }
                if (xSignifier & 0x2000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000162E42FEFA39EF34 >> 128;
                }
                if (xSignifier & 0x1000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000B17217F7D1CF799 >> 128;
                }
                if (xSignifier & 0x800000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000058B90BFBE8E7BCC >> 128;
                }
                if (xSignifier & 0x400000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000002C5C85FDF473DE5 >> 128;
                }
                if (xSignifier & 0x200000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000162E42FEFA39EF2 >> 128;
                }
                if (xSignifier & 0x100000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000B17217F7D1CF78 >> 128;
                }
                if (xSignifier & 0x80000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000058B90BFBE8E7BB >> 128;
                }
                if (xSignifier & 0x40000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000002C5C85FDF473DD >> 128;
                }
                if (xSignifier & 0x20000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000162E42FEFA39EE >> 128;
                }
                if (xSignifier & 0x10000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000B17217F7D1CF6 >> 128;
                }
                if (xSignifier & 0x8000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000058B90BFBE8E7A >> 128;
                }
                if (xSignifier & 0x4000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000002C5C85FDF473C >> 128;
                }
                if (xSignifier & 0x2000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000162E42FEFA39D >> 128;
                }
                if (xSignifier & 0x1000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000B17217F7D1CE >> 128;
                }
                if (xSignifier & 0x800000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000058B90BFBE8E6 >> 128;
                }
                if (xSignifier & 0x400000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000002C5C85FDF472 >> 128;
                }
                if (xSignifier & 0x200000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000162E42FEFA38 >> 128;
                }
                if (xSignifier & 0x100000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000B17217F7D1B >> 128;
                }
                if (xSignifier & 0x80000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000058B90BFBE8D >> 128;
                }
                if (xSignifier & 0x40000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000002C5C85FDF46 >> 128;
                }
                if (xSignifier & 0x20000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000162E42FEFA2 >> 128;
                }
                if (xSignifier & 0x10000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000B17217F7D0 >> 128;
                }
                if (xSignifier & 0x8000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000058B90BFBE7 >> 128;
                }
                if (xSignifier & 0x4000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000002C5C85FDF3 >> 128;
                }
                if (xSignifier & 0x2000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000162E42FEF9 >> 128;
                }
                if (xSignifier & 0x1000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000B17217F7C >> 128;
                }
                if (xSignifier & 0x800000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000058B90BFBD >> 128;
                }
                if (xSignifier & 0x400000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000002C5C85FDE >> 128;
                }
                if (xSignifier & 0x200000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000162E42FEE >> 128;
                }
                if (xSignifier & 0x100000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000B17217F6 >> 128;
                }
                if (xSignifier & 0x80000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000058B90BFA >> 128;
                }
                if (xSignifier & 0x40000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000002C5C85FC >> 128;
                }
                if (xSignifier & 0x20000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000162E42FD >> 128;
                }
                if (xSignifier & 0x10000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000B17217E >> 128;
                }
                if (xSignifier & 0x8000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000058B90BE >> 128;
                }
                if (xSignifier & 0x4000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000002C5C85E >> 128;
                }
                if (xSignifier & 0x2000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000162E42E >> 128;
                }
                if (xSignifier & 0x1000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000B17216 >> 128;
                }
                if (xSignifier & 0x800000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000058B90A >> 128;
                }
                if (xSignifier & 0x400000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000002C5C84 >> 128;
                }
                if (xSignifier & 0x200000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000162E41 >> 128;
                }
                if (xSignifier & 0x100000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000B1720 >> 128;
                }
                if (xSignifier & 0x80000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000058B8F >> 128;
                }
                if (xSignifier & 0x40000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000002C5C7 >> 128;
                }
                if (xSignifier & 0x20000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000162E3 >> 128;
                }
                if (xSignifier & 0x10000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000B171 >> 128;
                }
                if (xSignifier & 0x8000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000058B8 >> 128;
                }
                if (xSignifier & 0x4000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000002C5B >> 128;
                }
                if (xSignifier & 0x2000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000162D >> 128;
                }
                if (xSignifier & 0x1000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000B16 >> 128;
                }
                if (xSignifier & 0x800 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000058A >> 128;
                }
                if (xSignifier & 0x400 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000002C4 >> 128;
                }
                if (xSignifier & 0x200 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000161 >> 128;
                }
                if (xSignifier & 0x100 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000000B0 >> 128;
                }
                if (xSignifier & 0x80 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000057 >> 128;
                }
                if (xSignifier & 0x40 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000002B >> 128;
                }
                if (xSignifier & 0x20 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000015 >> 128;
                }
                if (xSignifier & 0x10 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000000A >> 128;
                }
                if (xSignifier & 0x8 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000004 >> 128;
                }
                if (xSignifier & 0x4 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000001 >> 128;
                }

                if (!xNegative) {
                    resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    resultExponent += 0x3FFF;
                } else if (resultExponent <= 0x3FFE) {
                    resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    resultExponent = 0x3FFF - resultExponent;
                } else {
                    resultSignifier = resultSignifier >> resultExponent - 16_367;
                    resultExponent = 0;
                }

                return bytes16(uint128(resultExponent << 112 | resultSignifier));
            }
        }
    }

    function pow_2ToUInt(bytes16 x) internal pure returns (uint256) {
        unchecked {
            bool xNegative = uint128(x) > 0x80000000000000000000000000000000;
            uint256 xExponent = uint128(x) >> 112 & 0x7FFF;
            uint256 xSignifier = uint128(x) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
            uint128 y;
            if (xExponent == 0x7FFF && xSignifier != 0) {
                return toUInt(NaN);
            } else if (xExponent > 16_397) {
                return xNegative ? toUInt(POSITIVE_ZERO) : toUInt(POSITIVE_INFINITY);
            } else if (xExponent < 16_255) {
                return toUInt(0x3FFF0000000000000000000000000000);
            } else {
                if (xExponent == 0) xExponent = 1;
                else xSignifier |= 0x10000000000000000000000000000;

                if (xExponent > 16_367) {
                    xSignifier <<= xExponent - 16_367;
                } else if (xExponent < 16_367) {
                    xSignifier >>= 16_367 - xExponent;
                }

                if (xNegative && xSignifier > 0x406E00000000000000000000000000000000) {
                    return toUInt(POSITIVE_ZERO);
                }

                if (!xNegative && xSignifier > 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
                    return toUInt(POSITIVE_INFINITY);
                }

                uint256 resultExponent = xSignifier >> 128;
                xSignifier &= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                if (xNegative && xSignifier != 0) {
                    xSignifier = ~xSignifier;
                    resultExponent += 1;
                }

                uint256 resultSignifier = 0x80000000000000000000000000000000;
                if (xSignifier & 0x80000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
                }
                if (xSignifier & 0x40000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
                }
                if (xSignifier & 0x20000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
                }
                if (xSignifier & 0x10000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
                }
                if (xSignifier & 0x8000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
                }
                if (xSignifier & 0x4000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
                }
                if (xSignifier & 0x1000000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
                }
                if (xSignifier & 0x800000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
                }
                if (xSignifier & 0x400000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
                }
                if (xSignifier & 0x200000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
                }
                if (xSignifier & 0x100000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
                }
                if (xSignifier & 0x80000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
                }
                if (xSignifier & 0x40000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
                }
                if (xSignifier & 0x20000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000162E525EE054754457D5995292026 >> 128;
                }
                if (xSignifier & 0x10000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
                }
                if (xSignifier & 0x8000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
                }
                if (xSignifier & 0x4000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000162E43F4F831060E02D839A9D16D >> 128;
                }
                if (xSignifier & 0x1000000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
                }
                if (xSignifier & 0x800000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
                }
                if (xSignifier & 0x400000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
                }
                if (xSignifier & 0x200000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
                }
                if (xSignifier & 0x100000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
                }
                if (xSignifier & 0x80000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
                }
                if (xSignifier & 0x40000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
                }
                if (xSignifier & 0x20000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
                }
                if (xSignifier & 0x10000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
                }
                if (xSignifier & 0x8000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
                }
                if (xSignifier & 0x4000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
                }
                if (xSignifier & 0x1000000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
                }
                if (xSignifier & 0x800000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
                }
                if (xSignifier & 0x400000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
                }
                if (xSignifier & 0x200000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000162E42FEFB2FED257559BDAA >> 128;
                }
                if (xSignifier & 0x100000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
                }
                if (xSignifier & 0x80000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
                }
                if (xSignifier & 0x40000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
                }
                if (xSignifier & 0x20000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
                }
                if (xSignifier & 0x10000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000B17217F7D20CF927C8E94C >> 128;
                }
                if (xSignifier & 0x8000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
                }
                if (xSignifier & 0x4000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000002C5C85FDF477B662B26945 >> 128;
                }
                if (xSignifier & 0x2000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000162E42FEFA3AE53369388C >> 128;
                }
                if (xSignifier & 0x1000000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000B17217F7D1D351A389D40 >> 128;
                }
                if (xSignifier & 0x800000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
                }
                if (xSignifier & 0x400000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
                }
                if (xSignifier & 0x200000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000162E42FEFA39FE95583C2 >> 128;
                }
                if (xSignifier & 0x100000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
                }
                if (xSignifier & 0x80000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
                }
                if (xSignifier & 0x40000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000002C5C85FDF473E242EA38 >> 128;
                }
                if (xSignifier & 0x20000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000162E42FEFA39F02B772C >> 128;
                }
                if (xSignifier & 0x10000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
                }
                if (xSignifier & 0x8000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
                }
                if (xSignifier & 0x4000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000002C5C85FDF473DEA871F >> 128;
                }
                if (xSignifier & 0x2000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000162E42FEFA39EF44D91 >> 128;
                }
                if (xSignifier & 0x1000000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000B17217F7D1CF79E949 >> 128;
                }
                if (xSignifier & 0x800000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
                }
                if (xSignifier & 0x400000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
                }
                if (xSignifier & 0x200000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000162E42FEFA39EF366F >> 128;
                }
                if (xSignifier & 0x100000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000B17217F7D1CF79AFA >> 128;
                }
                if (xSignifier & 0x80000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
                }
                if (xSignifier & 0x40000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
                }
                if (xSignifier & 0x20000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000162E42FEFA39EF358 >> 128;
                }
                if (xSignifier & 0x10000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000B17217F7D1CF79AB >> 128;
                }
                if (xSignifier & 0x8000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000058B90BFBE8E7BCD5 >> 128;
                }
                if (xSignifier & 0x4000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000002C5C85FDF473DE6A >> 128;
                }
                if (xSignifier & 0x2000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000162E42FEFA39EF34 >> 128;
                }
                if (xSignifier & 0x1000000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000B17217F7D1CF799 >> 128;
                }
                if (xSignifier & 0x800000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000058B90BFBE8E7BCC >> 128;
                }
                if (xSignifier & 0x400000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000002C5C85FDF473DE5 >> 128;
                }
                if (xSignifier & 0x200000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000162E42FEFA39EF2 >> 128;
                }
                if (xSignifier & 0x100000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000B17217F7D1CF78 >> 128;
                }
                if (xSignifier & 0x80000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000058B90BFBE8E7BB >> 128;
                }
                if (xSignifier & 0x40000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000002C5C85FDF473DD >> 128;
                }
                if (xSignifier & 0x20000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000162E42FEFA39EE >> 128;
                }
                if (xSignifier & 0x10000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000B17217F7D1CF6 >> 128;
                }
                if (xSignifier & 0x8000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000058B90BFBE8E7A >> 128;
                }
                if (xSignifier & 0x4000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000002C5C85FDF473C >> 128;
                }
                if (xSignifier & 0x2000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000162E42FEFA39D >> 128;
                }
                if (xSignifier & 0x1000000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000B17217F7D1CE >> 128;
                }
                if (xSignifier & 0x800000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000058B90BFBE8E6 >> 128;
                }
                if (xSignifier & 0x400000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000002C5C85FDF472 >> 128;
                }
                if (xSignifier & 0x200000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000162E42FEFA38 >> 128;
                }
                if (xSignifier & 0x100000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000B17217F7D1B >> 128;
                }
                if (xSignifier & 0x80000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000058B90BFBE8D >> 128;
                }
                if (xSignifier & 0x40000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000002C5C85FDF46 >> 128;
                }
                if (xSignifier & 0x20000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000162E42FEFA2 >> 128;
                }
                if (xSignifier & 0x10000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000B17217F7D0 >> 128;
                }
                if (xSignifier & 0x8000000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000058B90BFBE7 >> 128;
                }
                if (xSignifier & 0x4000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000002C5C85FDF3 >> 128;
                }
                if (xSignifier & 0x2000000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000162E42FEF9 >> 128;
                }
                if (xSignifier & 0x1000000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000B17217F7C >> 128;
                }
                if (xSignifier & 0x800000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000058B90BFBD >> 128;
                }
                if (xSignifier & 0x400000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000002C5C85FDE >> 128;
                }
                if (xSignifier & 0x200000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000162E42FEE >> 128;
                }
                if (xSignifier & 0x100000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000B17217F6 >> 128;
                }
                if (xSignifier & 0x80000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000058B90BFA >> 128;
                }
                if (xSignifier & 0x40000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000002C5C85FC >> 128;
                }
                if (xSignifier & 0x20000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000162E42FD >> 128;
                }
                if (xSignifier & 0x10000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000B17217E >> 128;
                }
                if (xSignifier & 0x8000000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000058B90BE >> 128;
                }
                if (xSignifier & 0x4000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000002C5C85E >> 128;
                }
                if (xSignifier & 0x2000000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000162E42E >> 128;
                }
                if (xSignifier & 0x1000000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000B17216 >> 128;
                }
                if (xSignifier & 0x800000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000058B90A >> 128;
                }
                if (xSignifier & 0x400000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000002C5C84 >> 128;
                }
                if (xSignifier & 0x200000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000162E41 >> 128;
                }
                if (xSignifier & 0x100000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000B1720 >> 128;
                }
                if (xSignifier & 0x80000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000058B8F >> 128;
                }
                if (xSignifier & 0x40000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000002C5C7 >> 128;
                }
                if (xSignifier & 0x20000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000162E3 >> 128;
                }
                if (xSignifier & 0x10000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000B171 >> 128;
                }
                if (xSignifier & 0x8000 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000058B8 >> 128;
                }
                if (xSignifier & 0x4000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000002C5B >> 128;
                }
                if (xSignifier & 0x2000 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000162D >> 128;
                }
                if (xSignifier & 0x1000 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000B16 >> 128;
                }
                if (xSignifier & 0x800 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000058A >> 128;
                }
                if (xSignifier & 0x400 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000002C4 >> 128;
                }
                if (xSignifier & 0x200 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000161 >> 128;
                }
                if (xSignifier & 0x100 > 0) {
                    resultSignifier = resultSignifier * 0x1000000000000000000000000000000B0 >> 128;
                }
                if (xSignifier & 0x80 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000057 >> 128;
                }
                if (xSignifier & 0x40 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000002B >> 128;
                }
                if (xSignifier & 0x20 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000015 >> 128;
                }
                if (xSignifier & 0x10 > 0) {
                    resultSignifier = resultSignifier * 0x10000000000000000000000000000000A >> 128;
                }
                if (xSignifier & 0x8 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000004 >> 128;
                }
                if (xSignifier & 0x4 > 0) {
                    resultSignifier = resultSignifier * 0x100000000000000000000000000000001 >> 128;
                }

                if (!xNegative) {
                    resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    resultExponent += 0x3FFF;
                } else if (resultExponent <= 0x3FFE) {
                    resultSignifier = resultSignifier >> 15 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
                    resultExponent = 0x3FFF - resultExponent;
                } else {
                    resultSignifier = resultSignifier >> resultExponent - 16_367;
                    resultExponent = 0;
                }

                y = uint128(resultExponent << 112 | resultSignifier); 

                uint256 exponent = y >> 112 & 0x7FFF;

                if (exponent < 16_383) return 0; // Underflow

                require(y < 0x80000000000000000000000000000000); // Negative

                require(exponent <= 16_638); // Overflow
                uint256 result = uint256(y) & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF | 0x10000000000000000000000000000;

                if (exponent < 16_495) result >>= 16_495 - exponent;
                else if (exponent > 16_495) result <<= exponent - 16_495;

                return result;
            }
           
        }
    }

    /**
     * Calculate e^x.
     *
     * @param x quadruple precision number
     * @return quadruple precision number
     */
    function exp(bytes16 x) internal pure returns (bytes16) {
        unchecked {
            return pow_2(mul(x, 0x3FFF71547652B82FE1777D0FFDA0D23A));
        }
    }

    /**
     * Get index of the most significant non-zero bit in binary representation of
     * x.  Reverts if x is zero.
     *
     * @return index of the most significant non-zero bit in binary representation
     *         of x
     */
    function mostSignificantBit(uint256 x) private pure returns (uint256) {
        unchecked {
            require(x > 0);

            uint256 result = 0;

            if (x >= 0x100000000000000000000000000000000) {
                x >>= 128;
                result += 128;
            }
            if (x >= 0x10000000000000000) {
                x >>= 64;
                result += 64;
            }
            if (x >= 0x100000000) {
                x >>= 32;
                result += 32;
            }
            if (x >= 0x10000) {
                x >>= 16;
                result += 16;
            }
            if (x >= 0x100) {
                x >>= 8;
                result += 8;
            }
            if (x >= 0x10) {
                x >>= 4;
                result += 4;
            }
            if (x >= 0x4) {
                x >>= 2;
                result += 2;
            }
            if (x >= 0x2) result += 1; // No need to shift x anymore

            return result;
        }
    }

    //////////////////// EXTENSIONS ////////////////////

    /**
     * Raises x (ABDK quadruple precision number) to the power of y (basic unsigned integer)
     * using the famous algorithm "exponentiation by squaring".
     *
     * @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
     */
    function powu(bytes16 x, uint256 y) internal pure returns (bytes16 result) {
        // Calculate the first iteration of the loop in advance.
        bytes16 uUint = fromUInt(1);
        result = y & 1 > 0 ? x : uUint;

        // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
        for (y >>= 1; y > 0; y >>= 1) {
            x = mul(x, x);

            // Equivalent to "y % 2 == 1" but faster.
            if (y & 1 > 0) {
                result = mul(result, x);
            }
        }
    }
}

File 40 of 49 : LibBytes.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title LibBytes
 * @author Publius
 * @notice Contains byte operations used during storage reads & writes.
 *
 * {LibBytes} tightly packs an array of `uint256` values into `n / 2` storage
 * slots, where `n` is number of items to pack.
 *
 * Each value must be `<= type(uint128).max` in order pack properly.
 */
library LibBytes {
    uint256 constant MAX_UINT128 = 340_282_366_920_938_463_463_374_607_431_768_211_455; // type(uint128).max

    /**
     * @dev Store packed uint128 `reserves` starting at storage position `slot`.
     * Balances are passed as an uint256[], but values must be <= max uint128
     * to allow for packing into a single storage slot.
     */
    function storeUint128(bytes32 slot, uint256[] memory reserves) internal {
        // Shortcut: two reserves can be packed into one slot without a loop
        if (reserves.length == 2) {
            require(reserves[0] <= MAX_UINT128, "ByteStorage: too large");
            require(reserves[1] <= MAX_UINT128, "ByteStorage: too large");
            assembly {
                sstore(slot, add(mload(add(reserves, 32)), shl(128, mload(add(reserves, 64)))))
            }
        } else {
            uint256 maxI = reserves.length / 2; // number of fully-packed slots
            uint256 iByte; // byte offset of the current reserve
            for (uint256 i; i < maxI; ++i) {
                require(reserves[2 * i] <= MAX_UINT128, "ByteStorage: too large");
                require(reserves[2 * i + 1] <= MAX_UINT128, "ByteStorage: too large");
                iByte = i * 64;
                assembly {
                    sstore(
                        add(slot, i),
                        add(mload(add(reserves, add(iByte, 32))), shl(128, mload(add(reserves, add(iByte, 64)))))
                    )
                }
            }
            // If there is an odd number of reserves, create a slot with the last reserve
            // Since `i < maxI` above, the next byte offset `maxI * 64`
            // Equivalent to "reserves.length % 2 == 1", but cheaper.
            if (reserves.length & 1 == 1) {
                require(reserves[reserves.length - 1] <= MAX_UINT128, "ByteStorage: too large");
                iByte = maxI * 64;
                assembly {
                    sstore(
                        add(slot, maxI),
                        add(mload(add(reserves, add(iByte, 32))), shr(128, shl(128, sload(add(slot, maxI)))))
                    )
                }
            }
        }
    }

    /**
     * @dev Read `n` packed uint128 reserves at storage position `slot`.
     */
    function readUint128(bytes32 slot, uint256 n) internal view returns (uint256[] memory reserves) {
        // Initialize array with length `n`, fill it in via assembly
        reserves = new uint256[](n);

        // Shortcut: two reserves can be quickly unpacked from one slot
        if (n == 2) {
            assembly {
                mstore(add(reserves, 32), shr(128, shl(128, sload(slot))))
                mstore(add(reserves, 64), shr(128, sload(slot)))
            }
            return reserves;
        }

        uint256 iByte;
        for (uint256 i = 1; i <= n; ++i) {
            // `iByte` is the byte position for the current slot:
            // i        1 2 3 4 5 6
            // iByte    0 0 1 1 2 2
            iByte = (i - 1) / 2;
            // Equivalent to "i % 2 == 1", but cheaper.
            if (i & 1 == 1) {
                assembly {
                    mstore(
                        // store at index i * 32; i = 0 is skipped by loop
                        add(reserves, mul(i, 32)),
                        shr(128, shl(128, sload(add(slot, iByte))))
                    )
                }
            } else {
                assembly {
                    mstore(add(reserves, mul(i, 32)), shr(128, sload(add(slot, iByte))))
                }
            }
        }
    }
}

File 41 of 49 : LibBytes16.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title LibBytes16
 * @author Publius
 * @notice Contains byte operations used during storage reads & writes for Pumps.
 *
 * {LibBytes16} tightly packs an array of `bytes16` values into `n / 2` storage
 * slots, where `n` is number of items to pack.
 */
library LibBytes16 {
    /**
     * @dev Store packed bytes16 `reserves` starting at storage position `slot`.
     */
    function storeBytes16(bytes32 slot, bytes16[] memory reserves) internal {
        // Shortcut: two reserves can be packed into one slot without a loop
        if (reserves.length == 2) {
            assembly {
                sstore(slot, add(mload(add(reserves, 32)), shr(128, mload(add(reserves, 64)))))
            }
        } else {
            uint256 maxI = reserves.length / 2; // number of fully-packed slots
            uint256 iByte; // byte offset of the current reserve
            for (uint256 i; i < maxI; ++i) {
                iByte = i * 64;
                assembly {
                    sstore(
                        add(slot, i),
                        add(mload(add(reserves, add(iByte, 32))), shr(128, mload(add(reserves, add(iByte, 64)))))
                    )
                }
            }
            // If there is an odd number of reserves, create a slot with the last reserve
            // Since `i < maxI` above, the next byte offset `maxI * 64`
            // Equivalent to "reserves.length % 2 == 1", but cheaper.
            if (reserves.length & 1 == 1) {
                iByte = maxI * 64;
                assembly {
                    sstore(
                        add(slot, maxI),
                        add(mload(add(reserves, add(iByte, 32))), shr(128, shl(128, sload(add(slot, maxI)))))
                    )
                }
            }
        }
    }

    /**
     * @dev Read `n` packed uint128 reserves at storage position `slot`.
     */
    function readBytes16(bytes32 slot, uint256 n) internal view returns (bytes16[] memory reserves) {
        // Initialize array with length `n`, fill it in via assembly
        reserves = new bytes16[](n);

        // Shortcut: two reserves can be quickly unpacked from one slot
        if (n == 2) {
            assembly {
                mstore(add(reserves, 32), sload(slot))
                mstore(add(reserves, 64), shl(128, sload(slot)))
            }
            return reserves;
        }

        uint256 iByte;
        for (uint256 i = 1; i <= n; ++i) {
            // `iByte` is the byte position for the current slot:
            // i        1 2 3 4 5 6
            // iByte    0 0 1 1 2 2
            iByte = (i - 1) / 2;
            // Equivalent to "i % 2 == 1" but cheaper.
            if (i & 1 == 1) {
                assembly {
                    mstore(
                        // store at index i * 32; i = 0 is skipped by loop
                        add(reserves, mul(i, 32)),
                        sload(add(slot, iByte))
                    )
                }
            } else {
                assembly {
                    mstore(add(reserves, mul(i, 32)), shl(128, sload(add(slot, iByte))))
                }
            }
        }
    }
}

File 42 of 49 : LibClone.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/// @notice Minimal proxy library.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibClone.sol)
/// @author Minimal proxy by 0age (https://github.com/0age)
/// @author Clones with immutable args by wighawag, zefram.eth, Saw-mon & Natalie
/// (https://github.com/Saw-mon-and-Natalie/clones-with-immutable-args)
///
/// @dev Minimal proxy:
/// Although the sw0nt pattern saves 5 gas over the erc-1167 pattern during runtime,
/// it is not supported out-of-the-box on Etherscan. Hence, we choose to use the 0age pattern,
/// which saves 4 gas over the erc-1167 pattern during runtime, and has the smallest bytecode.
///
/// @dev Clones with immutable args (CWIA):
/// The implementation of CWIA here implements a `receive()` method that emits the
/// `ReceiveETH(uint256)` event. This skips the `DELEGATECALL` when there is no calldata,
/// enabling us to accept hard gas-capped `sends` & `transfers` for maximum backwards
/// composability. The minimal proxy implementation does not offer this feature.
library LibClone {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unable to deploy the clone.
    error DeploymentFailed();

    /// @dev The salt must start with either the zero address or the caller.
    error SaltDoesNotStartWithCaller();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  MINIMAL PROXY OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a clone of `implementation`.
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * --------------------------------------------------------------------------+
             * CREATION (9 bytes)                                                        |
             * --------------------------------------------------------------------------|
             * Opcode     | Mnemonic          | Stack     | Memory                       |
             * --------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize     | r         |                              |
             * 3d         | RETURNDATASIZE    | 0 r       |                              |
             * 81         | DUP2              | r 0 r     |                              |
             * 60 offset  | PUSH1 offset      | o r 0 r   |                              |
             * 3d         | RETURNDATASIZE    | 0 o r 0 r |                              |
             * 39         | CODECOPY          | 0 r       | [0..runSize): runtime code   |
             * f3         | RETURN            |           | [0..runSize): runtime code   |
             * --------------------------------------------------------------------------|
             * RUNTIME (44 bytes)                                                        |
             * --------------------------------------------------------------------------|
             * Opcode  | Mnemonic       | Stack                  | Memory                |
             * --------------------------------------------------------------------------|
             *                                                                           |
             * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: |
             * 3d      | RETURNDATASIZE | 0                      |                       |
             * 3d      | RETURNDATASIZE | 0 0                    |                       |
             * 3d      | RETURNDATASIZE | 0 0 0                  |                       |
             * 3d      | RETURNDATASIZE | 0 0 0 0                |                       |
             *                                                                           |
             * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: |
             * 36      | CALLDATASIZE   | cds 0 0 0 0            |                       |
             * 3d      | RETURNDATASIZE | 0 cds 0 0 0 0          |                       |
             * 3d      | RETURNDATASIZE | 0 0 cds 0 0 0 0        |                       |
             * 37      | CALLDATACOPY   | 0 0 0 0                | [0..cds): calldata    |
             *                                                                           |
             * ::: delegate call to the implementation contract :::::::::::::::::::::::: |
             * 36      | CALLDATASIZE   | cds 0 0 0 0            | [0..cds): calldata    |
             * 3d      | RETURNDATASIZE | 0 cds 0 0 0 0          | [0..cds): calldata    |
             * 73 addr | PUSH20 addr    | addr 0 cds 0 0 0 0     | [0..cds): calldata    |
             * 5a      | GAS            | gas addr 0 cds 0 0 0 0 | [0..cds): calldata    |
             * f4      | DELEGATECALL   | success 0 0            | [0..cds): calldata    |
             *                                                                           |
             * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: |
             * 3d      | RETURNDATASIZE | rds success 0 0        | [0..cds): calldata    |
             * 3d      | RETURNDATASIZE | rds rds success 0 0    | [0..cds): calldata    |
             * 93      | SWAP4          | 0 rds success 0 rds    | [0..cds): calldata    |
             * 80      | DUP1           | 0 0 rds success 0 rds  | [0..cds): calldata    |
             * 3e      | RETURNDATACOPY | success 0 rds          | [0..rds): returndata  |
             *                                                                           |
             * 60 0x2a | PUSH1 0x2a     | 0x2a success 0 rds     | [0..rds): returndata  |
             * 57      | JUMPI          | 0 rds                  | [0..rds): returndata  |
             *                                                                           |
             * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * fd      | REVERT         |                        | [0..rds): returndata  |
             *                                                                           |
             * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b      | JUMPDEST       | 0 rds                  | [0..rds): returndata  |
             * f3      | RETURN         |                        | [0..rds): returndata  |
             * --------------------------------------------------------------------------+
             */

            mstore(0x21, 0x5af43d3d93803e602a57fd5bf3)
            mstore(0x14, implementation)
            mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            instance := create(0, 0x0c, 0x35)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x21, 0)
            // If `instance` is zero, revert.
            if iszero(instance) {
                // Store the function selector of `DeploymentFailed()`.
                mstore(0x00, 0x30116425)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic clone of `implementation` with `salt`.
    function cloneDeterministic(address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x21, 0x5af43d3d93803e602a57fd5bf3)
            mstore(0x14, implementation)
            mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            instance := create2(0, 0x0c, 0x35, salt)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x21, 0)
            // If `instance` is zero, revert.
            if iszero(instance) {
                // Store the function selector of `DeploymentFailed()`.
                mstore(0x00, 0x30116425)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns the initialization code hash of the clone of `implementation`.
    /// Used for mining vanity addresses with create2crunch.
    function initCodeHash(address implementation) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x21, 0x5af43d3d93803e602a57fd5bf3)
            mstore(0x14, implementation)
            mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            hash := keccak256(0x0c, 0x35)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x21, 0)
        }
    }

    /// @dev Returns the address of the deterministic clone of `implementation`,
    /// with `salt` by `deployer`.
    function predictDeterministicAddress(address implementation, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        bytes32 hash = initCodeHash(implementation);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*           CLONES WITH IMMUTABLE ARGS OPERATIONS            */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a minimal proxy with `implementation`,
    /// using immutable arguments encoded in `data`.
    function clone(address implementation, bytes memory data) internal returns (address instance) {
        assembly {
            // Compute the boundaries of the data and cache the memory slots around it.
            let mBefore3 := mload(sub(data, 0x60))
            let mBefore2 := mload(sub(data, 0x40))
            let mBefore1 := mload(sub(data, 0x20))
            let dataLength := mload(data)
            let dataEnd := add(add(data, 0x20), dataLength)
            let mAfter1 := mload(dataEnd)

            // +2 bytes for telling how much data there is appended to the call.
            let extraLength := add(dataLength, 2)
            // The `creationSize` is `extraLength + 108`
            // The `runSize` is `creationSize - 10`.

            /**
             * ---------------------------------------------------------------------------------------------------+
             * CREATION (10 bytes)                                                                                |
             * ---------------------------------------------------------------------------------------------------|
             * Opcode     | Mnemonic          | Stack     | Memory                                                |
             * ---------------------------------------------------------------------------------------------------|
             * 61 runSize | PUSH2 runSize     | r         |                                                       |
             * 3d         | RETURNDATASIZE    | 0 r       |                                                       |
             * 81         | DUP2              | r 0 r     |                                                       |
             * 60 offset  | PUSH1 offset      | o r 0 r   |                                                       |
             * 3d         | RETURNDATASIZE    | 0 o r 0 r |                                                       |
             * 39         | CODECOPY          | 0 r       | [0..runSize): runtime code                            |
             * f3         | RETURN            |           | [0..runSize): runtime code                            |
             * ---------------------------------------------------------------------------------------------------|
             * RUNTIME (98 bytes + extraLength)                                                                   |
             * ---------------------------------------------------------------------------------------------------|
             * Opcode   | Mnemonic       | Stack                    | Memory                                      |
             * ---------------------------------------------------------------------------------------------------|
             *                                                                                                    |
             * ::: if no calldata, emit event & return w/o `DELEGATECALL` ::::::::::::::::::::::::::::::::::::::: |
             * 36       | CALLDATASIZE   | cds                      |                                             |
             * 60 0x2c  | PUSH1 0x2c     | 0x2c cds                 |                                             |
             * 57       | JUMPI          |                          |                                             |
             * 34       | CALLVALUE      | cv                       |                                             |
             * 3d       | RETURNDATASIZE | 0 cv                     |                                             |
             * 52       | MSTORE         |                          | [0..0x20): callvalue                        |
             * 7f sig   | PUSH32 0x9e..  | sig                      | [0..0x20): callvalue                        |
             * 59       | MSIZE          | 0x20 sig                 | [0..0x20): callvalue                        |
             * 3d       | RETURNDATASIZE | 0 0x20 sig               | [0..0x20): callvalue                        |
             * a1       | LOG1           |                          | [0..0x20): callvalue                        |
             * 00       | STOP           |                          | [0..0x20): callvalue                        |
             * 5b       | JUMPDEST       |                          |                                             |
             *                                                                                                    |
             * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36       | CALLDATASIZE   | cds                      |                                             |
             * 3d       | RETURNDATASIZE | 0 cds                    |                                             |
             * 3d       | RETURNDATASIZE | 0 0 cds                  |                                             |
             * 37       | CALLDATACOPY   |                          | [0..cds): calldata                          |
             *                                                                                                    |
             * ::: keep some values in stack :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d       | RETURNDATASIZE | 0                        | [0..cds): calldata                          |
             * 3d       | RETURNDATASIZE | 0 0                      | [0..cds): calldata                          |
             * 3d       | RETURNDATASIZE | 0 0 0                    | [0..cds): calldata                          |
             * 3d       | RETURNDATASIZE | 0 0 0 0                  | [0..cds): calldata                          |
             * 61 extra | PUSH2 extra    | e 0 0 0 0                | [0..cds): calldata                          |
             *                                                                                                    |
             * ::: copy extra data to memory :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 80       | DUP1           | e e 0 0 0 0              | [0..cds): calldata                          |
             * 60 0x62  | PUSH1 0x62     | 0x62 e e 0 0 0 0         | [0..cds): calldata                          |
             * 36       | CALLDATASIZE   | cds 0x62 e e 0 0 0 0     | [0..cds): calldata                          |
             * 39       | CODECOPY       | e 0 0 0 0                | [0..cds): calldata, [cds..cds+e): extraData |
             *                                                                                                    |
             * ::: delegate call to the implementation contract ::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36       | CALLDATASIZE   | cds e 0 0 0 0            | [0..cds): calldata, [cds..cds+e): extraData |
             * 01       | ADD            | cds+e 0 0 0 0            | [0..cds): calldata, [cds..cds+e): extraData |
             * 3d       | RETURNDATASIZE | 0 cds+e 0 0 0 0          | [0..cds): calldata, [cds..cds+e): extraData |
             * 73 addr  | PUSH20 addr    | addr 0 cds+e 0 0 0 0     | [0..cds): calldata, [cds..cds+e): extraData |
             * 5a       | GAS            | gas addr 0 cds+e 0 0 0 0 | [0..cds): calldata, [cds..cds+e): extraData |
             * f4       | DELEGATECALL   | success 0 0              | [0..cds): calldata, [cds..cds+e): extraData |
             *                                                                                                    |
             * ::: copy return data to memory ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d       | RETURNDATASIZE | rds success 0 0          | [0..cds): calldata, [cds..cds+e): extraData |
             * 3d       | RETURNDATASIZE | rds rds success 0 0      | [0..cds): calldata, [cds..cds+e): extraData |
             * 93       | SWAP4          | 0 rds success 0 rds      | [0..cds): calldata, [cds..cds+e): extraData |
             * 80       | DUP1           | 0 0 rds success 0 rds    | [0..cds): calldata, [cds..cds+e): extraData |
             * 3e       | RETURNDATACOPY | success 0 rds            | [0..rds): returndata                        |
             *                                                                                                    |
             * 60 0x60  | PUSH1 0x60     | 0x60 success 0 rds       | [0..rds): returndata                        |
             * 57       | JUMPI          | 0 rds                    | [0..rds): returndata                        |
             *                                                                                                    |
             * ::: revert ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * fd       | REVERT         |                          | [0..rds): returndata                        |
             *                                                                                                    |
             * ::: return ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b       | JUMPDEST       | 0 rds                    | [0..rds): returndata                        |
             * f3       | RETURN         |                          | [0..rds): returndata                        |
             * ---------------------------------------------------------------------------------------------------+
             */
            // Write the bytecode before the data.
            mstore(data, 0x5af43d3d93803e606057fd5bf3)
            // Write the address of the implementation.
            mstore(sub(data, 0x0d), implementation)
            // Write the rest of the bytecode.
            mstore(
                sub(data, 0x21),
                or(shl(0x48, extraLength), 0x593da1005b363d3d373d3d3d3d610000806062363936013d73)
            )
            // `keccak256("ReceiveETH(uint256)")`
            mstore(
                sub(data, 0x3a), 0x9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff
            )
            mstore(
                sub(data, 0x5a),
                or(shl(0x78, add(extraLength, 0x62)), 0x6100003d81600a3d39f336602c57343d527f)
            )
            mstore(dataEnd, shl(0xf0, extraLength))

            // Create the instance.
            instance := create(0, sub(data, 0x4c), add(extraLength, 0x6c))

            // If `instance` is zero, revert.
            if iszero(instance) {
                // Store the function selector of `DeploymentFailed()`.
                mstore(0x00, 0x30116425)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Restore the overwritten memory surrounding `data`.
            mstore(dataEnd, mAfter1)
            mstore(data, dataLength)
            mstore(sub(data, 0x20), mBefore1)
            mstore(sub(data, 0x40), mBefore2)
            mstore(sub(data, 0x60), mBefore3)
        }
    }

    /// @dev Deploys a deterministic clone of `implementation`,
    /// using immutable arguments encoded in `data`, with `salt`.
    function cloneDeterministic(address implementation, bytes memory data, bytes32 salt)
        internal
        returns (address instance)
    {
        assembly {
            // Compute the boundaries of the data and cache the memory slots around it.
            let mBefore3 := mload(sub(data, 0x60))
            let mBefore2 := mload(sub(data, 0x40))
            let mBefore1 := mload(sub(data, 0x20))
            let dataLength := mload(data)
            let dataEnd := add(add(data, 0x20), dataLength)
            let mAfter1 := mload(dataEnd)

            // +2 bytes for telling how much data there is appended to the call.
            let extraLength := add(dataLength, 2)

            // Write the bytecode before the data.
            mstore(data, 0x5af43d3d93803e606057fd5bf3)
            // Write the address of the implementation.
            mstore(sub(data, 0x0d), implementation)
            // Write the rest of the bytecode.
            mstore(
                sub(data, 0x21),
                or(shl(0x48, extraLength), 0x593da1005b363d3d373d3d3d3d610000806062363936013d73)
            )
            // `keccak256("ReceiveETH(uint256)")`
            mstore(
                sub(data, 0x3a), 0x9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff
            )
            mstore(
                sub(data, 0x5a),
                or(shl(0x78, add(extraLength, 0x62)), 0x6100003d81600a3d39f336602c57343d527f)
            )
            mstore(dataEnd, shl(0xf0, extraLength))

            // Create the instance.
            instance := create2(0, sub(data, 0x4c), add(extraLength, 0x6c), salt)

            // If `instance` is zero, revert.
            if iszero(instance) {
                // Store the function selector of `DeploymentFailed()`.
                mstore(0x00, 0x30116425)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }

            // Restore the overwritten memory surrounding `data`.
            mstore(dataEnd, mAfter1)
            mstore(data, dataLength)
            mstore(sub(data, 0x20), mBefore1)
            mstore(sub(data, 0x40), mBefore2)
            mstore(sub(data, 0x60), mBefore3)
        }
    }

    /// @dev Returns the initialization code hash of the clone of `implementation`
    /// using immutable arguments encoded in `data`.
    /// Used for mining vanity addresses with create2crunch.
    function initCodeHash(address implementation, bytes memory data)
        internal
        pure
        returns (bytes32 hash)
    {
        assembly {
            // Compute the boundaries of the data and cache the memory slots around it.
            let mBefore3 := mload(sub(data, 0x60))
            let mBefore2 := mload(sub(data, 0x40))
            let mBefore1 := mload(sub(data, 0x20))
            let dataLength := mload(data)
            let dataEnd := add(add(data, 0x20), dataLength)
            let mAfter1 := mload(dataEnd)

            // +2 bytes for telling how much data there is appended to the call.
            let extraLength := add(dataLength, 2)

            // Write the bytecode before the data.
            mstore(data, 0x5af43d3d93803e606057fd5bf3)
            // Write the address of the implementation.
            mstore(sub(data, 0x0d), implementation)
            // Write the rest of the bytecode.
            mstore(
                sub(data, 0x21),
                or(shl(0x48, extraLength), 0x593da1005b363d3d373d3d3d3d610000806062363936013d73)
            )
            // `keccak256("ReceiveETH(uint256)")`
            mstore(
                sub(data, 0x3a), 0x9e4ac34f21c619cefc926c8bd93b54bf5a39c7ab2127a895af1cc0691d7e3dff
            )
            mstore(
                sub(data, 0x5a),
                or(shl(0x78, add(extraLength, 0x62)), 0x6100003d81600a3d39f336602c57343d527f)
            )
            mstore(dataEnd, shl(0xf0, extraLength))

            // Compute and store the bytecode hash.
            hash := keccak256(sub(data, 0x4c), add(extraLength, 0x6c))

            // Restore the overwritten memory surrounding `data`.
            mstore(dataEnd, mAfter1)
            mstore(data, dataLength)
            mstore(sub(data, 0x20), mBefore1)
            mstore(sub(data, 0x40), mBefore2)
            mstore(sub(data, 0x60), mBefore3)
        }
    }

    /// @dev Returns the address of the deterministic clone of
    /// `implementation` using immutable arguments encoded in `data`, with `salt`, by `deployer`.
    function predictDeterministicAddress(
        address implementation,
        bytes memory data,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHash(implementation, data);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      OTHER OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the address when a contract with initialization code hash,
    /// `hash`, is deployed with `salt`, by `deployer`.
    function predictDeterministicAddress(bytes32 hash, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, hash)
            mstore(0x01, shl(96, deployer))
            mstore(0x15, salt)
            predicted := keccak256(0x00, 0x55)
            // Restore the part of the free memory pointer that has been overwritten.
            mstore(0x35, 0)
        }
    }

    /// @dev Reverts if `salt` does not start with either the zero address or the caller.
    function checkStartsWithCaller(bytes32 salt) internal view {
        /// @solidity memory-safe-assembly
        assembly {
            // If the salt does not start with the zero address or the caller.
            if iszero(or(iszero(shr(96, salt)), eq(caller(), shr(96, salt)))) {
                // Store the function selector of `SaltDoesNotStartWithCaller()`.
                mstore(0x00, 0x2f634836)
                // Revert with (offset, size).
                revert(0x1c, 0x04)
            }
        }
    }
}

File 43 of 49 : LibContractInfo.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title LibContractInfo
 * @notice Contains logic to call functions that return information about a given contract.
 */
library LibContractInfo {
    /**
     * @notice gets the symbol of a given contract
     * @param _contract The contract to get the symbol of
     * @return symbol The symbol of the contract
     * @dev if the contract does not have a symbol function, the first 4 bytes of the address are returned
     */
    function getSymbol(address _contract) internal view returns (string memory symbol) {
        (bool success, bytes memory data) = _contract.staticcall(abi.encodeWithSignature("symbol()"));
        symbol = new string(4);
        if (success) {
            symbol = abi.decode(data, (string));
        } else {
            assembly {
                mstore(add(symbol, 0x20), shl(224, shr(128, _contract)))
            }
        }
    }

    /**
     * @notice gets the name of a given contract
     * @param _contract The contract to get the name of
     * @return name The name of the contract
     * @dev if the contract does not have a name function, the first 8 bytes of the address are returned
     */
    function getName(address _contract) internal view returns (string memory name) {
        (bool success, bytes memory data) = _contract.staticcall(abi.encodeWithSignature("name()"));
        name = new string(8);
        if (success) {
            name = abi.decode(data, (string));
        } else {
            assembly {
                mstore(add(name, 0x20), shl(224, shr(128, _contract)))
            }
        }
    }

    /**
     * @notice gets the decimals of a given contract
     * @param _contract The contract to get the decimals of
     * @return decimals The decimals of the contract
     * @dev if the contract does not have a decimals function, 18 is returned
     */
    function getDecimals(address _contract) internal view returns (uint8 decimals) {
        (bool success, bytes memory data) = _contract.staticcall(abi.encodeWithSignature("decimals()"));
        decimals = success ? abi.decode(data, (uint8)) : 18; // default to 18 decimals
    }
}

File 44 of 49 : LibLastReserveBytes.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title LibLastReserveBytes
 * @author Publius
 * @notice  Contains byte operations used during storage reads & writes for Pumps.
 *
 * @dev {LibLastReserveBytes} tightly packs a `uint8 n`, `uint40 timestamp` and `bytes16[] reserves`
 * for gas efficiency purposes. The first 2 values in `reserves` are packed into the first slot with
 * `timestamp` and `n`. Thus, only the first 13 bytes (104 bit) of each reserve value are stored and
 * the last 3 bytes get truncated. Given that the Well uses the quadruple-precision floating-point
 * format for last reserve values and only uses the last reserves to compute the max increase/decrease
 * in reserves for manipulation resistance purposes, the gas savings is worth the lose of precision.
 */
library LibLastReserveBytes {
    function readNumberOfReserves(bytes32 slot) internal view returns (uint8 _numberOfReserves) {
        assembly {
            _numberOfReserves := shr(248, sload(slot))
        }
    }

    function storeLastReserves(bytes32 slot, uint40 lastTimestamp, bytes16[] memory reserves) internal {
        // Potential optimization – shift reserve bytes left to perserve extra decimal precision.
        uint8 n = uint8(reserves.length);
        if (n == 1) {
            assembly {
                sstore(slot, or(or(shl(208, lastTimestamp), shl(248, n)), shl(104, shr(152, mload(add(reserves, 32))))))
            }
            return;
        }
        assembly {
            sstore(
                slot,
                or(
                    or(shl(208, lastTimestamp), shl(248, n)),
                    or(shl(104, shr(152, mload(add(reserves, 32)))), shr(152, mload(add(reserves, 64))))
                )
            )
            // slot := add(slot, 32)
        }
        if (n > 2) {
            uint256 maxI = n / 2; // number of fully-packed slots
            uint256 iByte; // byte offset of the current reserve
            for (uint256 i = 1; i < maxI; ++i) {
                iByte = i * 64;
                assembly {
                    sstore(
                        add(slot, i),
                        add(mload(add(reserves, add(iByte, 32))), shr(128, mload(add(reserves, add(iByte, 64)))))
                    )
                }
            }
            // If there is an odd number of reserves, create a slot with the last reserve
            // Since `i < maxI` above, the next byte offset `maxI * 64`
            // Equivalent to "reserves.length % 2 == 1" but cheaper.
            if (reserves.length & 1 == 1) {
                iByte = maxI * 64;
                assembly {
                    sstore(
                        add(slot, maxI),
                        add(mload(add(reserves, add(iByte, 32))), shr(128, shl(128, sload(add(slot, maxI)))))
                    )
                }
            }
        }
    }

    /**
     * @dev Read `n` packed bytes16 reserves at storage position `slot`.
     */
    function readLastReserves(bytes32 slot)
        internal
        view
        returns (uint8 n, uint40 lastTimestamp, bytes16[] memory reserves)
    {
        // Shortcut: two reserves can be quickly unpacked from one slot
        bytes32 temp;
        assembly {
            temp := sload(slot)
            n := shr(248, temp)
            lastTimestamp := shr(208, temp)
        }
        if (n == 0) return (n, lastTimestamp, reserves);
        // Initialize array with length `n`, fill it in via assembly
        reserves = new bytes16[](n);
        assembly {
            mstore(add(reserves, 32), shl(152, shr(104, temp)))
        }
        if (n == 1) return (n, lastTimestamp, reserves);
        assembly {
            mstore(add(reserves, 64), shl(152, temp))
        }

        if (n > 2) {
            uint256 iByte;
            for (uint256 i = 3; i <= n; ++i) {
                // `iByte` is the byte position for the current slot:
                // i        3 4 5 6
                // iByte    1 1 2 2
                iByte = (i - 1) / 2;
                // Equivalent to "i % 2 == 1" but cheaper.
                if (i & 1 == 1) {
                    assembly {
                        mstore(
                            // store at index i * 32; i = 0 is skipped by loop
                            add(reserves, mul(i, 32)),
                            sload(add(slot, iByte))
                        )
                    }
                } else {
                    assembly {
                        mstore(add(reserves, mul(i, 32)), shl(128, sload(add(slot, iByte))))
                    }
                }
            }
        }
    }

    function readBytes(bytes32 slot) internal view returns (bytes32 value) {
        assembly {
            value := sload(slot)
        }
    }
}

File 45 of 49 : LibMath.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @title Lib Math contains math operations
 */
library LibMath {
    /**
     * @param a numerator
     * @param b denominator
     * @dev Division, rounded up
     */
    function roundUpDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        return (a - 1) / b + 1;
    }

    /**
     * @notice Computes the `n`th root of a number `a` using the Newton--Raphson method.
     * @param a The number to compute the root of
     * @param n The root to compute
     * @return root The `n`th root of `a`
     * @dev TODO: more testing - https://ethereum.stackexchange.com/questions
     * /38468/calculate-the-nth-root-of-an-arbitrary-uint-using-solidity
     * https://en.wikipedia.org/wiki/Nth_root_algorithm
     * This is used in {ConstantProduct.Sol}, where the number of tokens are
     * restricted to 16. even roots are much cheaper to compute than uneven,
     * thus we recursively call sqrt().
     *
     */
    function nthRoot(uint256 a, uint256 n) internal pure returns (uint256 root) {
        assert(n > 1);
        if (a == 0) return 0;
        // Equivalent to "i % 2 == 0" but cheaper.
        if (n & 1 == 0) {
            if (n == 2) return sqrt(a); // shortcut for square root
            if (n == 4) return sqrt(sqrt(a));
            if (n == 8) return sqrt(sqrt(sqrt(a)));
            if (n == 16) return sqrt(sqrt(sqrt(sqrt(a))));
        }
        // The scale factor is a crude way to turn everything into integer calcs.
        // Actually do ((10 ^ n) * a) ^ (1/n)
        uint256 a0 = (10 ** n) * a;

        uint256 xNew = 10;
        uint256 x;
        while (xNew != x) {
            x = xNew;
            uint256 t0 = x ** (n - 1);
            if (x * t0 > a0) {
                xNew = x - (x - a0 / t0) / n;
            } else {
                xNew = x + (a0 / t0 - x) / n;
            }
        }

        root = (xNew + 5) / 10;
    }

    /**
     * @notice computes the square root of a given number
     * @param a The number to compute the square root of
     * @return z The square root of a
     * @dev
     * This function is based on the Babylonian method of computing square roots
     * https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
     * Implementation from: https://github.com/Gaussian-Process/solidity-sqrt/blob/main/src/FixedPointMathLib.sol
     * based on https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol
     */

    function sqrt(uint256 a) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := a // We start y at a, which will help us make our initial estimate.

            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // We check y >= 2^(k + 8) but shift right by k bits
            // each branch to ensure that if a >= 256, then y >= 256.
            if iszero(lt(y, 0x10000000000000000000000000000000000)) {
                y := shr(128, y)
                z := shl(64, z)
            }
            if iszero(lt(y, 0x1000000000000000000)) {
                y := shr(64, y)
                z := shl(32, z)
            }
            if iszero(lt(y, 0x10000000000)) {
                y := shr(32, y)
                z := shl(16, z)
            }
            if iszero(lt(y, 0x1000000)) {
                y := shr(16, y)
                z := shl(8, z)
            }

            // Goal was to get z*z*y within a small factor of a. More iterations could
            // get y in a tighter range. Currently, we will have y in [256, 256*2^16).
            // We ensured y >= 256 so that the relative difference between y and y+1 is small.
            // That's not possible if a < 256 but we can just verify those cases exhaustively.

            // Now, z*z*y <= a < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or a < 256.
            // Correctness can be checked exhaustively for a < 256, so we assume y >= 256.
            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(a), or about 20bps.

            // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
            // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.

            // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
            // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.

            // There is no overflow risk here since y < 2^136 after the first branch above.
            z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(a, z)))
            z := shr(1, add(z, div(a, z)))
            z := shr(1, add(z, div(a, z)))
            z := shr(1, add(z, div(a, z)))
            z := shr(1, add(z, div(a, z)))
            z := shr(1, add(z, div(a, z)))
            z := shr(1, add(z, div(a, z)))

            // If a+1 is a perfect square, the Babylonian method cycles between
            // floor(sqrt(a)) and ceil(sqrt(a)). This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
            // If you don't care whether the floor or ceil square root is returned, you can remove this statement.
            z := sub(z, lt(div(a, z), z))
        }
    }

    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        // 512-bit multiply [prod1 prod0] = a * b
        // Compute the product mod 2**256 and mod 2**256 - 1
        // then 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 {
            let mm := mulmod(a, b, not(0))
            prod0 := mul(a, b)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

        // Handle non-overflow cases, 256 by 256 division
        if (prod1 == 0) {
            require(denominator > 0);
            assembly {
                result := div(prod0, denominator)
            }
            return result;
        }

        // Make sure the result is less than 2**256.
        // Also prevents denominator == 0
        require(denominator > prod1);

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

        // Make division exact by subtracting the remainder from [prod1 prod0]
        // Compute remainder using mulmod
        uint256 remainder;
        assembly {
            remainder := mulmod(a, b, denominator)
        }
        // Subtract 256 bit number from 512 bit number
        assembly {
            prod1 := sub(prod1, gt(remainder, prod0))
            prod0 := sub(prod0, remainder)
        }

        // Factor powers of two out of denominator
        // Compute largest power of two divisor of denominator.
        // Always >= 1.
        unchecked {
            uint256 twos = (type(uint256).max - denominator + 1) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

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

File 46 of 49 : LibWellConstructor.sol
// SPDX-License-Identifier: MIT
// forgefmt: disable-start

pragma solidity ^0.8.20;

import {LibContractInfo} from "src/libraries/LibContractInfo.sol";
import {Call, IERC20} from "src/Well.sol";

library LibWellConstructor {
    /**
     * @notice Encode the Well's immutable data and init data.
     */
    function encodeWellDeploymentData(
        address _aquifer,
        IERC20[] memory _tokens,
        Call memory _wellFunction,
        Call[] memory _pumps
    ) internal view returns (bytes memory immutableData, bytes memory initData) {
        immutableData = encodeWellImmutableData(_aquifer, _tokens, _wellFunction, _pumps);
        initData = encodeWellInitFunctionCall(_tokens, _wellFunction);
    }

    /**
     * @notice Encode the Well's immutable data.
     * @param _aquifer The address of the Aquifer which will deploy this Well.
     * @param _tokens A list of ERC20 tokens supported by the Well.
     * @param _wellFunction A single Call struct representing a call to the Well Function.
     * @param _pumps An array of Call structs representings calls to Pumps.
     * @dev `immutableData` is tightly packed, however since `_tokens` itself is
     * an array, each address in the array will be padded up to 32 bytes.
     *
     * Arbitrary-length bytes are applied to the end of the encoded bytes array
     * for easy reading of statically-sized data.
     * 
     */
    function encodeWellImmutableData(
        address _aquifer,
        IERC20[] memory _tokens,
        Call memory _wellFunction,
        Call[] memory _pumps
    ) internal pure returns (bytes memory immutableData) {
        
        immutableData = abi.encodePacked(
            _aquifer,                   // aquifer address
            _tokens.length,             // number of tokens
            _wellFunction.target,       // well function address
            _wellFunction.data.length,  // well function data length
            _pumps.length,              // number of pumps
            _tokens,                    // tokens array
            _wellFunction.data         // well function data (bytes)
        );
        for (uint256 i; i < _pumps.length; ++i) {
            immutableData = abi.encodePacked(
                immutableData,            // previously packed pumps
                _pumps[i].target,       // pump address
                _pumps[i].data.length,  // pump data length
                _pumps[i].data          // pump data (bytes)
            );
        }
    }

    /**
     * @notice Encode a call to the {Well.init} function to set a standardized ERC20 name and symbol.
     */
    function encodeWellInitFunctionCall(
        IERC20[] memory _tokens,
        Call memory _wellFunction
    ) public view returns (bytes memory initFunctionCall) {
        string memory name = LibContractInfo.getSymbol(address(_tokens[0]));
        string memory symbol = name;
        for (uint256 i = 1; i < _tokens.length; ++i) {
            name = string.concat(name, ":", LibContractInfo.getSymbol(address(_tokens[i])));
            symbol = string.concat(symbol, LibContractInfo.getSymbol(address(_tokens[i])));
        }
        name = string.concat(name, " ", LibContractInfo.getName(_wellFunction.target), " Well");
        symbol = string.concat(symbol, LibContractInfo.getSymbol(_wellFunction.target), "w");

        // See {Well.init}.
        initFunctionCall = abi.encodeWithSignature("init(string,string)", name, symbol);
    }

    /**
     * @notice Encode a Call struct representing an arbitrary call to `target` with additional data `data`.
     */
    function encodeCall(address target, bytes memory data) public pure returns (Call memory) {
        return Call(target, data);
    }
}

File 47 of 49 : Clone.sol
// SPDX-License-Identifier: BSD
pragma solidity ^0.8.20;

/// @title Clone
/// @author zefram.eth, Saw-mon & Natalie
/// @notice Provides helper functions for reading immutable args from calldata
contract Clone {

    uint256 internal constant ONE_WORD = 0x20;

    /// @notice Reads an immutable arg with type address
    /// @param argOffset The offset of the arg in the packed data
    /// @return arg The arg value
    function _getArgAddress(uint256 argOffset)
        internal
        pure
        returns (address arg)
    {
        uint256 offset = _getImmutableArgsOffset();
        // solhint-disable-next-line no-inline-assembly
        assembly {
            arg := shr(0x60, calldataload(add(offset, argOffset)))
        }
    }

    /// @notice Reads an immutable arg with type uint256
    /// @param argOffset The offset of the arg in the packed data
    /// @return arg The arg value
    function _getArgUint256(uint256 argOffset)
        internal
        pure
        returns (uint256 arg)
    {
        uint256 offset = _getImmutableArgsOffset();
        // solhint-disable-next-line no-inline-assembly
        assembly {
            arg := calldataload(add(offset, argOffset))
        }
    }

    /// @notice Reads a uint256 array stored in the immutable args.
    /// @param argOffset The offset of the arg in the packed data
    /// @param arrLen Number of elements in the array
    /// @return arr The array
    function _getArgUint256Array(uint256 argOffset, uint256 arrLen)
        internal
        pure
      returns (uint256[] memory arr)
    {
        uint256 offset = _getImmutableArgsOffset() + argOffset;
        arr = new uint256[](arrLen);

        // solhint-disable-next-line no-inline-assembly
        assembly {
            calldatacopy(
                add(arr, ONE_WORD),
                offset,
                shl(5, arrLen)
            )
        }
    }

    /// @notice Reads an immutable arg with type uint64
    /// @param argOffset The offset of the arg in the packed data
    /// @return arg The arg value
    function _getArgUint64(uint256 argOffset)
        internal
        pure
        returns (uint64 arg)
    {
        uint256 offset = _getImmutableArgsOffset();
        // solhint-disable-next-line no-inline-assembly
        assembly {
            arg := shr(0xc0, calldataload(add(offset, argOffset)))
        }
    }

    /// @notice Reads an immutable arg with type uint8
    /// @param argOffset The offset of the arg in the packed data
    /// @return arg The arg value
    function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) {
        uint256 offset = _getImmutableArgsOffset();
        // solhint-disable-next-line no-inline-assembly
        assembly {
            arg := shr(0xf8, calldataload(add(offset, argOffset)))
        }
    }

    /// @return offset The offset of the packed immutable args in calldata
    function _getImmutableArgsOffset() internal pure returns (uint256 offset) {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            offset := sub(
                calldatasize(),
                shr(0xf0, calldataload(sub(calldatasize(), 2)))
            )
        }
    }
}

File 48 of 49 : ClonePlus.sol
// SPDX-License-Identifier: BSD
pragma solidity ^0.8.20;

import {Clone} from "./Clone.sol";
import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";

/// @title ClonePlus
/// @notice Extends Clone with additional helper functions
contract ClonePlus is Clone {
    /// @notice Reads a IERC20 array stored in the immutable args.
    /// @param argOffset The offset of the arg in the packed data
    /// @param arrLen Number of elements in the array
    /// @return arr The array
    function _getArgIERC20Array(uint256 argOffset, uint256 arrLen) internal pure returns (IERC20[] memory arr) {
        uint256 offset = _getImmutableArgsOffset() + argOffset;
        arr = new IERC20[](arrLen);

        // solhint-disable-next-line no-inline-assembly
        assembly {
            calldatacopy(add(arr, ONE_WORD), offset, shl(5, arrLen))
        }
    }

    /// @notice Reads a bytes data stored in the immutable args.
    /// @param argOffset The offset of the arg in the packed data
    /// @param bytesLen Number of bytes in the data
    /// @return data the bytes data
    function _getArgBytes(uint256 argOffset, uint256 bytesLen) internal pure returns (bytes memory data) {
        if (bytesLen == 0) return data;
        uint256 offset = _getImmutableArgsOffset() + argOffset;
        data = new bytes(bytesLen);

        // solhint-disable-next-line no-inline-assembly
        assembly {
            calldatacopy(add(data, ONE_WORD), offset, bytesLen)
        }
    }
}

File 49 of 49 : Well.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

import {ReentrancyGuardUpgradeable} from "lib/openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol";
import {ERC20Upgradeable, ERC20PermitUpgradeable} from "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC20PermitUpgradeable.sol";
import {IERC20, SafeERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol";
import {IWell, Call} from "src/interfaces/IWell.sol";
import {IWellErrors} from "src/interfaces/IWellErrors.sol";
import {IPump} from "src/interfaces/pumps/IPump.sol";
import {IWellFunction} from "src/interfaces/IWellFunction.sol";
import {LibBytes} from "src/libraries/LibBytes.sol";
import {ClonePlus} from "src/utils/ClonePlus.sol";

/**
 * @title Well
 * @author Publius, Silo Chad, Brean
 * @dev A Well is a constant function AMM allowing the provisioning of liquidity
 * into a single pooled on-chain liquidity position.
 *
 * Rebasing Tokens:
 * - Positive rebasing tokens are supported by Wells, but any tokens recieved from a
 *   rebase will not be rewarded to LP holders and instead can be extracted by anyone
 *   using `skim`, `sync` or `shift`.
 * - Negative rebasing tokens should not be used in Well as the effect of a negative
 *   rebase will be realized by users interacting with the Well, not LP token holders.
 *
 * Fee on Tranfer (FoT) Tokens:
 * - When transferring fee on transfer tokens to a Well (swapping from or adding liquidity),
 *   use `swapFromFeeOnTrasfer` or `addLiquidityFeeOnTransfer`. `swapTo` does not support
 *   fee on transfer tokens (See {swapTo}).
 * - When recieving fee on transfer tokens from a Well (swapping to and removing liquidity),
 *   INCLUDE the fee that is taken on transfer when calculating amount out values.
 */
contract Well is ERC20PermitUpgradeable, IWell, IWellErrors, ReentrancyGuardUpgradeable, ClonePlus {
    using SafeERC20 for IERC20;

    uint256 private constant PACKED_ADDRESS = 20;
    uint256 private constant ONE_WORD_PLUS_PACKED_ADDRESS = 52; // For gas efficiency purposes
    bytes32 private constant RESERVES_STORAGE_SLOT = 0x4bba01c388049b5ebd30398b65e8ad45b632802c5faf4964e58085ea8ab03715; // bytes32(uint256(keccak256("reserves.storage.slot")) - 1);

    constructor() {
        // Disable Initializers to prevent the init function from being callable on the implementation contract
        _disableInitializers();
    }

    function init(string memory _name, string memory _symbol) external initializer {
        __ERC20Permit_init(_name);
        __ERC20_init(_name, _symbol);
        __ReentrancyGuard_init();

        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        for (uint256 i; i < tokensLength - 1; ++i) {
            for (uint256 j = i + 1; j < tokensLength; ++j) {
                if (_tokens[i] == _tokens[j]) {
                    revert DuplicateTokens(_tokens[i]);
                }
            }
        }
    }

    function isInitialized() external view returns (bool) {
        return _getInitializedVersion() > 0;
    }

    //////////////////// WELL DEFINITION ////////////////////

    /// This Well uses a dynamic immutable storage layout. Immutable storage is
    /// used for gas-efficient reads during Well operation. The Well must be
    /// created by cloning with a pre-encoded byte string containing immutable
    /// data.
    ///
    /// Let n = number of tokens
    ///     m = length of well function data (bytes)
    ///
    /// TYPE        NAME                       LOCATION (CONSTANT)
    /// ==============================================================
    /// address     aquifer()                  0        (LOC_AQUIFER_ADDR)
    /// uint256     numberOfTokens()           20       (LOC_TOKENS_COUNT)
    /// address     wellFunctionAddress()      52       (LOC_WELL_FUNCTION_ADDR)
    /// uint256     wellFunctionDataLength()   72       (LOC_WELL_FUNCTION_DATA_LENGTH)
    /// uint256     numberOfPumps()            104      (LOC_PUMPS_COUNT)
    /// --------------------------------------------------------------
    /// address     token0                     136      (LOC_VARIABLE)
    /// ...
    /// address     tokenN                     136 + (n-1) * 32
    /// --------------------------------------------------------------
    /// byte        wellFunctionData0          136 + n * 32
    /// ...
    /// byte        wellFunctionDataM          136 + n * 32 + m
    /// --------------------------------------------------------------
    /// address     pump1Address               136 + n * 32 + m
    /// uint256     pump1DataLength            136 + n * 32 + m + 20
    /// byte        pump1Data                  136 + n * 32 + m + 52
    /// ...
    /// ==============================================================

    uint256 private constant LOC_AQUIFER_ADDR = 0;
    uint256 private constant LOC_TOKENS_COUNT = 20; // LOC_AQUIFER_ADDR + PACKED_ADDRESS
    uint256 private constant LOC_WELL_FUNCTION_ADDR = 52; // LOC_TOKENS_COUNT + ONE_WORD
    uint256 private constant LOC_WELL_FUNCTION_DATA_LENGTH = 72; // LOC_WELL_FUNCTION_ADDR + PACKED_ADDRESS;
    uint256 private constant LOC_PUMPS_COUNT = 104; // LOC_WELL_FUNCTION_DATA_LENGTH + ONE_WORD;
    uint256 private constant LOC_VARIABLE = 136; // LOC_PUMPS_COUNT + ONE_WORD;

    function tokens() public pure returns (IERC20[] memory _tokens) {
        _tokens = _getArgIERC20Array(LOC_VARIABLE, numberOfTokens());
    }

    function wellFunction() public pure returns (Call memory _wellFunction) {
        _wellFunction.target = wellFunctionAddress();
        _wellFunction.data = _getArgBytes(LOC_VARIABLE + numberOfTokens() * ONE_WORD, wellFunctionDataLength());
    }

    function pumps() public pure returns (Call[] memory _pumps) {
        uint256 _numberOfPumps = numberOfPumps();
        if (_numberOfPumps == 0) return _pumps;

        _pumps = new Call[](_numberOfPumps);
        uint256 dataLoc = LOC_VARIABLE + numberOfTokens() * ONE_WORD + wellFunctionDataLength();

        uint256 pumpDataLength;
        for (uint256 i; i < _pumps.length; ++i) {
            _pumps[i].target = _getArgAddress(dataLoc);
            dataLoc += PACKED_ADDRESS;
            pumpDataLength = _getArgUint256(dataLoc);
            dataLoc += ONE_WORD;
            _pumps[i].data = _getArgBytes(dataLoc, pumpDataLength);
            dataLoc += pumpDataLength;
        }
    }

    /**
     * @dev {wellData} is unused in this implementation.
     */
    function wellData() public pure returns (bytes memory) {}

    function aquifer() public pure override returns (address) {
        return _getArgAddress(LOC_AQUIFER_ADDR);
    }

    function well()
        external
        pure
        returns (
            IERC20[] memory _tokens,
            Call memory _wellFunction,
            Call[] memory _pumps,
            bytes memory _wellData,
            address _aquifer
        )
    {
        _tokens = tokens();
        _wellFunction = wellFunction();
        _pumps = pumps();
        _wellData = wellData();
        _aquifer = aquifer();
    }

    //////////////////// WELL DEFINITION: HELPERS ////////////////////

    /**
     * @notice Returns the number of tokens that are tradable in this Well.
     * @dev Length of the `tokens()` array.
     */
    function numberOfTokens() public pure returns (uint256) {
        return _getArgUint256(LOC_TOKENS_COUNT);
    }

    /**
     * @notice Returns the address of the Well Function.
     */
    function wellFunctionAddress() public pure returns (address) {
        return _getArgAddress(LOC_WELL_FUNCTION_ADDR);
    }

    /**
     * @notice Returns the length of the configurable `data` parameter passed during calls to the Well Function.
     */
    function wellFunctionDataLength() public pure returns (uint256) {
        return _getArgUint256(LOC_WELL_FUNCTION_DATA_LENGTH);
    }

    /**
     * @notice Returns the number of Pumps which this Well was initialized with.
     */
    function numberOfPumps() public pure returns (uint256) {
        return _getArgUint256(LOC_PUMPS_COUNT);
    }

    /**
     * @notice Returns address & data used to call the first Pump.
     * @dev Provided as an optimization in the case where {numberOfPumps} returns 1.
     */
    function firstPump() public pure returns (Call memory _pump) {
        uint256 dataLoc = LOC_VARIABLE + numberOfTokens() * ONE_WORD + wellFunctionDataLength();
        _pump.target = _getArgAddress(dataLoc);
        _pump.data = _getArgBytes(dataLoc + ONE_WORD_PLUS_PACKED_ADDRESS, _getArgUint256(dataLoc + PACKED_ADDRESS));
    }

    //////////////////// SWAP: FROM ////////////////////

    /**
     * @dev MUST revert if a fee on transfer token is used. The requisite check
     * is performed in {_setReserves}.
     */
    function swapFrom(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 amountOut) {
        fromToken.safeTransferFrom(msg.sender, address(this), amountIn);
        amountOut = _swapFrom(fromToken, toToken, amountIn, minAmountOut, recipient);
    }

    /**
     * @dev Note that `amountOut` is the amount *transferred* by the Well; if a fee
     * is charged on transfers of `toToken`, the amount received by `recipient`
     * will be less than `amountOut`.
     */
    function swapFromFeeOnTransfer(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 amountOut) {
        amountIn = _safeTransferFromFeeOnTransfer(fromToken, msg.sender, amountIn);
        amountOut = _swapFrom(fromToken, toToken, amountIn, minAmountOut, recipient);
    }

    function _swapFrom(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 minAmountOut,
        address recipient
    ) internal returns (uint256 amountOut) {
        IERC20[] memory _tokens = tokens();
        (uint256 i, uint256 j) = _getIJ(_tokens, fromToken, toToken);
        uint256[] memory reserves = _updatePumps(_tokens.length);

        reserves[i] += amountIn;
        uint256 reserveJBefore = reserves[j];
        reserves[j] = _calcReserve(wellFunction(), reserves, j, totalSupply());

        // Note: The rounding approach of the Well function determines whether
        // slippage from imprecision goes to the Well or to the User.
        amountOut = reserveJBefore - reserves[j];
        if (amountOut < minAmountOut) {
            revert SlippageOut(amountOut, minAmountOut);
        }

        toToken.safeTransfer(recipient, amountOut);
        emit Swap(fromToken, toToken, amountIn, amountOut, recipient);
        _setReserves(_tokens, reserves);
    }

    /**
     * @dev Assumes both tokens incur no fee on transfer.
     */
    function getSwapOut(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn
    ) external view readOnlyNonReentrant returns (uint256 amountOut) {
        IERC20[] memory _tokens = tokens();
        (uint256 i, uint256 j) = _getIJ(_tokens, fromToken, toToken);
        uint256[] memory reserves = _getReserves(_tokens.length);

        reserves[i] += amountIn;

        // underflow is desired; Well Function SHOULD NOT increase reserves of both `i` and `j`
        amountOut = reserves[j] - _calcReserve(wellFunction(), reserves, j, totalSupply());
    }

    //////////////////// SWAP: TO ////////////////////

    /**
     * @dev {swapTo} does not support fee on transfer tokens, and no corresponding
     * "swapToFeeOnTransfer" function is provided as this would require either:
     * (a) inclusion of the fee as a parameter with verification; or
     * (b) iterative transfers which attempts to back-calculate the fee.
     */
    function swapTo(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 maxAmountIn,
        uint256 amountOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 amountIn) {
        IERC20[] memory _tokens = tokens();
        (uint256 i, uint256 j) = _getIJ(_tokens, fromToken, toToken);
        uint256[] memory reserves = _updatePumps(_tokens.length);

        reserves[j] -= amountOut;
        uint256 reserveIBefore = reserves[i];
        reserves[i] = _calcReserve(wellFunction(), reserves, i, totalSupply());

        // Note: The rounding approach of the Well function determines whether
        // slippage from imprecision goes to the Well or to the User.
        amountIn = reserves[i] - reserveIBefore;

        if (amountIn > maxAmountIn) {
            revert SlippageIn(amountIn, maxAmountIn);
        }

        _swapTo(fromToken, toToken, amountIn, amountOut, recipient);
        _setReserves(_tokens, reserves);
    }

    /**
     * @dev Executes token transfers and emits Swap event. Used by {swapTo} to
     * avoid stack too deep errors.
     */
    function _swapTo(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountIn,
        uint256 amountOut,
        address recipient
    ) internal {
        fromToken.safeTransferFrom(msg.sender, address(this), amountIn);
        toToken.safeTransfer(recipient, amountOut);
        emit Swap(fromToken, toToken, amountIn, amountOut, recipient);
    }

    /**
     * @dev Assumes both tokens incur no fee on transfer.
     */
    function getSwapIn(
        IERC20 fromToken,
        IERC20 toToken,
        uint256 amountOut
    ) external view readOnlyNonReentrant returns (uint256 amountIn) {
        IERC20[] memory _tokens = tokens();
        (uint256 i, uint256 j) = _getIJ(_tokens, fromToken, toToken);
        uint256[] memory reserves = _getReserves(_tokens.length);

        reserves[j] -= amountOut;

        amountIn = _calcReserve(wellFunction(), reserves, i, totalSupply()) - reserves[i];
    }

    //////////////////// SHIFT ////////////////////

    /**
     * @dev When using Wells for a multi-hop swap in 1 single transaction using a
     * multicall contract like Pipeline, costs can be reduced by "shifting" tokens
     * from one Well to another rather than returning them to the multicall router.
     *
     * Example multi-hop swap: WETH -> DAI -> USDC
     *
     * 1. Using a router without {shift}:
     *  WETH.transfer(sender=0xUSER, recipient=0xROUTER)                     [1]
     *  Call the router, which performs:
     *      Well1.swapFrom(fromToken=WETH, toToken=DAI, recipient=0xROUTER)
     *          WETH.transfer(sender=0xROUTER, recipient=Well1)              [2]
     *          DAI.transfer(sender=Well1, recipient=0xROUTER)               [3]
     *      Well2.swapFrom(fromToken=DAI, toToken=USDC, recipient=0xROUTER)
     *          DAI.transfer(sender=0xROUTER, recipient=Well2)               [4]
     *          USDC.transfer(sender=Well2, recipient=0xROUTER)              [5]
     *  USDC.transfer(sender=0xROUTER, recipient=0xUSER)                     [6]
     *
     *  Note: this could be optimized by configuring the router to deliver
     *  tokens from the last swap directly to the user.
     *
     * 2. Using a router with {shift}:
     *  WETH.transfer(sender=0xUSER, recipient=Well1)                        [1]
     *  Call the router, which performs:
     *      Well1.shift(tokenOut=DAI, recipient=Well2)
     *          DAI.transfer(sender=Well1, recipient=Well2)                  [2]
     *      Well2.shift(tokenOut=USDC, recipient=0xUSER)
     *          USDC.transfer(sender=Well2, recipient=0xUSER)                [3]
     */
    function shift(
        IERC20 tokenOut,
        uint256 minAmountOut,
        address recipient
    ) external nonReentrant returns (uint256 amountOut) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        _updatePumps(tokensLength);

        uint256[] memory reserves = new uint256[](tokensLength);

        // Use the balances of the pool instead of the stored reserves.
        // If there is a change in token balances relative to the currently
        // stored reserves, the extra tokens can be shifted into `tokenOut`.
        for (uint256 i; i < tokensLength; ++i) {
            reserves[i] = _tokens[i].balanceOf(address(this));
        }
        uint256 j = _getJ(_tokens, tokenOut);
        amountOut = reserves[j] - _calcReserve(wellFunction(), reserves, j, totalSupply());

        if (amountOut >= minAmountOut) {
            tokenOut.safeTransfer(recipient, amountOut);
            reserves[j] -= amountOut;
            _setReserves(_tokens, reserves);
            emit Shift(reserves, tokenOut, amountOut, recipient);
        } else {
            revert SlippageOut(amountOut, minAmountOut);
        }
    }

    function getShiftOut(IERC20 tokenOut) external view readOnlyNonReentrant returns (uint256 amountOut) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = new uint256[](tokensLength);
        for (uint256 i; i < tokensLength; ++i) {
            reserves[i] = _tokens[i].balanceOf(address(this));
        }

        uint256 j = _getJ(_tokens, tokenOut);
        amountOut = reserves[j] - _calcReserve(wellFunction(), reserves, j, totalSupply());
    }

    //////////////////// ADD LIQUIDITY ////////////////////

    function addLiquidity(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 lpAmountOut) {
        lpAmountOut = _addLiquidity(tokenAmountsIn, minLpAmountOut, recipient, false);
    }

    function addLiquidityFeeOnTransfer(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 lpAmountOut) {
        lpAmountOut = _addLiquidity(tokenAmountsIn, minLpAmountOut, recipient, true);
    }

    /**
     * @dev Gas optimization: {IWell.AddLiquidity} is emitted even if `lpAmountOut` is 0.
     */
    function _addLiquidity(
        uint256[] memory tokenAmountsIn,
        uint256 minLpAmountOut,
        address recipient,
        bool feeOnTransfer
    ) internal returns (uint256 lpAmountOut) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = _updatePumps(tokensLength);

        uint256 _tokenAmountIn;
        if (feeOnTransfer) {
            for (uint256 i; i < tokensLength; ++i) {
                _tokenAmountIn = tokenAmountsIn[i];
                if (_tokenAmountIn == 0) continue;
                _tokenAmountIn = _safeTransferFromFeeOnTransfer(_tokens[i], msg.sender, _tokenAmountIn);
                reserves[i] += _tokenAmountIn;
                tokenAmountsIn[i] = _tokenAmountIn;
            }
        } else {
            for (uint256 i; i < tokensLength; ++i) {
                _tokenAmountIn = tokenAmountsIn[i];
                if (_tokenAmountIn == 0) continue;
                _tokens[i].safeTransferFrom(msg.sender, address(this), _tokenAmountIn);
                reserves[i] += _tokenAmountIn;
            }
        }

        lpAmountOut = _calcLpTokenSupply(wellFunction(), reserves) - totalSupply();
        if (lpAmountOut < minLpAmountOut) {
            revert SlippageOut(lpAmountOut, minLpAmountOut);
        }

        _mint(recipient, lpAmountOut);
        _setReserves(_tokens, reserves);
        emit AddLiquidity(tokenAmountsIn, lpAmountOut, recipient);
    }

    /**
     * @dev Assumes that no tokens involved incur a fee on transfer.
     */
    function getAddLiquidityOut(uint256[] memory tokenAmountsIn)
        external
        view
        readOnlyNonReentrant
        returns (uint256 lpAmountOut)
    {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = _getReserves(tokensLength);
        for (uint256 i; i < tokensLength; ++i) {
            reserves[i] += tokenAmountsIn[i];
        }
        lpAmountOut = _calcLpTokenSupply(wellFunction(), reserves) - totalSupply();
    }

    //////////////////// REMOVE LIQUIDITY: BALANCED ////////////////////

    function removeLiquidity(
        uint256 lpAmountIn,
        uint256[] calldata minTokenAmountsOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256[] memory tokenAmountsOut) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = _updatePumps(tokensLength);

        tokenAmountsOut = _calcLPTokenUnderlying(wellFunction(), lpAmountIn, reserves, totalSupply());
        _burn(msg.sender, lpAmountIn);
        uint256 _tokenAmountOut;
        for (uint256 i; i < tokensLength; ++i) {
            _tokenAmountOut = tokenAmountsOut[i];
            if (_tokenAmountOut < minTokenAmountsOut[i]) {
                revert SlippageOut(_tokenAmountOut, minTokenAmountsOut[i]);
            }
            _tokens[i].safeTransfer(recipient, _tokenAmountOut);
            reserves[i] -= _tokenAmountOut;
        }

        _setReserves(_tokens, reserves);
        emit RemoveLiquidity(lpAmountIn, tokenAmountsOut, recipient);
    }

    function getRemoveLiquidityOut(uint256 lpAmountIn)
        external
        view
        readOnlyNonReentrant
        returns (uint256[] memory tokenAmountsOut)
    {
        IERC20[] memory _tokens = tokens();
        uint256[] memory reserves = _getReserves(_tokens.length);
        uint256 lpTokenSupply = totalSupply();

        tokenAmountsOut = _calcLPTokenUnderlying(wellFunction(), lpAmountIn, reserves, lpTokenSupply);
    }

    //////////////////// REMOVE LIQUIDITY: ONE TOKEN ////////////////////

    function removeLiquidityOneToken(
        uint256 lpAmountIn,
        IERC20 tokenOut,
        uint256 minTokenAmountOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 tokenAmountOut) {
        IERC20[] memory _tokens = tokens();
        uint256[] memory reserves = _updatePumps(_tokens.length);
        uint256 j = _getJ(_tokens, tokenOut);

        tokenAmountOut = _getRemoveLiquidityOneTokenOut(lpAmountIn, j, reserves);
        if (tokenAmountOut < minTokenAmountOut) {
            revert SlippageOut(tokenAmountOut, minTokenAmountOut);
        }

        _burn(msg.sender, lpAmountIn);
        tokenOut.safeTransfer(recipient, tokenAmountOut);

        reserves[j] -= tokenAmountOut;
        _setReserves(_tokens, reserves);
        emit RemoveLiquidityOneToken(lpAmountIn, tokenOut, tokenAmountOut, recipient);
    }

    function getRemoveLiquidityOneTokenOut(
        uint256 lpAmountIn,
        IERC20 tokenOut
    ) external view readOnlyNonReentrant returns (uint256 tokenAmountOut) {
        IERC20[] memory _tokens = tokens();
        uint256[] memory reserves = _getReserves(_tokens.length);
        tokenAmountOut = _getRemoveLiquidityOneTokenOut(lpAmountIn, _getJ(_tokens, tokenOut), reserves);
    }

    /**
     * @dev Shared logic for removing a single token from liquidity.
     * Calculates change in reserve `j` given a change in LP token supply.
     *
     * Note: `lpAmountIn` is the amount of LP the user is burning in exchange
     * for some amount of token `j`.
     */
    function _getRemoveLiquidityOneTokenOut(
        uint256 lpAmountIn,
        uint256 j,
        uint256[] memory reserves
    ) private view returns (uint256 tokenAmountOut) {
        uint256 newReserveJ = _calcReserve(wellFunction(), reserves, j, totalSupply() - lpAmountIn);
        tokenAmountOut = reserves[j] - newReserveJ;
    }

    //////////// REMOVE LIQUIDITY: IMBALANCED ////////////

    function removeLiquidityImbalanced(
        uint256 maxLpAmountIn,
        uint256[] calldata tokenAmountsOut,
        address recipient,
        uint256 deadline
    ) external nonReentrant expire(deadline) returns (uint256 lpAmountIn) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = _updatePumps(tokensLength);

        uint256 _tokenAmountOut;
        for (uint256 i; i < tokensLength; ++i) {
            _tokenAmountOut = tokenAmountsOut[i];
            _tokens[i].safeTransfer(recipient, _tokenAmountOut);
            reserves[i] -= _tokenAmountOut;
        }

        lpAmountIn = totalSupply() - _calcLpTokenSupply(wellFunction(), reserves);
        if (lpAmountIn > maxLpAmountIn) {
            revert SlippageIn(lpAmountIn, maxLpAmountIn);
        }
        _burn(msg.sender, lpAmountIn);

        _setReserves(_tokens, reserves);
        emit RemoveLiquidity(lpAmountIn, tokenAmountsOut, recipient);
    }

    function getRemoveLiquidityImbalancedIn(uint256[] calldata tokenAmountsOut)
        external
        view
        readOnlyNonReentrant
        returns (uint256 lpAmountIn)
    {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = _getReserves(tokensLength);
        for (uint256 i; i < tokensLength; ++i) {
            reserves[i] -= tokenAmountsOut[i];
        }
        lpAmountIn = totalSupply() - _calcLpTokenSupply(wellFunction(), reserves);
    }

    //////////////////// RESERVES ////////////////////

    /**
     * @dev Can be used in a multicall to add liquidity similar to how `shift` can be used to swap.
     * See {shift} for examples of how to use in a multicall.
     */
    function sync(address recipient, uint256 minLpAmountOut) external nonReentrant returns (uint256 lpAmountOut) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        _updatePumps(tokensLength);
        uint256[] memory reserves = new uint256[](tokensLength);
        for (uint256 i; i < tokensLength; ++i) {
            reserves[i] = _tokens[i].balanceOf(address(this));
        }
        uint256 newTokenSupply = _calcLpTokenSupply(wellFunction(), reserves);
        uint256 oldTokenSupply = totalSupply();
        if (newTokenSupply > oldTokenSupply) {
            lpAmountOut = newTokenSupply - oldTokenSupply;
            _mint(recipient, lpAmountOut);
        }

        if (lpAmountOut < minLpAmountOut) {
            revert SlippageOut(lpAmountOut, minLpAmountOut);
        }

        _setReserves(_tokens, reserves);
        emit Sync(reserves, lpAmountOut, recipient);
    }

    function getSyncOut() external view readOnlyNonReentrant returns (uint256 lpAmountOut) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;

        uint256[] memory reserves = new uint256[](tokensLength);
        for (uint256 i; i < tokensLength; ++i) {
            reserves[i] = _tokens[i].balanceOf(address(this));
        }

        uint256 newTokenSupply = _calcLpTokenSupply(wellFunction(), reserves);
        uint256 oldTokenSupply = totalSupply();
        if (newTokenSupply > oldTokenSupply) {
            lpAmountOut = newTokenSupply - oldTokenSupply;
        }
    }

    /**
     * @dev Transfer excess tokens held by the Well to `recipient`.
     */
    function skim(address recipient) external nonReentrant returns (uint256[] memory skimAmounts) {
        IERC20[] memory _tokens = tokens();
        uint256 tokensLength = _tokens.length;
        uint256[] memory reserves = _getReserves(tokensLength);
        skimAmounts = new uint256[](tokensLength);
        for (uint256 i; i < tokensLength; ++i) {
            skimAmounts[i] = _tokens[i].balanceOf(address(this)) - reserves[i];
            if (skimAmounts[i] > 0) {
                _tokens[i].safeTransfer(recipient, skimAmounts[i]);
            }
        }
    }

    function getReserves() external view readOnlyNonReentrant returns (uint256[] memory reserves) {
        reserves = _getReserves(numberOfTokens());
    }

    /**
     * @dev Gets the Well's token reserves by reading from byte storage.
     */
    function _getReserves(uint256 _numberOfTokens) internal view returns (uint256[] memory reserves) {
        reserves = LibBytes.readUint128(RESERVES_STORAGE_SLOT, _numberOfTokens);
    }

    /**
     * @dev Checks that the balance of each ERC-20 token is >= the reserves and
     * sets the Well's reserves of each token by writing to byte storage.
     */
    function _setReserves(IERC20[] memory _tokens, uint256[] memory reserves) internal {
        for (uint256 i; i < reserves.length; ++i) {
            if (reserves[i] > _tokens[i].balanceOf(address(this))) revert InvalidReserves();
        }
        LibBytes.storeUint128(RESERVES_STORAGE_SLOT, reserves);
    }

    //////////////////// INTERNAL: UPDATE PUMPS ////////////////////

    /**
     * @dev Fetches the current token reserves of the Well and updates the Pumps.
     * Typically called before an operation that modifies the Well's reserves.
     */
    function _updatePumps(uint256 _numberOfTokens) internal returns (uint256[] memory reserves) {
        reserves = _getReserves(_numberOfTokens);

        uint256 _numberOfPumps = numberOfPumps();
        if (_numberOfPumps == 0) {
            return reserves;
        }

        // gas optimization: avoid looping if there is only one pump
        if (_numberOfPumps == 1) {
            Call memory _pump = firstPump();
            // Don't revert if the update call fails.
            try IPump(_pump.target).update(reserves, _pump.data) {}
            catch {
                // ignore reversion. If an external shutoff mechanism is added to a Pump, it could be called here.
            }
        } else {
            Call[] memory _pumps = pumps();
            for (uint256 i; i < _pumps.length; ++i) {
                // Don't revert if the update call fails.
                try IPump(_pumps[i].target).update(reserves, _pumps[i].data) {}
                catch {
                    // ignore reversion. If an external shutoff mechanism is added to a Pump, it could be called here.
                }
            }
        }
    }

    //////////////////// INTERNAL: WELL FUNCTION INTERACTION ////////////////////

    /**
     * @dev Calculates the LP token supply given a list of `reserves` using the
     * provided `_wellFunction`. Wraps {IWellFunction.calcLpTokenSupply}.
     *
     * The Well function is passed as a parameter to minimize gas in instances
     * where it is called multiple times in one transaction.
     */
    function _calcLpTokenSupply(
        Call memory _wellFunction,
        uint256[] memory reserves
    ) internal view returns (uint256 lpTokenSupply) {
        lpTokenSupply = IWellFunction(_wellFunction.target).calcLpTokenSupply(reserves, _wellFunction.data);
    }

    /**
     * @dev Calculates the `j`th reserve given a list of `reserves` and `lpTokenSupply`
     * using the provided `_wellFunction`. Wraps {IWellFunction.calcReserve}.
     *
     * The Well function is passed as a parameter to minimize gas in instances
     * where it is called multiple times in one transaction.
     */
    function _calcReserve(
        Call memory _wellFunction,
        uint256[] memory reserves,
        uint256 j,
        uint256 lpTokenSupply
    ) internal view returns (uint256 reserve) {
        reserve = IWellFunction(_wellFunction.target).calcReserve(reserves, j, lpTokenSupply, _wellFunction.data);
    }

    /**
     * @dev Calculates the amount of tokens that underly a given amount of LP tokens
     * Wraps {IWellFunction.calcLPTokenAmount}.
     *
     * Used to determine the how many tokens to send to a user when they remove LP.
     *
     * The Well function is passed as a parameter to minimize gas in instances
     * where it is called multiple times in one transaction.
     */
    function _calcLPTokenUnderlying(
        Call memory _wellFunction,
        uint256 lpTokenAmount,
        uint256[] memory reserves,
        uint256 lpTokenSupply
    ) internal view returns (uint256[] memory tokenAmounts) {
        tokenAmounts = IWellFunction(_wellFunction.target).calcLPTokenUnderlying(
            lpTokenAmount, reserves, lpTokenSupply, _wellFunction.data
        );
    }

    //////////////////// INTERNAL: WELL TOKEN INDEXING ////////////////////

    /**
     * @dev Returns the indices of `iToken` and `jToken` in `_tokens`.
     * Reverts if either token is not in `_tokens`.
     * Reverts if `iToken` and `jToken` are the same.
     */
    function _getIJ(
        IERC20[] memory _tokens,
        IERC20 iToken,
        IERC20 jToken
    ) internal pure returns (uint256 i, uint256 j) {
        bool foundOne;
        for (uint256 k; k < _tokens.length; ++k) {
            if (iToken == _tokens[k]) {
                i = k;
                if (foundOne) return (i, j);
                foundOne = true;
            } else if (jToken == _tokens[k]) {
                j = k;
                if (foundOne) return (i, j);
                foundOne = true;
            }
        }
        revert InvalidTokens();
    }

    /**
     * @dev Returns the index of `jToken` in `_tokens`. Reverts if `jToken` is
     * not in `_tokens`.
     *
     * If `_tokens` contains multiple instances of `jToken`, this will return
     * the first one. A {Well} with duplicate tokens has been misconfigured.
     */
    function _getJ(IERC20[] memory _tokens, IERC20 jToken) internal pure returns (uint256 j) {
        for (j; j < _tokens.length; ++j) {
            if (jToken == _tokens[j]) {
                return j;
            }
        }
        revert InvalidTokens();
    }

    //////////////////// INTERNAL: TRANSFER HELPERS ////////////////////

    /**
     * @dev Calculates the change in token balance of the Well across a transfer.
     * Used when a fee might be incurred during safeTransferFrom.
     */
    function _safeTransferFromFeeOnTransfer(
        IERC20 token,
        address from,
        uint256 amount
    ) internal returns (uint256 amountTransferred) {
        uint256 balanceBefore = token.balanceOf(address(this));
        token.safeTransferFrom(from, address(this), amount);
        amountTransferred = token.balanceOf(address(this)) - balanceBefore;
    }

    //////////////////// INTERNAL: EXPIRY ////////////////////

    /**
     * @dev Reverts if the deadline has passed.
     */
    modifier expire(uint256 deadline) {
        if (block.timestamp > deadline) {
            revert Expired();
        }
        _;
    }

    //////////////////// INTERNAL: Read Only Reentrancy ////////////////////

    /**
     * @dev Reverts if the reentrncy guard has been entered.
     */
    modifier readOnlyNonReentrant() {
        // Use the same error as `ReentrancyGuardUpgradeable` instead of using a custom error for consistency.
        require(!_reentrancyGuardEntered(), "ReentrancyGuard: reentrant call");
        _;
    }
}

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "viaIR": true,
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"bytes16","name":"_maxPercentIncrease","type":"bytes16"},{"internalType":"bytes16","name":"_maxPercentDecrease","type":"bytes16"},{"internalType":"uint256","name":"_capInterval","type":"uint256"},{"internalType":"bytes16","name":"_alpha","type":"bytes16"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"NoTimePassed","type":"error"},{"inputs":[],"name":"NotInitialized","type":"error"},{"inputs":[],"name":"ALPHA","outputs":[{"internalType":"bytes16","name":"","type":"bytes16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CAP_INTERVAL","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LOG_MAX_DECREASE","outputs":[{"internalType":"bytes16","name":"","type":"bytes16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LOG_MAX_INCREASE","outputs":[{"internalType":"bytes16","name":"","type":"bytes16"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"}],"name":"readCappedReserves","outputs":[{"internalType":"uint256[]","name":"cappedReserves","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"readCumulativeReserves","outputs":[{"internalType":"bytes","name":"cumulativeReserves","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"readInstantaneousReserves","outputs":[{"internalType":"uint256[]","name":"emaReserves","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"}],"name":"readLastCappedReserves","outputs":[{"internalType":"uint256[]","name":"lastCappedReserves","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"}],"name":"readLastCumulativeReserves","outputs":[{"internalType":"bytes16[]","name":"cumulativeReserves","type":"bytes16[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"}],"name":"readLastInstantaneousReserves","outputs":[{"internalType":"uint256[]","name":"emaReserves","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"well","type":"address"},{"internalType":"bytes","name":"startCumulativeReserves","type":"bytes"},{"internalType":"uint256","name":"startTimestamp","type":"uint256"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"readTwaReserves","outputs":[{"internalType":"uint256[]","name":"twaReserves","type":"uint256[]"},{"internalType":"bytes","name":"cumulativeReserves","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256[]","name":"reserves","type":"uint256[]"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"update","outputs":[],"stateMutability":"nonpayable","type":"function"}]

61010034620000fc57601f6200446038819003918201601f19168301916001600160401b038311848410176200010057808492608094604052833981010312620000fc576200004e8162000114565b906200009c62000087620000656020840162000114565b6200008d620000876200008060606040880151970162000114565b966200012a565b62000448565b608052600160ff1b186200012a565b60a05260e05260c052604051613d9a9081620006c682396080518181816105bc01526135d7015260a05181818161019e0152613592015260c051818181610578015281816109e00152613778015260e0518181816105f70152610a220152f35b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b51906001600160801b031982168203620000fc57565b613fff8160801c617fff90818460f01c16928284145f146200014d575050505090565b5f9492936001607f1b9391926001600160701b0392600160701b9284831692919084816200043e57505060015b83620001945750613fff60f01b9998505050505050505050565b8781880393105f14620002b3576070831315620001bf5750613fff60f01b9998505050505050505050565b5f8313156200026b5750501c905b019384600160711b81101562000259575b5082036200020657505050505f14620001fd576001600160f01b031990565b617fff60f01b90565b600160701b8410156200024e5750505f925b5f90156200024657505b6001600160801b031660709290921b919091171760801b6001600160801b03191690565b905062000222565b909392169162000218565b600180929496501c9401915f620001de565b9098979695949391606f198112156200028a5750505050505050505090565b5f9192939495969798995012620002a3575b50620001cd565b9350613ffe1984011c5f6200029c565b94969495929390505f821315620004215750600160711b915f1901945b6070821315620003c4575060019250505b818110620003b75703925b8315620003ad57620002fe84620005f1565b938460718103620003655750600180939495501c169201925b830362000334575050505f14620001fd576001600160f01b031990565b9091925f905f146200024657506001600160801b031660709290921b919091171760801b6001600160801b03191690565b92939260701115620003a157846070038084115f146200038f571b1692606f199101019262000317565b50929350505f19011b905f9262000317565b91949116925062000317565b5050505050505f90565b60019650900392620002ec565b6001821315620003e35750600191925f1980910191011c0190620002e1565b90606f19811215620003fa575050506001620002e1565b5f198091126200040d575b5050620002e1565b6001920190613fff19011c015f8062000405565b91945f821215620002d05794509160011b915f19850194620002d0565b909317926200017a565b608081901c6001607f1b8082111562000468575061ffff60ef1b92915050565b6001600160801b031991838316613fff60f01b036200048957505050505f90565b617fff91828560f01c169283145f14620004a4575050505090565b9293506001600160701b0390811692909180620005e157506001905b8315620005cf5761406f613fff831062000595575f92613ffe190194600f1b5b8083036200054357508262000538575b620004fb85620005f1565b94856070031b94606f19910101915b5f90156200052f5750905b60018060801b03809160701b1691161791161760801b1690565b90509062000515565b9360010193620004f0565b9092905f82156200058f575060015b60ff8091165b600160701b88106200056d575050506200050a565b9091945f190194800280831c978289189060011b0197607f011c919062000558565b62000552565b600192600160701b8610620005b257613ffe0394600f1b620004e0565b50620005be85620005f1565b948561406d0395607f031b620004e0565b506001600160f01b0319949350505050565b600160701b9093179290620004c0565b8015620000fc575f90600160801b811015620006b9575b80680100000000000000006002921015620006ac575b6401000000008110156200069f575b6201000081101562000692575b61010081101562000685575b601081101562000678575b60048110156200066c575b1015620006665790565b60010190565b91810191811c6200065c565b6004928301921c62000651565b6008928301921c62000646565b6010928301921c6200063a565b6020928301921c6200062d565b6040928301921c6200061e565b60809150811c6200060856fe60806040526004361015610011575f80fd5b5f3560e01c8063497163ef146100d45780635b1a7bbc146100cf5780635e1ef722146100ca5780636832326a146100c55780636de13cba146100c0578063944fc4dd146100bb5780639dc1a10e146100b6578063b0bb1c5a146100b1578063b1a66d94146100ac578063b89643d3146100a7578063d18a0706146100a25763d393b27a1461009d575f80fd5b6106bf565b61061a565b6105e0565b61059c565b610558565b610507565b610411565b6103f7565b61029f565b61021f565b61017e565b61010b565b9181601f840112156101075782359167ffffffffffffffff8311610107576020838186019501011161010757565b5f80fd5b346101075760403660031901126101075760043567ffffffffffffffff808211610107573660238301121561010757816004013590808211610107573660248360051b85010111610107576024359081116101075761017c9261017460249236906004016100d9565b50500161095d565b005b34610107575f3660031901126101075760206040516001600160801b03197f0000000000000000000000000000000000000000000000000000000000000000168152f35b600435906001600160a01b038216820361010757565b9081518082526020808093019301915f5b8281106101f7575050505090565b8351855293810193928101926001016101e9565b90602061021c9281815201906101d8565b90565b346101075760203660031901126101075761025761024361023e6101c2565b61343c565b6040519182916020835260208301906101d8565b0390f35b602090816040818301928281528551809452019301915f5b828110610281575050505090565b83516001600160801b03191685529381019392810192600101610273565b34610107576020366003190112610107576bffffffffffffffffffffffff196102c66101c2565b60601b16805460f81c9081156102fc57816102f0916102e761025794613d18565b60011b0161196e565b6040519182918261025b565b60046040517f87138d5c000000000000000000000000000000000000000000000000000000008152fd5b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761035c57604052565b610326565b81601f820112156101075780359067ffffffffffffffff821161035c5760405192610396601f8401601f19166020018561033a565b8284526020838301011161010757815f926020809301838601378301015290565b906040600319830112610107576004356001600160a01b038116810361010757916024359067ffffffffffffffff82116101075761021c91600401610361565b346101075761025761024361040b366103b7565b506136cf565b34610107576020366003190112610107576bffffffffffffffffffffffff1961045061043b6101c2565b60601b6bffffffffffffffffffffffff191690565b16805460f81c9081156102fc57816104719161046b82613d18565b0161196e565b9061047b8161193c565b915f5b8281106104935760405180610257868261020b565b806104b46001600160801b03196104ad6104c49486610949565b5116611c18565b6104be8287610949565b52610912565b61047e565b91908251928382525f5b8481106104f3575050825f602080949584010152601f8019910116010190565b6020818301810151848301820152016104d3565b3461010757610257610536610544610527610521366103b7565b5061386f565b6040519283916020830161025b565b03601f19810183528261033a565b6040519182916020835260208301906104c9565b34610107575f3660031901126101075760206040516001600160801b03197f0000000000000000000000000000000000000000000000000000000000000000168152f35b34610107575f3660031901126101075760206040516001600160801b03197f0000000000000000000000000000000000000000000000000000000000000000168152f35b34610107575f3660031901126101075760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346101075760203660031901126101075760ff61064f6bffffffffffffffffffffffff1961064961043b6101c2565b16611aff565b929190501680156102fc576106638161193c565b915f5b82811061067b5760405180610257868261020b565b806104b46001600160801b03196104ad6106959486610949565b610666565b90916106b161021c936040845260408401906101d8565b9160208184039101526104c9565b34610107576080366003190112610107576106d86101c2565b67ffffffffffffffff90602435828111610107576106fa9036906004016100d9565b92606435908111610107576107239261052161071a923690600401610361565b9281019061399e565b61072d825161193c565b61075861075361074964ffffffffff8060443516904216613d37565b64ffffffffff1690565b610dfe565b6001600160801b03198116156107fa575f5b84518110156107c857806107b96107b4846107af61079c61078e6107c3978c610949565b516001600160801b03191690565b6107a961078e878c610949565b906114bd565b613a44565b611c18565b6104be8286610949565b61076a565b604051836107eb826107dd896020830161025b565b03601f19810184528361033a565b6102576040519283928361069a565b60046040517f0b914749000000000000000000000000000000000000000000000000000000008152fd5b604051906080820182811067ffffffffffffffff82111761035c57604052606080835f81528160208201528160408201520152565b67ffffffffffffffff811161035c5760051b60200190565b929161087c82610859565b9161088a604051938461033a565b829481845260208094019160051b810192831161010757905b8282106108b05750505050565b813581529083019083016108a3565b634e487b7160e01b5f52601160045260245ffd5b5f198101919082116108e157565b6108bf565b81156108f0570490565b634e487b7160e01b5f52601260045260245ffd5b90600182018092116108e157565b5f1981146108e15760010190565b634e487b7160e01b5f52603260045260245ffd5b91908110156109445760051b0190565b610920565b80518210156109445760209160051b010190565b919091610968610824565b903360601b6bffffffffffffffffffffffff191661099f61098882611aff565b92915060208601928352859064ffffffffff169052565b64ffffffffff93846109b6825164ffffffffff1690565b1615610bc6576109d36109ce825164ffffffffff1690565b613d4e565b8015610bbc5793610a04857f0000000000000000000000000000000000000000000000000000000000000000611842565b94610a4c610753610a47610a20610a1a85610dfe565b946108d3565b7f0000000000000000000000000000000000000000000000000000000000000000906108e6565b610904565b9589610a5781613d18565b809701976060610a7b89610a6b858d61196e565b9b60408a019c8d52019d8e61196e565b96019586525f8092600160ff1b8518935b818110610ac557505050505050505082610ac39697610aaf610ab89351826118b0565b039351846118b0565b5192421691036119ed565b565b80610ba7610b9c8c8f8b610b838f8f98610b958f8f8f948f8f99610bac9f87610b8e61078e978f610b889f8499610b6e61078e9f61078e88610b8896610b62610b48610b629f95610b6896610b539f86610b749c610b2292610934565b35610b3161078e888851610949565b91508015610bb157610b4290610be2565b90613573565b610b53848451610949565b906001600160801b0319169052565b51610949565b91610e95565b906114cd565b91610b8361078e868951610949565b6114cd565b90611186565b9251610949565b9551610949565b610b53838d51610949565b610912565b610a8c565b50610b426001610be2565b5050505050509050565b505090610bd990610ac394953691610871565b91421690611b9a565b80610bec57505f90565b80610bf68161176c565b9160709182841015610de057508282031b915b6dffffffffffffffffffffffffffff80931691613fff918201811b936001600160801b03918286168517926001607f1b948585115f14610c5457505050505050505061ffff60ef1b90565b6001600160801b031995868660801b1697613fff60f01b89145f14610c8157505050505050505050505f90565b617fff8097861c169687145f14610c9f575050505050505050905090565b9193959750919380969816179580155f14610dd257506001915b8615610dbe5761406f908310610d89575f92613ffe190196600f1b5b808303610d2a575082610d1f575b90839291610cf08861176c565b978887031b97606f19910101915b5f9015610d175750935b1b1691161791161760801b1690565b905093610d08565b600190960195610ce3565b9092905f8215610d7e5750849392919060015b60ff8091165b600160701b8b10610d5657505050610cfe565b91800280821c80841860019c909c1b9b909b019a8897505f199690960195607f011c91610d43565b908594939291610d3d565b600192600160701b8810610da457613ffe0396600f1b610cd5565b50610dae8761176c565b968761406d0397607f031b610cd5565b50505050505050506001600160f01b031990565b9195600160701b1795610cb9565b8284929411610df0575b50610c09565b606f1982011c92505f610dea565b80610e0857505f90565b6001600160801b03199080610e1c8161176c565b906070821015610e595750906001600160801b036dffffffffffffffffffffffffffff91836070031b925b613fff0160701b1691161760801b1690565b60708211610e80575b506001600160801b036dffffffffffffffffffffffffffff91610e47565b606f1982011c91506001600160801b03610e62565b613fff8160801c617fff90818460f01c16928284145f14610eb7575050505090565b909192935f94600160701b906001607f1b946dffffffffffffffffffffffffffff93848216928481155f1461117d57505060015b83610f035750505050505050505050613fff60f01b90565b8781880393105f14611019576070831315610f2b5750505050505050505050613fff60f01b90565b5f831315610fd55750501c905b0193600160711b851015610fc6575b8203610f6c57505050505f14610f63576001600160f01b031990565b617fff60f01b90565b6001600160801b031994929190600160701b851015610fb35750506001600160801b03905f925b5f9015610fab5750915b60701b9116171760801b1690565b905091610f9d565b6001600160801b03929193941693610f93565b9193600190811c940191610f47565b9098979695949391606f19811215610ff35750505050505050505090565b5f919293949596979899501261100a575b50610f38565b9350613ffe1984011c5f611004565b979695929390505f8213156111625750600160711b915f1901965b607082131561110c575060019250505b81811061110157035b80156110f75761105c8161176c565b607181036110b6575090600191821c169301915b820361108b575050505f14610f63576001600160f01b031990565b6001600160801b03906001600160801b0319945f905f14610fab57509160701b9116171760801b1690565b94919060708610156110ee57856070038084115f146110dd571b169301606f190191611070565b50929450505f19011b915f91611070565b16935091611070565b5050505050505f90565b60019650900361104d565b60018213156111295750600191925f1980910191011c0190611044565b90606f1981121561113e575050506001611044565b5f1980911261114f575b5050611044565b6001920190613fff19011c015f80611148565b91965f8212156110345796509160011b915f19870196611034565b90931792610eeb565b908160801c617fff90818460f01c168360801c838560f01c16928483145f146111d557505050036111d1576001600160801b03198281169116036111c75790565b5061ffff60ef1b90565b5090565b84849594979697145f146111ec5750505050505090565b6001607f1b9283821015956dffffffffffffffffffffffffffff8093169180155f146114af57506001935b838682101591169180155f146114a2575060015b836112565750505050505050505050600160ff1b6001600160801b03198216145f1461021c57505f90565b82939495969798999a9192155f1461128e5750505050505050505050600160ff1b6001600160801b03198216145f1461021c57505f90565b808703928a8103611335575060708313156112b0575050505050505050505090565b90919293949596979899505f83135f146112f15750501c0193600160711b851015610fc6578203610f6c57505050505f14610f63576001600160f01b031990565b9098979695949391606f1981121561130f5750505050505050505090565b909192939495969798505f8112611328575b5050610f38565b9094505f031c5f80611321565b999a505f99939897969394915089831315611482575060011b915f1901965b607082131561142d5750506001915b8282106114245750035b801561141a5761137c8161176c565b607181036113d9575090600191821c169301915b82036113ac57505050505f14610f63576001600160f01b031990565b836001600160801b0319956001600160801b03939495505f14610fab57509160701b9116171760801b1690565b949190607086101561141157856070038084115f14611400571b169301606f190191611390565b50929450505f19011b918391611390565b16935091611390565b5050505050905090565b9750900361136d565b6001821315611447575f1990810191011c60010191611363565b9290606f1981121561145d575060019150611363565b5f1980821261146e575b5050611363565b806001939401918a03011c01905f80611467565b89839992949912611494575b50611354565b5f1901975060011b5f61148e565b91600160701b179161122b565b9391600160701b1791611217565b600160ff1b61021c921890611186565b617fff808260f01c16818460f01c16908281145f14611559575003611529576001600160801b03198181168382160361150c575090600160ff1b161890565b81831816600160ff1b0361151e571790565b505061ffff60ef1b90565b906f7fffffffffffffffffffffffffffffff60801b811661154f57505061ffff60ef1b90565b600160ff1b161890565b909392918085036115915750509091506f7fffffffffffffffffffffffffffffff60801b8116155f1461154f57505061ffff60ef1b90565b6dffffffffffffffffffffffffffff808460801c169280155f1461175757506001955b818660801c169080155f1461174957506001935b02928315611727576001600160801b03199601915f7c020000000000000000000000000000000000000000000000000000000085106116eb575060e1915b82840190614070938483105f1461163957505050505050506001607f1b5f92835b60701b921860801c16171760801b1690565b6140e083101561168957505050508082101561165f57031c916001607f1b905b5f611627565b8194929411611675575b506001607f1b90611659565b61406f19019290921b916001607f1b611669565b929591945092509061c0dd8411156116ad57505050506001607f1b90925f93611627565b92956001607f1b94509260708111156116d257606f19011c5b16936140de1901611627565b607081106116e1575b506116c6565b6070031b5f6116db565b507c010000000000000000000000000000000000000000000000000000000084106117195760e05b91611606565b6117228461176c565b611713565b50600160ff1b95505f949093188516159250611744915050575090565b905090565b9390600160701b17906115c8565b9592600160701b17926115b4565b1561010757565b611777811515611765565b5f90700100000000000000000000000000000000811015611837575b8068010000000000000000600292101561182b575b64010000000081101561181f575b62010000811015611813575b610100811015611807575b60108110156117fb575b60048110156117f0575b10156117ea5790565b60010190565b91810191811c6117e1565b6004928301921c6117d7565b6008928301921c6117cd565b6010928301921c6117c2565b6020928301921c6117b6565b6040928301921c6117a8565b60809150811c611793565b90919060018084161561188f57815b93811c91825b61186057505050565b8061186a916114cd565b918282821661187e575b50811c9182611857565b61188891956114cd565b935f611874565b613fff60f01b611851565b908160061b91808304604014901517156108e157565b908051600281145f146118d057506020604082015160801c910151019055565b60011c5f5b8181106119115750600180835116146118ee575b505050565b806118fa60209261189a565b9301926001600160801b0384541692010151019055565b8061191e6119379261189a565b84016020604082015160801c9101510181860155610912565b6118d5565b9061194682610859565b611953604051918261033a565b8281528092611964601f1991610859565b0190602036910137565b91906119798161193c565b92600282146119da57600190815b838111156119955750505050565b806119ab6119a56119c3936108d3565b60011c90565b81851685036119c8578301548160051b880152610912565b611987565b83015460801b8160051b880152610912565b546020840181905260801b604084015250565b91906119fa825160ff1690565b60ff81169060018214611acb5760026040928386015160981c9460209579ffffffffffffffffffffffffff000000000000000000000000008789015160301c1617908460f81b9060d01b1717875511611a55575b5050505050565b607f9060011c169060015b828110611aa257505060018084511614611a7b575b80611a4e565b611a848161189a565b9301926001600160801b03845416920101510190555f808080611a75565b80611aaf611ac69261189a565b8601858482015160801c9101510181880155610912565b611a60565b9279ffffffffffffffffffffffffff0000000000000000000000000091506020015160301c169160f81b9060d01b17179055565b80548060f81c928160d01c928415611b935760ff8516611b1e8161193c565b937fffffffffffffffffffffffffff000000000000000000000000000000000000008160301b16602086015260018092146118e95760981b604085015260ff86169160028311611b6d57505050565b60035b83811115611b7e5750505050565b806119ab6119a5611b8e936108d3565b611b70565b5060609150565b82519291611ba78461193c565b925f5b858110611bd0575050610ac393611bc584611bca93856119ed565b613d18565b016118b0565b611bda8183610949565b51908115611c0f57611bee611c0a92610be2565b6001600160801b0319611c018389610949565b91169052610912565b611baa565b50505050505050565b608081811c6001607f1b9283821192617fff809260f01c166dffffffffffffffffffffffffffff80941690838114806133ae575b15611c55575f80fd5b61400d811115611c7457505050505090505f905f14611c715790565b80fd5b613f7f811015611c8a5750505050505050600190565b806133a1575060015b613fef808211156133885750613fee19011b905b848061336d575b6110f7578415908180613352575b6101075782811c91826001600160801b038095169780613349575b61333b575b509085918891898916613323575b6f400000000000000000000000000000008916613307575b6f2000000000000000000000000000000089166132eb575b6f1000000000000000000000000000000089166132cf575b6f0800000000000000000000000000000089166132b3575b6f040000000000000000000000000000008916613297575b6f02000000000000000000000000000000891661327b575b6f01000000000000000000000000000000891661325f575b6e8000000000000000000000000000008916613243575b6e4000000000000000000000000000008916613227575b6e200000000000000000000000000000891661320b575b6e10000000000000000000000000000089166131ef575b6e08000000000000000000000000000089166131d3575b6e04000000000000000000000000000089166131b7575b600160711b891661319b575b600160701b9889811661317f575b6d80000000000000000000000000008116613163575b6d40000000000000000000000000008116613147575b6d2000000000000000000000000000811661312b575b6d1000000000000000000000000000811661310f575b6d080000000000000000000000000081166130f3575b6d040000000000000000000000000081166130d7575b6d020000000000000000000000000081166130bb575b6d0100000000000000000000000000811661309f575b6c800000000000000000000000008116613083575b6c400000000000000000000000008116613067575b6c20000000000000000000000000811661304b575b6c10000000000000000000000000811661302f575b6c080000000000000000000000008116613013575b6c040000000000000000000000008116612ff7575b6c020000000000000000000000008116612fdb575b6c010000000000000000000000008116612fbf575b6b8000000000000000000000008116612fa3575b6b4000000000000000000000008116612f87575b6b2000000000000000000000008116612f6b575b6b1000000000000000000000008116612f4f575b6b0800000000000000000000008116612f33575b6b0400000000000000000000008116612f17575b6b0200000000000000000000008116612efb575b6b0100000000000000000000008116612edf575b6a80000000000000000000008116612ec3575b6a40000000000000000000008116612ea7575b6a20000000000000000000008116612e8b575b6a10000000000000000000008116612e6f575b6a08000000000000000000008116612e53575b6a04000000000000000000008116612e37575b6a02000000000000000000008116612e1b575b6a01000000000000000000008116612dff575b69800000000000000000008116612de3575b69400000000000000000008116612dc7575b69200000000000000000008116612dab575b69100000000000000000008116612d8f575b69080000000000000000008116612d73575b69040000000000000000008116612d57575b69020000000000000000008116612d3b575b69010000000000000000008116612d1f575b688000000000000000008116612d03575b684000000000000000008116612ce7575b682000000000000000008116612ccb575b681000000000000000008116612caf575b680800000000000000008116612c93575b680400000000000000008116612c77575b680200000000000000008116612c5b575b680100000000000000008116612c3f575b6780000000000000008116612c23575b6740000000000000008116612c07575b6720000000000000008116612beb575b6710000000000000008116612bcf575b6708000000000000008116612bb3575b6704000000000000008116612b97575b6702000000000000008116612b7b575b6701000000000000008116612b5f575b66800000000000008116612b43575b66400000000000008116612b27575b66200000000000008116612b0b575b66100000000000008116612aef575b66080000000000008116612ad3575b66040000000000008116612ab7575b66020000000000008116612a9b575b66010000000000008116612a7f575b658000000000008116612a63575b654000000000008116612a47575b652000000000008116612a2b575b651000000000008116612a0f575b6508000000000081166129f3575b6504000000000081166129d7575b6502000000000081166129bb575b65010000000000811661299f575b6480000000008116612983575b6440000000008116612967575b642000000000811661294b575b641000000000811661292f575b6408000000008116612913575b64040000000081166128f7575b64020000000081166128db575b64010000000081166128bf575b638000000081166128a3575b63400000008116612887575b6320000000811661286b575b6310000000811661284f575b63080000008116612833575b63040000008116612817575b630200000081166127fb575b630100000081166127df575b6280000081166127c3575b6240000081166127a7575b62200000811661278b575b62100000811661276f575b620800008116612753575b620400008116612737575b62020000811661271b575b6201000081166126ff575b61800081166126e3575b61400081166126c7575b61200081166126ab575b611000811661268f575b6108008116612673575b6104008116612657575b610200811661263b575b610100811661261f575b818116612603575b604081166125e7575b602081166125cb575b601081166125af575b60088116612592575b600416612574575b501561254e57600f1c1690613fff015b60701b17918260701c1694613fff86106110f75761251a91831610611765565b6125286140fe851115611765565b16179061406f8082101561253b57031c90565b8111612545575090565b61406e19011b90565b613ffe831161256557600f1c1690613fff036124fa565b919050613fee19011c5f6124fa565b909170010000000000000000000000000000000102901c905f6124ea565b700100000000000000000000000000000004909302811c926124e2565b9270010000000000000000000000000000000a02811c926124d9565b9270010000000000000000000000000000001502811c926124d0565b9270010000000000000000000000000000002b02811c926124c7565b9270010000000000000000000000000000005702811c926124be565b927001000000000000000000000000000000b002811c926124b6565b9270010000000000000000000000000000016102811c926124ac565b927001000000000000000000000000000002c402811c926124a2565b9270010000000000000000000000000000058a02811c92612498565b92700100000000000000000000000000000b1602811c9261248e565b9270010000000000000000000000000000162d02811c92612484565b92700100000000000000000000000000002c5b02811c9261247a565b927001000000000000000000000000000058b802811c92612470565b9270010000000000000000000000000000b17102811c92612466565b927001000000000000000000000000000162e302811c9261245b565b9270010000000000000000000000000002c5c702811c92612450565b92700100000000000000000000000000058b8f02811c92612445565b927001000000000000000000000000000b172002811c9261243a565b92700100000000000000000000000000162e4102811c9261242f565b927001000000000000000000000000002c5c8402811c92612424565b9270010000000000000000000000000058b90a02811c92612419565b92700100000000000000000000000000b1721602811c9261240e565b9270010000000000000000000000000162e42e02811c92612402565b92700100000000000000000000000002c5c85e02811c926123f6565b927001000000000000000000000000058b90be02811c926123ea565b9270010000000000000000000000000b17217e02811c926123de565b927001000000000000000000000000162e42fd02811c926123d2565b9270010000000000000000000000002c5c85fc02811c926123c6565b92700100000000000000000000000058b90bfa02811c926123ba565b927001000000000000000000000000b17217f602811c926123ae565b92700100000000000000000000000162e42fee02811c926123a1565b927001000000000000000000000002c5c85fde02811c92612394565b9270010000000000000000000000058b90bfbd02811c92612387565b92700100000000000000000000000b17217f7c02811c9261237a565b9270010000000000000000000000162e42fef902811c9261236d565b92700100000000000000000000002c5c85fdf302811c92612360565b927001000000000000000000000058b90bfbe702811c92612353565b9270010000000000000000000000b17217f7d002811c92612346565b927001000000000000000000000162e42fefa202811c92612338565b9270010000000000000000000002c5c85fdf4602811c9261232a565b92700100000000000000000000058b90bfbe8d02811c9261231c565b927001000000000000000000000b17217f7d1b02811c9261230e565b92700100000000000000000000162e42fefa3802811c92612300565b927001000000000000000000002c5c85fdf47202811c926122f2565b9270010000000000000000000058b90bfbe8e602811c926122e4565b92700100000000000000000000b17217f7d1ce02811c926122d6565b9270010000000000000000000162e42fefa39d02811c926122c7565b92700100000000000000000002c5c85fdf473c02811c926122b8565b927001000000000000000000058b90bfbe8e7a02811c926122a9565b9270010000000000000000000b17217f7d1cf602811c9261229a565b927001000000000000000000162e42fefa39ee02811c9261228b565b9270010000000000000000002c5c85fdf473dd02811c9261227c565b92700100000000000000000058b90bfbe8e7bb02811c9261226d565b927001000000000000000000b17217f7d1cf7802811c9261225e565b92700100000000000000000162e42fefa39ef202811c9261224e565b927001000000000000000002c5c85fdf473de502811c9261223e565b9270010000000000000000058b90bfbe8e7bcc02811c9261222e565b92700100000000000000000b17217f7d1cf79902811c9261221e565b9270010000000000000000162e42fefa39ef3402811c9261220e565b92700100000000000000002c5c85fdf473de6a02811c926121fe565b927001000000000000000058b90bfbe8e7bcd502811c926121ee565b9270010000000000000000b17217f7d1cf79ab02811c926121de565b927001000000000000000162e42fefa39ef35802811c926121cd565b9270010000000000000002c5c85fdf473de6b202811c926121bc565b92700100000000000000058b90bfbe8e7bcd6d02811c926121ab565b927001000000000000000b17217f7d1cf79afa02811c9261219a565b92700100000000000000162e42fefa39ef366f02811c92612189565b927001000000000000002c5c85fdf473de6eca02811c92612178565b9270010000000000000058b90bfbe8e7bce54402811c92612167565b92700100000000000000b17217f7d1cf79e94902811c92612156565b9270010000000000000162e42fefa39ef44d9102811c92612144565b92700100000000000002c5c85fdf473dea871f02811c92612132565b927001000000000000058b90bfbe8e7bdcbe2e02811c92612120565b9270010000000000000b17217f7d1cf7d83c1a02811c9261210e565b927001000000000000162e42fefa39f02b772c02811c926120fc565b9270010000000000002c5c85fdf473e242ea3802811c926120ea565b92700100000000000058b90bfbe8e7cc35c3f002811c926120d8565b927001000000000000b17217f7d1cfb72b45e102811c926120c6565b92700100000000000162e42fefa39fe95583c202811c926120b3565b927001000000000002c5c85fdf4741bea6e77e02811c926120a0565b9270010000000000058b90bfbe8e8b2d3d4ede02811c9261208d565b92700100000000000b17217f7d1d351a389d4002811c9261207a565b9270010000000000162e42fefa3ae53369388c02811c92612067565b92700100000000002c5c85fdf477b662b2694502811c92612054565b927001000000000058b90bfbe8f71cb4e4b33d02811c92612041565b9270010000000000b17217f7d20cf927c8e94c02811c9261202e565b927001000000000162e42fefa494f1478fde0502811c9261201a565b9270010000000002c5c85fdf4b15de6f17eb0d02811c92612006565b92700100000000058b90bfbe9ddbac5e109cce02811c92611ff2565b927001000000000b17217f7d5a7716bba4a9ae02811c92611fde565b92700100000000162e42fefb2fed257559bdaa02811c92611fca565b927001000000002c5c85fdf84bd62ae30a74cc02811c92611fb6565b9270010000000058b90bfbf8479bd5a81b51ad02811c92611fa2565b92700100000000b17217f80f4ef5aadda4555402811c92611f8e565b9270010000000162e42ff0999ce3541b9fffcf02811c92611f79565b92700100000002c5c85fe31f35a6a30da1be5002811c92611f64565b927001000000058b90bfcdee5acd3c1cedc82302811c92611f4f565b9270010000000b17217fba9c739aa5819f44f902811c92611f3a565b927001000000162e42fff037df38aa2b219f0602811c92611f25565b9270010000002c5c8601cc6b9e94213c72737a02811c92611f10565b92700100000058b90c0b48c6be5df846c5b2ef02811c92611efb565b927001000000b1721835514b86e6d96efd1bfe02811c92611ee6565b92700100000162e430e5a18f6119e3c02282a502811c92611ed0565b927001000002c5c863b73f016468f6bac5ca2b02811c92611eba565b9270010000058b90cf1e6d97f9ca14dbcc162802811c92611ea4565b92700100000b1721bcfc99d9f890ea0691176302811c92611e8e565b9270010000162e43f4f831060e02d839a9d16d02811c92611e78565b92700100002c5c89d5ec6ca4d7c8acc017b7c902811c92611e62565b927001000058b91b5bc9ae2eed81e9b7d4cfab02811c92611e4c565b9270010000b17255775c040618bf4a4ade83fc02811c92611e36565b917001000162e525ee054754457d599529202602821c91611e28565b9170010002c5cc37da9491d0985c348c68e7b302821c91611e1c565b91700100058ba01fb9f96d6cacd4b180917c3d02821c91611e05565b917001000b175effdc76ba38e31671ca93972502821c91611dee565b91700100162f3904051fa128bca9c55c31e5df02821c91611dd7565b917001002c605e2e8cec506d21bfc89a23a00f02821c91611dc0565b9170010058c86da1c09ea1ff19d294cf2f679b02821c91611da9565b91700100b1afa5abcbed6129ab13ec11dc954302821c91611d92565b9170010163da9fb33356d84a66ae336dcdfa3f02821c91611d7a565b91700102c9a3e778060ee6f7caca4f7a29bde802821c91611d62565b917001059b0d31585743ae7c548eb68ca417fd02821c91611d4a565b9170010b5586cf9890f6298b92b71842a9836302821c91611d32565b917001172b83c7d517adcdf7c8c50eb14a791f02821c91611d1a565b917001306fe0a31b7152de8d5a46305c85edec02821c91611d02565b6fb504f333f9de6484597d89b3754abe9f9250611cea565b961996600101925085611cdc565b50871515611cd7565b50713fffffffffffffffffffffffffffffffffff8311611cbc565b5071406e000000000000000000000000000000008211611cae565b808210613398575b505090611ca7565b031c5f80613390565b90600160701b1790611c93565b50811515611c4c565b60209081818403126101075780519067ffffffffffffffff821161010757019180601f840112156101075782516133ed81610859565b936133fb604051958661033a565b818552838086019260051b820101928311610107578301905b828210613422575050505090565b81518152908301908301613414565b6040513d5f823e3d90fd5b9060405191630240bc6b60e21b83525f836004816001600160a01b0385165afa92831561356e575f93613544575b5060ff906134899060601b6bffffffffffffffffffffffff1916611aff565b91929092169182156102fc576107496134a99164ffffffffff4216613d37565b936134b38361193c565b94801561351757610753610a47610a206134cc936108d3565b915f5b8481106134dd575050505050565b806135086107b4866134f561078e6135129688610949565b610b42613502868a610949565b51610be2565b6104be828a610949565b6134cf565b505092905f5b81811061352b575090925050565b806107b96107b461078e61353f9489610949565b61351d565b6135666134899160ff93953d8091833e61355e818361033a565b8101906133b7565b93915061346a565b613431565b91909160016135828483613604565b5f0b036135ce57610b886135b7927f0000000000000000000000000000000000000000000000000000000000000000906114cd565b60016135c38383613604565b5f0b14611744575090565b610b886135fc927f0000000000000000000000000000000000000000000000000000000000000000906114cd565b60016135c382845b8060801c6f7fffffffffffffffffffffffffffffff808216926136716f7fff00000000000000000000000000009161363e83871115611765565b8660801c9384169661365284891115611765565b6001600160801b031980911691161480928115916136c5575b50611765565b1561367e57505050505f90565b6001607f1b9081111591106136a957156136a257111561369d575f1990565b600190565b50505f1990565b156136b5575050600190565b11156136c057600190565b5f1990565b905085105f61366b565b906001600160a01b035f6bffffffffffffffffffffffff198460601b1693600460405180948193630240bc6b60e21b8352165afa90811561356e575f91613856575b5060ff61371d84611aff565b9591929092169081156102fc5761074961373e8361374c9361046b82613d18565b9364ffffffffff4216613d37565b906137568161193c565b9582156138275761379c613775610753610a47610a20879996996108d3565b937f0000000000000000000000000000000000000000000000000000000000000000611842565b92600160ff1b8418925f5b8781106137b8575050505050505050565b806138186107b489610b888a610b8361078e876138128e610b6e8f8f8f9e6138229f9261380d61380361078e94610b6896610b42613502876137fd61078e828a610949565b93610949565b610b538484610949565b610949565b95610949565b6104be828d610949565b6137a7565b5091949250505f5b81811061383d575090925050565b806107b96107b461078e6138519489610949565b61382f565b613869913d8091833e61355e818361033a565b5f613711565b906001600160a01b03915f6bffffffffffffffffffffffff198260601b1691600460405180968193630240bc6b60e21b8352165afa801561356e5760ff935f91613985575b506138be82611aff565b93919590951680156102fc576138e7816138f59361046b6138e161074995613d18565b60011b90565b9564ffffffffff4216613d37565b9081156118e957613917610753610a47610a2061391186610dfe565b956108d3565b905f5b8651811015611a4e57806139526139488561393b61078e613980968b610949565b610b426135028689610949565b610b538389610949565b610ba761397661396561078e848c610949565b610b8888610b8361078e878d610949565b610b53838b610949565b61391a565b613998913d8091833e61355e818361033a565b5f6138b4565b60209081818403126101075780359067ffffffffffffffff821161010757019180601f840112156101075782356139d481610859565b936139e2604051958661033a565b818552838086019260051b820101928311610107578301905b828210613a09575050505090565b81356001600160801b0319811681036101075781529083019083016139fb565b15613a3057565b634e487b7160e01b5f52600160045260245ffd5b90617fff808360f01c16818360f01c16908281145f14613a6f57500361154f57505061ffff60ef1b90565b818303613ab4575050507dffffffffffffffffffffffffffff00000000000000000000000000000000811615613aaa57505061ffff60ef1b90565b18600160ff1b1690565b6f7fffffffffffffffffffffffffffffff60801b92848416613af6575050508216613ae457505061ffff60ef1b90565b600160ff1b911816617fff60f01b1790565b909392506dffffffffffffffffffffffffffff949194808460801c169580155f14613d0c57506001955b818460801c1686155f14613cf95780613cd3575b90613b3e916108e6565b908115613cba576001600160801b031996613b696d1000000000000000000000000000841015613a29565b5f6e0800000000000000000000000000008410613c795750613b8a8361176c565b915b878301906140718301821115613bbf5750505050506001607f1b91929350925f9360701b921860801c16171760801b1690565b909192939450613ffc9383858401105f14613bea575050505050509091506001607f1b5f9283611627565b83613f8c8401105f14613c4a5750505085820181811115613c1857506001607f1b93949503011b925f611627565b819396925094939410613c33575b50506001607f1b90611659565b9003613ffb19019290921c916001607f1b5f613c26565b6001607f1b96979591929850613f8d945060708111613c6e575b5016950301611627565b606f19011c5f613c64565b6e0400000000000000000000000000008410613c9c575060ff60725b1691613b8c565b50600160711b8310613cb15760ff6071613c95565b60ff6070613c95565b50600160ff1b95505f9450505018821615611744575090565b9550613b3e90613ce28761176c565b60e20397880160711901976001979192501b613b34565b90600160701b613b3e921760721b6108e6565b95600160701b17613b20565b5f1981019081116108e15760011c600181018091116108e15760051b90565b64ffffffffff91821690821603919082116108e157565b613d6064ffffffffff91824216613d37565b169056fea26469706673582212204f01a9cd7ed72dceb737fa39596c58cbf7a658716264fc5be10646422f7bfa1c64736f6c634300081400333ff50624dd2f1a9fbe76c8b439581062000000000000000000000000000000003ff505e1d27a3ee9bffd7f3dd1a3267100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c3ffeef368eb04325c526c2246eec3e5500000000000000000000000000000000

Deployed Bytecode

0x60806040526004361015610011575f80fd5b5f3560e01c8063497163ef146100d45780635b1a7bbc146100cf5780635e1ef722146100ca5780636832326a146100c55780636de13cba146100c0578063944fc4dd146100bb5780639dc1a10e146100b6578063b0bb1c5a146100b1578063b1a66d94146100ac578063b89643d3146100a7578063d18a0706146100a25763d393b27a1461009d575f80fd5b6106bf565b61061a565b6105e0565b61059c565b610558565b610507565b610411565b6103f7565b61029f565b61021f565b61017e565b61010b565b9181601f840112156101075782359167ffffffffffffffff8311610107576020838186019501011161010757565b5f80fd5b346101075760403660031901126101075760043567ffffffffffffffff808211610107573660238301121561010757816004013590808211610107573660248360051b85010111610107576024359081116101075761017c9261017460249236906004016100d9565b50500161095d565b005b34610107575f3660031901126101075760206040516001600160801b03197fbff57a013faca6c6a89eef57df18223900000000000000000000000000000000168152f35b600435906001600160a01b038216820361010757565b9081518082526020808093019301915f5b8281106101f7575050505090565b8351855293810193928101926001016101e9565b90602061021c9281815201906101d8565b90565b346101075760203660031901126101075761025761024361023e6101c2565b61343c565b6040519182916020835260208301906101d8565b0390f35b602090816040818301928281528551809452019301915f5b828110610281575050505090565b83516001600160801b03191685529381019392810192600101610273565b34610107576020366003190112610107576bffffffffffffffffffffffff196102c66101c2565b60601b16805460f81c9081156102fc57816102f0916102e761025794613d18565b60011b0161196e565b6040519182918261025b565b60046040517f87138d5c000000000000000000000000000000000000000000000000000000008152fd5b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761035c57604052565b610326565b81601f820112156101075780359067ffffffffffffffff821161035c5760405192610396601f8401601f19166020018561033a565b8284526020838301011161010757815f926020809301838601378301015290565b906040600319830112610107576004356001600160a01b038116810361010757916024359067ffffffffffffffff82116101075761021c91600401610361565b346101075761025761024361040b366103b7565b506136cf565b34610107576020366003190112610107576bffffffffffffffffffffffff1961045061043b6101c2565b60601b6bffffffffffffffffffffffff191690565b16805460f81c9081156102fc57816104719161046b82613d18565b0161196e565b9061047b8161193c565b915f5b8281106104935760405180610257868261020b565b806104b46001600160801b03196104ad6104c49486610949565b5116611c18565b6104be8287610949565b52610912565b61047e565b91908251928382525f5b8481106104f3575050825f602080949584010152601f8019910116010190565b6020818301810151848301820152016104d3565b3461010757610257610536610544610527610521366103b7565b5061386f565b6040519283916020830161025b565b03601f19810183528261033a565b6040519182916020835260208301906104c9565b34610107575f3660031901126101075760206040516001600160801b03197f3ffeef368eb04325c526c2246eec3e5500000000000000000000000000000000168152f35b34610107575f3660031901126101075760206040516001600160801b03197f3ff57a013faca6c6a8ba2fc9d3b9fd9400000000000000000000000000000000168152f35b34610107575f3660031901126101075760206040517f000000000000000000000000000000000000000000000000000000000000000c8152f35b346101075760203660031901126101075760ff61064f6bffffffffffffffffffffffff1961064961043b6101c2565b16611aff565b929190501680156102fc576106638161193c565b915f5b82811061067b5760405180610257868261020b565b806104b46001600160801b03196104ad6106959486610949565b610666565b90916106b161021c936040845260408401906101d8565b9160208184039101526104c9565b34610107576080366003190112610107576106d86101c2565b67ffffffffffffffff90602435828111610107576106fa9036906004016100d9565b92606435908111610107576107239261052161071a923690600401610361565b9281019061399e565b61072d825161193c565b61075861075361074964ffffffffff8060443516904216613d37565b64ffffffffff1690565b610dfe565b6001600160801b03198116156107fa575f5b84518110156107c857806107b96107b4846107af61079c61078e6107c3978c610949565b516001600160801b03191690565b6107a961078e878c610949565b906114bd565b613a44565b611c18565b6104be8286610949565b61076a565b604051836107eb826107dd896020830161025b565b03601f19810184528361033a565b6102576040519283928361069a565b60046040517f0b914749000000000000000000000000000000000000000000000000000000008152fd5b604051906080820182811067ffffffffffffffff82111761035c57604052606080835f81528160208201528160408201520152565b67ffffffffffffffff811161035c5760051b60200190565b929161087c82610859565b9161088a604051938461033a565b829481845260208094019160051b810192831161010757905b8282106108b05750505050565b813581529083019083016108a3565b634e487b7160e01b5f52601160045260245ffd5b5f198101919082116108e157565b6108bf565b81156108f0570490565b634e487b7160e01b5f52601260045260245ffd5b90600182018092116108e157565b5f1981146108e15760010190565b634e487b7160e01b5f52603260045260245ffd5b91908110156109445760051b0190565b610920565b80518210156109445760209160051b010190565b919091610968610824565b903360601b6bffffffffffffffffffffffff191661099f61098882611aff565b92915060208601928352859064ffffffffff169052565b64ffffffffff93846109b6825164ffffffffff1690565b1615610bc6576109d36109ce825164ffffffffff1690565b613d4e565b8015610bbc5793610a04857f3ffeef368eb04325c526c2246eec3e5500000000000000000000000000000000611842565b94610a4c610753610a47610a20610a1a85610dfe565b946108d3565b7f000000000000000000000000000000000000000000000000000000000000000c906108e6565b610904565b9589610a5781613d18565b809701976060610a7b89610a6b858d61196e565b9b60408a019c8d52019d8e61196e565b96019586525f8092600160ff1b8518935b818110610ac557505050505050505082610ac39697610aaf610ab89351826118b0565b039351846118b0565b5192421691036119ed565b565b80610ba7610b9c8c8f8b610b838f8f98610b958f8f8f948f8f99610bac9f87610b8e61078e978f610b889f8499610b6e61078e9f61078e88610b8896610b62610b48610b629f95610b6896610b539f86610b749c610b2292610934565b35610b3161078e888851610949565b91508015610bb157610b4290610be2565b90613573565b610b53848451610949565b906001600160801b0319169052565b51610949565b91610e95565b906114cd565b91610b8361078e868951610949565b6114cd565b90611186565b9251610949565b9551610949565b610b53838d51610949565b610912565b610a8c565b50610b426001610be2565b5050505050509050565b505090610bd990610ac394953691610871565b91421690611b9a565b80610bec57505f90565b80610bf68161176c565b9160709182841015610de057508282031b915b6dffffffffffffffffffffffffffff80931691613fff918201811b936001600160801b03918286168517926001607f1b948585115f14610c5457505050505050505061ffff60ef1b90565b6001600160801b031995868660801b1697613fff60f01b89145f14610c8157505050505050505050505f90565b617fff8097861c169687145f14610c9f575050505050505050905090565b9193959750919380969816179580155f14610dd257506001915b8615610dbe5761406f908310610d89575f92613ffe190196600f1b5b808303610d2a575082610d1f575b90839291610cf08861176c565b978887031b97606f19910101915b5f9015610d175750935b1b1691161791161760801b1690565b905093610d08565b600190960195610ce3565b9092905f8215610d7e5750849392919060015b60ff8091165b600160701b8b10610d5657505050610cfe565b91800280821c80841860019c909c1b9b909b019a8897505f199690960195607f011c91610d43565b908594939291610d3d565b600192600160701b8810610da457613ffe0396600f1b610cd5565b50610dae8761176c565b968761406d0397607f031b610cd5565b50505050505050506001600160f01b031990565b9195600160701b1795610cb9565b8284929411610df0575b50610c09565b606f1982011c92505f610dea565b80610e0857505f90565b6001600160801b03199080610e1c8161176c565b906070821015610e595750906001600160801b036dffffffffffffffffffffffffffff91836070031b925b613fff0160701b1691161760801b1690565b60708211610e80575b506001600160801b036dffffffffffffffffffffffffffff91610e47565b606f1982011c91506001600160801b03610e62565b613fff8160801c617fff90818460f01c16928284145f14610eb7575050505090565b909192935f94600160701b906001607f1b946dffffffffffffffffffffffffffff93848216928481155f1461117d57505060015b83610f035750505050505050505050613fff60f01b90565b8781880393105f14611019576070831315610f2b5750505050505050505050613fff60f01b90565b5f831315610fd55750501c905b0193600160711b851015610fc6575b8203610f6c57505050505f14610f63576001600160f01b031990565b617fff60f01b90565b6001600160801b031994929190600160701b851015610fb35750506001600160801b03905f925b5f9015610fab5750915b60701b9116171760801b1690565b905091610f9d565b6001600160801b03929193941693610f93565b9193600190811c940191610f47565b9098979695949391606f19811215610ff35750505050505050505090565b5f919293949596979899501261100a575b50610f38565b9350613ffe1984011c5f611004565b979695929390505f8213156111625750600160711b915f1901965b607082131561110c575060019250505b81811061110157035b80156110f75761105c8161176c565b607181036110b6575090600191821c169301915b820361108b575050505f14610f63576001600160f01b031990565b6001600160801b03906001600160801b0319945f905f14610fab57509160701b9116171760801b1690565b94919060708610156110ee57856070038084115f146110dd571b169301606f190191611070565b50929450505f19011b915f91611070565b16935091611070565b5050505050505f90565b60019650900361104d565b60018213156111295750600191925f1980910191011c0190611044565b90606f1981121561113e575050506001611044565b5f1980911261114f575b5050611044565b6001920190613fff19011c015f80611148565b91965f8212156110345796509160011b915f19870196611034565b90931792610eeb565b908160801c617fff90818460f01c168360801c838560f01c16928483145f146111d557505050036111d1576001600160801b03198281169116036111c75790565b5061ffff60ef1b90565b5090565b84849594979697145f146111ec5750505050505090565b6001607f1b9283821015956dffffffffffffffffffffffffffff8093169180155f146114af57506001935b838682101591169180155f146114a2575060015b836112565750505050505050505050600160ff1b6001600160801b03198216145f1461021c57505f90565b82939495969798999a9192155f1461128e5750505050505050505050600160ff1b6001600160801b03198216145f1461021c57505f90565b808703928a8103611335575060708313156112b0575050505050505050505090565b90919293949596979899505f83135f146112f15750501c0193600160711b851015610fc6578203610f6c57505050505f14610f63576001600160f01b031990565b9098979695949391606f1981121561130f5750505050505050505090565b909192939495969798505f8112611328575b5050610f38565b9094505f031c5f80611321565b999a505f99939897969394915089831315611482575060011b915f1901965b607082131561142d5750506001915b8282106114245750035b801561141a5761137c8161176c565b607181036113d9575090600191821c169301915b82036113ac57505050505f14610f63576001600160f01b031990565b836001600160801b0319956001600160801b03939495505f14610fab57509160701b9116171760801b1690565b949190607086101561141157856070038084115f14611400571b169301606f190191611390565b50929450505f19011b918391611390565b16935091611390565b5050505050905090565b9750900361136d565b6001821315611447575f1990810191011c60010191611363565b9290606f1981121561145d575060019150611363565b5f1980821261146e575b5050611363565b806001939401918a03011c01905f80611467565b89839992949912611494575b50611354565b5f1901975060011b5f61148e565b91600160701b179161122b565b9391600160701b1791611217565b600160ff1b61021c921890611186565b617fff808260f01c16818460f01c16908281145f14611559575003611529576001600160801b03198181168382160361150c575090600160ff1b161890565b81831816600160ff1b0361151e571790565b505061ffff60ef1b90565b906f7fffffffffffffffffffffffffffffff60801b811661154f57505061ffff60ef1b90565b600160ff1b161890565b909392918085036115915750509091506f7fffffffffffffffffffffffffffffff60801b8116155f1461154f57505061ffff60ef1b90565b6dffffffffffffffffffffffffffff808460801c169280155f1461175757506001955b818660801c169080155f1461174957506001935b02928315611727576001600160801b03199601915f7c020000000000000000000000000000000000000000000000000000000085106116eb575060e1915b82840190614070938483105f1461163957505050505050506001607f1b5f92835b60701b921860801c16171760801b1690565b6140e083101561168957505050508082101561165f57031c916001607f1b905b5f611627565b8194929411611675575b506001607f1b90611659565b61406f19019290921b916001607f1b611669565b929591945092509061c0dd8411156116ad57505050506001607f1b90925f93611627565b92956001607f1b94509260708111156116d257606f19011c5b16936140de1901611627565b607081106116e1575b506116c6565b6070031b5f6116db565b507c010000000000000000000000000000000000000000000000000000000084106117195760e05b91611606565b6117228461176c565b611713565b50600160ff1b95505f949093188516159250611744915050575090565b905090565b9390600160701b17906115c8565b9592600160701b17926115b4565b1561010757565b611777811515611765565b5f90700100000000000000000000000000000000811015611837575b8068010000000000000000600292101561182b575b64010000000081101561181f575b62010000811015611813575b610100811015611807575b60108110156117fb575b60048110156117f0575b10156117ea5790565b60010190565b91810191811c6117e1565b6004928301921c6117d7565b6008928301921c6117cd565b6010928301921c6117c2565b6020928301921c6117b6565b6040928301921c6117a8565b60809150811c611793565b90919060018084161561188f57815b93811c91825b61186057505050565b8061186a916114cd565b918282821661187e575b50811c9182611857565b61188891956114cd565b935f611874565b613fff60f01b611851565b908160061b91808304604014901517156108e157565b908051600281145f146118d057506020604082015160801c910151019055565b60011c5f5b8181106119115750600180835116146118ee575b505050565b806118fa60209261189a565b9301926001600160801b0384541692010151019055565b8061191e6119379261189a565b84016020604082015160801c9101510181860155610912565b6118d5565b9061194682610859565b611953604051918261033a565b8281528092611964601f1991610859565b0190602036910137565b91906119798161193c565b92600282146119da57600190815b838111156119955750505050565b806119ab6119a56119c3936108d3565b60011c90565b81851685036119c8578301548160051b880152610912565b611987565b83015460801b8160051b880152610912565b546020840181905260801b604084015250565b91906119fa825160ff1690565b60ff81169060018214611acb5760026040928386015160981c9460209579ffffffffffffffffffffffffff000000000000000000000000008789015160301c1617908460f81b9060d01b1717875511611a55575b5050505050565b607f9060011c169060015b828110611aa257505060018084511614611a7b575b80611a4e565b611a848161189a565b9301926001600160801b03845416920101510190555f808080611a75565b80611aaf611ac69261189a565b8601858482015160801c9101510181880155610912565b611a60565b9279ffffffffffffffffffffffffff0000000000000000000000000091506020015160301c169160f81b9060d01b17179055565b80548060f81c928160d01c928415611b935760ff8516611b1e8161193c565b937fffffffffffffffffffffffffff000000000000000000000000000000000000008160301b16602086015260018092146118e95760981b604085015260ff86169160028311611b6d57505050565b60035b83811115611b7e5750505050565b806119ab6119a5611b8e936108d3565b611b70565b5060609150565b82519291611ba78461193c565b925f5b858110611bd0575050610ac393611bc584611bca93856119ed565b613d18565b016118b0565b611bda8183610949565b51908115611c0f57611bee611c0a92610be2565b6001600160801b0319611c018389610949565b91169052610912565b611baa565b50505050505050565b608081811c6001607f1b9283821192617fff809260f01c166dffffffffffffffffffffffffffff80941690838114806133ae575b15611c55575f80fd5b61400d811115611c7457505050505090505f905f14611c715790565b80fd5b613f7f811015611c8a5750505050505050600190565b806133a1575060015b613fef808211156133885750613fee19011b905b848061336d575b6110f7578415908180613352575b6101075782811c91826001600160801b038095169780613349575b61333b575b509085918891898916613323575b6f400000000000000000000000000000008916613307575b6f2000000000000000000000000000000089166132eb575b6f1000000000000000000000000000000089166132cf575b6f0800000000000000000000000000000089166132b3575b6f040000000000000000000000000000008916613297575b6f02000000000000000000000000000000891661327b575b6f01000000000000000000000000000000891661325f575b6e8000000000000000000000000000008916613243575b6e4000000000000000000000000000008916613227575b6e200000000000000000000000000000891661320b575b6e10000000000000000000000000000089166131ef575b6e08000000000000000000000000000089166131d3575b6e04000000000000000000000000000089166131b7575b600160711b891661319b575b600160701b9889811661317f575b6d80000000000000000000000000008116613163575b6d40000000000000000000000000008116613147575b6d2000000000000000000000000000811661312b575b6d1000000000000000000000000000811661310f575b6d080000000000000000000000000081166130f3575b6d040000000000000000000000000081166130d7575b6d020000000000000000000000000081166130bb575b6d0100000000000000000000000000811661309f575b6c800000000000000000000000008116613083575b6c400000000000000000000000008116613067575b6c20000000000000000000000000811661304b575b6c10000000000000000000000000811661302f575b6c080000000000000000000000008116613013575b6c040000000000000000000000008116612ff7575b6c020000000000000000000000008116612fdb575b6c010000000000000000000000008116612fbf575b6b8000000000000000000000008116612fa3575b6b4000000000000000000000008116612f87575b6b2000000000000000000000008116612f6b575b6b1000000000000000000000008116612f4f575b6b0800000000000000000000008116612f33575b6b0400000000000000000000008116612f17575b6b0200000000000000000000008116612efb575b6b0100000000000000000000008116612edf575b6a80000000000000000000008116612ec3575b6a40000000000000000000008116612ea7575b6a20000000000000000000008116612e8b575b6a10000000000000000000008116612e6f575b6a08000000000000000000008116612e53575b6a04000000000000000000008116612e37575b6a02000000000000000000008116612e1b575b6a01000000000000000000008116612dff575b69800000000000000000008116612de3575b69400000000000000000008116612dc7575b69200000000000000000008116612dab575b69100000000000000000008116612d8f575b69080000000000000000008116612d73575b69040000000000000000008116612d57575b69020000000000000000008116612d3b575b69010000000000000000008116612d1f575b688000000000000000008116612d03575b684000000000000000008116612ce7575b682000000000000000008116612ccb575b681000000000000000008116612caf575b680800000000000000008116612c93575b680400000000000000008116612c77575b680200000000000000008116612c5b575b680100000000000000008116612c3f575b6780000000000000008116612c23575b6740000000000000008116612c07575b6720000000000000008116612beb575b6710000000000000008116612bcf575b6708000000000000008116612bb3575b6704000000000000008116612b97575b6702000000000000008116612b7b575b6701000000000000008116612b5f575b66800000000000008116612b43575b66400000000000008116612b27575b66200000000000008116612b0b575b66100000000000008116612aef575b66080000000000008116612ad3575b66040000000000008116612ab7575b66020000000000008116612a9b575b66010000000000008116612a7f575b658000000000008116612a63575b654000000000008116612a47575b652000000000008116612a2b575b651000000000008116612a0f575b6508000000000081166129f3575b6504000000000081166129d7575b6502000000000081166129bb575b65010000000000811661299f575b6480000000008116612983575b6440000000008116612967575b642000000000811661294b575b641000000000811661292f575b6408000000008116612913575b64040000000081166128f7575b64020000000081166128db575b64010000000081166128bf575b638000000081166128a3575b63400000008116612887575b6320000000811661286b575b6310000000811661284f575b63080000008116612833575b63040000008116612817575b630200000081166127fb575b630100000081166127df575b6280000081166127c3575b6240000081166127a7575b62200000811661278b575b62100000811661276f575b620800008116612753575b620400008116612737575b62020000811661271b575b6201000081166126ff575b61800081166126e3575b61400081166126c7575b61200081166126ab575b611000811661268f575b6108008116612673575b6104008116612657575b610200811661263b575b610100811661261f575b818116612603575b604081166125e7575b602081166125cb575b601081166125af575b60088116612592575b600416612574575b501561254e57600f1c1690613fff015b60701b17918260701c1694613fff86106110f75761251a91831610611765565b6125286140fe851115611765565b16179061406f8082101561253b57031c90565b8111612545575090565b61406e19011b90565b613ffe831161256557600f1c1690613fff036124fa565b919050613fee19011c5f6124fa565b909170010000000000000000000000000000000102901c905f6124ea565b700100000000000000000000000000000004909302811c926124e2565b9270010000000000000000000000000000000a02811c926124d9565b9270010000000000000000000000000000001502811c926124d0565b9270010000000000000000000000000000002b02811c926124c7565b9270010000000000000000000000000000005702811c926124be565b927001000000000000000000000000000000b002811c926124b6565b9270010000000000000000000000000000016102811c926124ac565b927001000000000000000000000000000002c402811c926124a2565b9270010000000000000000000000000000058a02811c92612498565b92700100000000000000000000000000000b1602811c9261248e565b9270010000000000000000000000000000162d02811c92612484565b92700100000000000000000000000000002c5b02811c9261247a565b927001000000000000000000000000000058b802811c92612470565b9270010000000000000000000000000000b17102811c92612466565b927001000000000000000000000000000162e302811c9261245b565b9270010000000000000000000000000002c5c702811c92612450565b92700100000000000000000000000000058b8f02811c92612445565b927001000000000000000000000000000b172002811c9261243a565b92700100000000000000000000000000162e4102811c9261242f565b927001000000000000000000000000002c5c8402811c92612424565b9270010000000000000000000000000058b90a02811c92612419565b92700100000000000000000000000000b1721602811c9261240e565b9270010000000000000000000000000162e42e02811c92612402565b92700100000000000000000000000002c5c85e02811c926123f6565b927001000000000000000000000000058b90be02811c926123ea565b9270010000000000000000000000000b17217e02811c926123de565b927001000000000000000000000000162e42fd02811c926123d2565b9270010000000000000000000000002c5c85fc02811c926123c6565b92700100000000000000000000000058b90bfa02811c926123ba565b927001000000000000000000000000b17217f602811c926123ae565b92700100000000000000000000000162e42fee02811c926123a1565b927001000000000000000000000002c5c85fde02811c92612394565b9270010000000000000000000000058b90bfbd02811c92612387565b92700100000000000000000000000b17217f7c02811c9261237a565b9270010000000000000000000000162e42fef902811c9261236d565b92700100000000000000000000002c5c85fdf302811c92612360565b927001000000000000000000000058b90bfbe702811c92612353565b9270010000000000000000000000b17217f7d002811c92612346565b927001000000000000000000000162e42fefa202811c92612338565b9270010000000000000000000002c5c85fdf4602811c9261232a565b92700100000000000000000000058b90bfbe8d02811c9261231c565b927001000000000000000000000b17217f7d1b02811c9261230e565b92700100000000000000000000162e42fefa3802811c92612300565b927001000000000000000000002c5c85fdf47202811c926122f2565b9270010000000000000000000058b90bfbe8e602811c926122e4565b92700100000000000000000000b17217f7d1ce02811c926122d6565b9270010000000000000000000162e42fefa39d02811c926122c7565b92700100000000000000000002c5c85fdf473c02811c926122b8565b927001000000000000000000058b90bfbe8e7a02811c926122a9565b9270010000000000000000000b17217f7d1cf602811c9261229a565b927001000000000000000000162e42fefa39ee02811c9261228b565b9270010000000000000000002c5c85fdf473dd02811c9261227c565b92700100000000000000000058b90bfbe8e7bb02811c9261226d565b927001000000000000000000b17217f7d1cf7802811c9261225e565b92700100000000000000000162e42fefa39ef202811c9261224e565b927001000000000000000002c5c85fdf473de502811c9261223e565b9270010000000000000000058b90bfbe8e7bcc02811c9261222e565b92700100000000000000000b17217f7d1cf79902811c9261221e565b9270010000000000000000162e42fefa39ef3402811c9261220e565b92700100000000000000002c5c85fdf473de6a02811c926121fe565b927001000000000000000058b90bfbe8e7bcd502811c926121ee565b9270010000000000000000b17217f7d1cf79ab02811c926121de565b927001000000000000000162e42fefa39ef35802811c926121cd565b9270010000000000000002c5c85fdf473de6b202811c926121bc565b92700100000000000000058b90bfbe8e7bcd6d02811c926121ab565b927001000000000000000b17217f7d1cf79afa02811c9261219a565b92700100000000000000162e42fefa39ef366f02811c92612189565b927001000000000000002c5c85fdf473de6eca02811c92612178565b9270010000000000000058b90bfbe8e7bce54402811c92612167565b92700100000000000000b17217f7d1cf79e94902811c92612156565b9270010000000000000162e42fefa39ef44d9102811c92612144565b92700100000000000002c5c85fdf473dea871f02811c92612132565b927001000000000000058b90bfbe8e7bdcbe2e02811c92612120565b9270010000000000000b17217f7d1cf7d83c1a02811c9261210e565b927001000000000000162e42fefa39f02b772c02811c926120fc565b9270010000000000002c5c85fdf473e242ea3802811c926120ea565b92700100000000000058b90bfbe8e7cc35c3f002811c926120d8565b927001000000000000b17217f7d1cfb72b45e102811c926120c6565b92700100000000000162e42fefa39fe95583c202811c926120b3565b927001000000000002c5c85fdf4741bea6e77e02811c926120a0565b9270010000000000058b90bfbe8e8b2d3d4ede02811c9261208d565b92700100000000000b17217f7d1d351a389d4002811c9261207a565b9270010000000000162e42fefa3ae53369388c02811c92612067565b92700100000000002c5c85fdf477b662b2694502811c92612054565b927001000000000058b90bfbe8f71cb4e4b33d02811c92612041565b9270010000000000b17217f7d20cf927c8e94c02811c9261202e565b927001000000000162e42fefa494f1478fde0502811c9261201a565b9270010000000002c5c85fdf4b15de6f17eb0d02811c92612006565b92700100000000058b90bfbe9ddbac5e109cce02811c92611ff2565b927001000000000b17217f7d5a7716bba4a9ae02811c92611fde565b92700100000000162e42fefb2fed257559bdaa02811c92611fca565b927001000000002c5c85fdf84bd62ae30a74cc02811c92611fb6565b9270010000000058b90bfbf8479bd5a81b51ad02811c92611fa2565b92700100000000b17217f80f4ef5aadda4555402811c92611f8e565b9270010000000162e42ff0999ce3541b9fffcf02811c92611f79565b92700100000002c5c85fe31f35a6a30da1be5002811c92611f64565b927001000000058b90bfcdee5acd3c1cedc82302811c92611f4f565b9270010000000b17217fba9c739aa5819f44f902811c92611f3a565b927001000000162e42fff037df38aa2b219f0602811c92611f25565b9270010000002c5c8601cc6b9e94213c72737a02811c92611f10565b92700100000058b90c0b48c6be5df846c5b2ef02811c92611efb565b927001000000b1721835514b86e6d96efd1bfe02811c92611ee6565b92700100000162e430e5a18f6119e3c02282a502811c92611ed0565b927001000002c5c863b73f016468f6bac5ca2b02811c92611eba565b9270010000058b90cf1e6d97f9ca14dbcc162802811c92611ea4565b92700100000b1721bcfc99d9f890ea0691176302811c92611e8e565b9270010000162e43f4f831060e02d839a9d16d02811c92611e78565b92700100002c5c89d5ec6ca4d7c8acc017b7c902811c92611e62565b927001000058b91b5bc9ae2eed81e9b7d4cfab02811c92611e4c565b9270010000b17255775c040618bf4a4ade83fc02811c92611e36565b917001000162e525ee054754457d599529202602821c91611e28565b9170010002c5cc37da9491d0985c348c68e7b302821c91611e1c565b91700100058ba01fb9f96d6cacd4b180917c3d02821c91611e05565b917001000b175effdc76ba38e31671ca93972502821c91611dee565b91700100162f3904051fa128bca9c55c31e5df02821c91611dd7565b917001002c605e2e8cec506d21bfc89a23a00f02821c91611dc0565b9170010058c86da1c09ea1ff19d294cf2f679b02821c91611da9565b91700100b1afa5abcbed6129ab13ec11dc954302821c91611d92565b9170010163da9fb33356d84a66ae336dcdfa3f02821c91611d7a565b91700102c9a3e778060ee6f7caca4f7a29bde802821c91611d62565b917001059b0d31585743ae7c548eb68ca417fd02821c91611d4a565b9170010b5586cf9890f6298b92b71842a9836302821c91611d32565b917001172b83c7d517adcdf7c8c50eb14a791f02821c91611d1a565b917001306fe0a31b7152de8d5a46305c85edec02821c91611d02565b6fb504f333f9de6484597d89b3754abe9f9250611cea565b961996600101925085611cdc565b50871515611cd7565b50713fffffffffffffffffffffffffffffffffff8311611cbc565b5071406e000000000000000000000000000000008211611cae565b808210613398575b505090611ca7565b031c5f80613390565b90600160701b1790611c93565b50811515611c4c565b60209081818403126101075780519067ffffffffffffffff821161010757019180601f840112156101075782516133ed81610859565b936133fb604051958661033a565b818552838086019260051b820101928311610107578301905b828210613422575050505090565b81518152908301908301613414565b6040513d5f823e3d90fd5b9060405191630240bc6b60e21b83525f836004816001600160a01b0385165afa92831561356e575f93613544575b5060ff906134899060601b6bffffffffffffffffffffffff1916611aff565b91929092169182156102fc576107496134a99164ffffffffff4216613d37565b936134b38361193c565b94801561351757610753610a47610a206134cc936108d3565b915f5b8481106134dd575050505050565b806135086107b4866134f561078e6135129688610949565b610b42613502868a610949565b51610be2565b6104be828a610949565b6134cf565b505092905f5b81811061352b575090925050565b806107b96107b461078e61353f9489610949565b61351d565b6135666134899160ff93953d8091833e61355e818361033a565b8101906133b7565b93915061346a565b613431565b91909160016135828483613604565b5f0b036135ce57610b886135b7927fbff57a013faca6c6a89eef57df18223900000000000000000000000000000000906114cd565b60016135c38383613604565b5f0b14611744575090565b610b886135fc927f3ff57a013faca6c6a8ba2fc9d3b9fd9400000000000000000000000000000000906114cd565b60016135c382845b8060801c6f7fffffffffffffffffffffffffffffff808216926136716f7fff00000000000000000000000000009161363e83871115611765565b8660801c9384169661365284891115611765565b6001600160801b031980911691161480928115916136c5575b50611765565b1561367e57505050505f90565b6001607f1b9081111591106136a957156136a257111561369d575f1990565b600190565b50505f1990565b156136b5575050600190565b11156136c057600190565b5f1990565b905085105f61366b565b906001600160a01b035f6bffffffffffffffffffffffff198460601b1693600460405180948193630240bc6b60e21b8352165afa90811561356e575f91613856575b5060ff61371d84611aff565b9591929092169081156102fc5761074961373e8361374c9361046b82613d18565b9364ffffffffff4216613d37565b906137568161193c565b9582156138275761379c613775610753610a47610a20879996996108d3565b937f3ffeef368eb04325c526c2246eec3e5500000000000000000000000000000000611842565b92600160ff1b8418925f5b8781106137b8575050505050505050565b806138186107b489610b888a610b8361078e876138128e610b6e8f8f8f9e6138229f9261380d61380361078e94610b6896610b42613502876137fd61078e828a610949565b93610949565b610b538484610949565b610949565b95610949565b6104be828d610949565b6137a7565b5091949250505f5b81811061383d575090925050565b806107b96107b461078e6138519489610949565b61382f565b613869913d8091833e61355e818361033a565b5f613711565b906001600160a01b03915f6bffffffffffffffffffffffff198260601b1691600460405180968193630240bc6b60e21b8352165afa801561356e5760ff935f91613985575b506138be82611aff565b93919590951680156102fc576138e7816138f59361046b6138e161074995613d18565b60011b90565b9564ffffffffff4216613d37565b9081156118e957613917610753610a47610a2061391186610dfe565b956108d3565b905f5b8651811015611a4e57806139526139488561393b61078e613980968b610949565b610b426135028689610949565b610b538389610949565b610ba761397661396561078e848c610949565b610b8888610b8361078e878d610949565b610b53838b610949565b61391a565b613998913d8091833e61355e818361033a565b5f6138b4565b60209081818403126101075780359067ffffffffffffffff821161010757019180601f840112156101075782356139d481610859565b936139e2604051958661033a565b818552838086019260051b820101928311610107578301905b828210613a09575050505090565b81356001600160801b0319811681036101075781529083019083016139fb565b15613a3057565b634e487b7160e01b5f52600160045260245ffd5b90617fff808360f01c16818360f01c16908281145f14613a6f57500361154f57505061ffff60ef1b90565b818303613ab4575050507dffffffffffffffffffffffffffff00000000000000000000000000000000811615613aaa57505061ffff60ef1b90565b18600160ff1b1690565b6f7fffffffffffffffffffffffffffffff60801b92848416613af6575050508216613ae457505061ffff60ef1b90565b600160ff1b911816617fff60f01b1790565b909392506dffffffffffffffffffffffffffff949194808460801c169580155f14613d0c57506001955b818460801c1686155f14613cf95780613cd3575b90613b3e916108e6565b908115613cba576001600160801b031996613b696d1000000000000000000000000000841015613a29565b5f6e0800000000000000000000000000008410613c795750613b8a8361176c565b915b878301906140718301821115613bbf5750505050506001607f1b91929350925f9360701b921860801c16171760801b1690565b909192939450613ffc9383858401105f14613bea575050505050509091506001607f1b5f9283611627565b83613f8c8401105f14613c4a5750505085820181811115613c1857506001607f1b93949503011b925f611627565b819396925094939410613c33575b50506001607f1b90611659565b9003613ffb19019290921c916001607f1b5f613c26565b6001607f1b96979591929850613f8d945060708111613c6e575b5016950301611627565b606f19011c5f613c64565b6e0400000000000000000000000000008410613c9c575060ff60725b1691613b8c565b50600160711b8310613cb15760ff6071613c95565b60ff6070613c95565b50600160ff1b95505f9450505018821615611744575090565b9550613b3e90613ce28761176c565b60e20397880160711901976001979192501b613b34565b90600160701b613b3e921760721b6108e6565b95600160701b17613b20565b5f1981019081116108e15760011c600181018091116108e15760051b90565b64ffffffffff91821690821603919082116108e157565b613d6064ffffffffff91824216613d37565b169056fea26469706673582212204f01a9cd7ed72dceb737fa39596c58cbf7a658716264fc5be10646422f7bfa1c64736f6c63430008140033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

3ff50624dd2f1a9fbe76c8b439581062000000000000000000000000000000003ff505e1d27a3ee9bffd7f3dd1a3267100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000c3ffeef368eb04325c526c2246eec3e5500000000000000000000000000000000

-----Decoded View---------------
Arg [0] : _maxPercentIncrease (bytes16): 0x3ff50624dd2f1a9fbe76c8b439581062
Arg [1] : _maxPercentDecrease (bytes16): 0x3ff505e1d27a3ee9bffd7f3dd1a32671
Arg [2] : _capInterval (uint256): 12
Arg [3] : _alpha (bytes16): 0x3ffeef368eb04325c526c2246eec3e55

-----Encoded View---------------
4 Constructor Arguments found :
Arg [0] : 3ff50624dd2f1a9fbe76c8b43958106200000000000000000000000000000000
Arg [1] : 3ff505e1d27a3ee9bffd7f3dd1a3267100000000000000000000000000000000
Arg [2] : 000000000000000000000000000000000000000000000000000000000000000c
Arg [3] : 3ffeef368eb04325c526c2246eec3e5500000000000000000000000000000000


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

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.