HYPE Price: $37.52 (-2.78%)

Contract

0x54563d1DdB55b029D6D7AcD89C633af746823092

Overview

HYPE Balance

HyperEVM LogoHyperEVM LogoHyperEVM Logo0 HYPE

HYPE Value

$0.00

More Info

Private Name Tags

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

1 Internal Transaction and > 10 Token Transfers found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Block From To
327902025-02-18 21:14:00139 days ago1739913240  Contract Creation0 HYPE
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
MultiAssetAtomicSolverRedeemUCP

Compiler Version
v0.8.25+commit.b61c2a91

Optimization Enabled:
Yes with 200 runs

Other Settings:
cancun EvmVersion
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.25;

import { IAtomicSolver } from "../IAtomicSolver.sol";
import { FixedPointMathLib } from "@solmate/utils/FixedPointMathLib.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { TellerWithMultiAssetSupport } from "src/base/Roles/TellerWithMultiAssetSupport.sol";
import { AccountantWithRateProviders } from "src/base/Roles/AccountantWithRateProviders.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SignedMath } from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

interface IAtomicQueueUCP {
    function solve(
        ERC20 offer,
        ERC20 want,
        address[] calldata users,
        bytes calldata runData,
        address solver,
        uint256 clearingPrice
    )
        external;
}

contract MultiAssetAtomicSolverRedeemUCP is Ownable, IAtomicSolver {
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;

    /**
     * @notice The Solve Type, used in `finishSolve` to determine the logic used.
     * @notice P2P Solver wants to swap share.asset() for user(s) shares
     * @notice REDEEM Solver needs to redeem shares, then can cover user(s) required assets.
     * for this solver to be compatible with first two versions of queue, this is needed to be able to encode the data
     * only redeem is used in this solver
     */
    enum SolveType {
        P2P,
        REDEEM
    }

    //============================== ERRORS ===============================

    error MultiAssetAtomicSolverRedeem___WrongInitiator();
    error MultiAssetAtomicSolverRedeem___AlreadyInSolveContext();
    error MultiAssetAtomicSolverRedeem___FailedToSolve();
    error MultiAssetAtomicSolverRedeem___SolveMaxAssetsExceeded(uint256 actualAssets, uint256 maxAssets);
    error MultiAssetAtomicSolverRedeem___BoringVaultTellerMismatch(address vault, address teller);
    error MultiAssetAtomicSolverRedeem___InsufficientAssetsRedeemed(uint256 redeemedAmount, uint256 requiredAmount);
    error MultiAssetAtomicSolverRedeem___MismatchedArrayLengths();
    error MultiAssetAtomicSolverRedeem___DuplicateWantAsset(address wantAsset);
    error MultiAssetAtomicSolverRedeem___GlobalSlippageThresholdExceeded(
        int256 globalSlippagePriceMinimum, int256[] balanceDeltas, int256 actualSlippage
    );
    error MultiAssetAtomicSolverRedeem___OnlyRedeemAllowed();
    error MultiAssetAtomicSolverRedeem___InvalidCaller();
    error MultiAssetAtomicSolverRedeem___OnlyQueue(address caller, address queue);
    error MultiAssetAtomicSolverRedeem___InsufficientOfferAmount(
        uint256 offerNeeded, uint256 currentBalance, uint256 maxAllowableOfferAmountFromSolver
    );

    // Updated struct to hold data for each want asset
    struct WantAssetData {
        ERC20 asset; // The desired asset by the users
        uint256 minimumAssetsOut; // a slippage control at the asset level
        uint256 maxAssets; // the maximum amount of assets to be redeemed for this asset
        // the amount of assets that will be redeemed in excess of user redemptions (can be 0)
        uint256 excessAssetAmount;
        // if true, will use all the initial solver balance in that asset first
        bool useSolverBalanceFirst;
        address[] users;
        // uniform clearing price for all users
        uint256 clearingPriceForAsset;
        // the maximum amount of offer asset from solver EOA balance that can be used to redeem this asset
        uint256 maxAllowableOfferAmountFromSolver;
    }

    IAtomicQueueUCP public immutable queue;

    mapping(address => bool) public isApprovedSolver;

    constructor(address _owner, IAtomicQueueUCP _queue, address[] memory approvedSolvers) Ownable(_owner) {
        queue = _queue;
        for (uint256 i; i < approvedSolvers.length;) {
            isApprovedSolver[approvedSolvers[i]] = true;
            unchecked {
                ++i;
            }
        }
    }

    //============================== SOLVE FUNCTIONS ===============================

    /**
     * @notice This function is used to solve for multiple assets in a single transaction
     * @notice Solvers should order the want assets in a way that they use their own balances (if any do so) first
     * @notice and then use the excess offer tokens to redeem the remaining assets last to minimize revert chances
     * @notice global slippage check uses exchange rate and rate providers and account for all want assets provided plus
     * vault tokens
     * @param offer the ERC20 asset sent to the solver
     * @param wantAssets an array of WantAssetData structs, each containing the desired asset and its users
     * @param teller the TellerWithMultiAssetSupport contract
     * @param globalSlippagePriceMinimum the solver sender's global slippage price minimum across all assets (in terms
     * of the base asset)
     * @param redeemCurrencyForExcessOffer the address to use as redeem token for excess offer
     */
    function multiAssetRedeemSolve(
        ERC20 offer,
        WantAssetData[] calldata wantAssets,
        TellerWithMultiAssetSupport teller,
        int256 globalSlippagePriceMinimum,
        address redeemCurrencyForExcessOffer
    )
        external
    {
        if (!isApprovedSolver[msg.sender]) revert MultiAssetAtomicSolverRedeem___InvalidCaller();

        AccountantWithRateProviders accountant = teller.accountant();
        _baseDecimalsTempStore(address(offer), accountant);

        (uint256[] memory assetPrices, int256[] memory balanceDeltas) =
            _multiAssetRedeemSolveSetup(offer, wantAssets, accountant);

        // Solve for each want asset with its corresponding users
        _doAllSolves(offer, wantAssets, teller, assetPrices);

        // send any excess offer shares to the solver or redeem in requested currency if specified
        if (redeemCurrencyForExcessOffer != address(0)) {
            teller.bulkWithdraw(ERC20(redeemCurrencyForExcessOffer), offer.balanceOf(address(this)), 0, msg.sender);
        } else {
            offer.safeTransfer(msg.sender, offer.balanceOf(address(this)));
        }

        // global slippage check with the balances, prices and maxOfferAssets
        _globalSlippageCheck(balanceDeltas, assetPrices, globalSlippagePriceMinimum, wantAssets, teller);

        // delete the temp storage for base decimals
        _baseDecimalsTempDelete(address(offer));
    }

    function finishSolve(
        bytes calldata runData,
        address initiator,
        ERC20 offer,
        ERC20 want,
        uint256 offerReceived,
        uint256 wantApprovalAmount
    )
        external
    {
        if (initiator != address(this)) revert MultiAssetAtomicSolverRedeem___WrongInitiator();

        if (msg.sender != address(queue)) revert MultiAssetAtomicSolverRedeem___OnlyQueue(msg.sender, address(queue));

        SolveType _type = abi.decode(runData, (SolveType));

        if (_type == SolveType.P2P) {
            revert MultiAssetAtomicSolverRedeem___OnlyRedeemAllowed();
        } else if (_type == SolveType.REDEEM) {
            _multiAssetRedeemSolve(runData, offer, want, offerReceived, wantApprovalAmount);
        }
    }

    function toggleApprovedSolvers(address[] memory solvers) external onlyOwner {
        for (uint256 i; i < solvers.length;) {
            isApprovedSolver[solvers[i]] = !isApprovedSolver[solvers[i]];
            unchecked {
                ++i;
            }
        }
    }

    function _multiAssetRedeemSolve(
        bytes memory runData,
        ERC20 offer,
        ERC20 want,
        uint256,
        uint256 wantApprovalAmount
    )
        internal
    {
        (, address solver,, uint256 maxAssets, TellerWithMultiAssetSupport teller, uint256 priceToCheckAtomicPrice) =
            abi.decode(runData, (SolveType, address, uint256, uint256, TellerWithMultiAssetSupport, uint256));

        if (address(offer) != address(teller.vault())) {
            revert MultiAssetAtomicSolverRedeem___BoringVaultTellerMismatch(address(offer), address(teller));
        }

        // Make sure solvers `maxAssets` was not exceeded.
        if (wantApprovalAmount > maxAssets) {
            revert MultiAssetAtomicSolverRedeem___SolveMaxAssetsExceeded(wantApprovalAmount, maxAssets);
        }

        _handleExcessOrBalanceAmounts(solver, want, offer, teller, wantApprovalAmount, priceToCheckAtomicPrice);

        // only transfer if there are orders to be filled
        if (wantApprovalAmount > 0) {
            // Transfer required assets from solver
            want.safeTransferFrom(solver, address(this), wantApprovalAmount);

            // Approve queue to spend wantApprovalAmount
            want.safeApprove(address(queue), wantApprovalAmount);
        }
    }

    function _doTempStore(
        ERC20 asset,
        uint256 excessAmount,
        bool useSolverBalanceFirst,
        uint256 maxAllowableOfferAmountFromSolver
    )
        internal
    {
        // Store excessAssetAmount, useSolverBalanceFirst, decimals and maxAllowableOfferAmountFromSolver for each asset
        uint256 key1 = uint256(keccak256(abi.encodePacked(asset)));
        uint256 key2 = key1 + 1;
        uint256 key3 = key2 + 1;
        uint256 key4 = key3 + 1;

        uint8 decimals = asset.decimals();

        assembly {
            tstore(key1, excessAmount)
            tstore(key2, useSolverBalanceFirst)
            tstore(key3, decimals)
            tstore(key4, maxAllowableOfferAmountFromSolver)
        }
    }

    function _doTempLoad(address asset) internal view returns (uint256, bool, uint8, uint256) {
        uint256 key1 = uint256(keccak256(abi.encodePacked(asset)));
        uint256 key2 = key1 + 1;
        uint256 key3 = key2 + 1;
        uint256 key4 = key3 + 1;

        uint256 excessAssetAmount;
        bool useSolverBalanceFirst;
        uint8 decimals;
        uint256 maxAllowableOfferAmountFromSolver;

        assembly {
            excessAssetAmount := tload(key1)
            useSolverBalanceFirst := tload(key2)
            decimals := tload(key3)
            maxAllowableOfferAmountFromSolver := tload(key4)
        }

        return (excessAssetAmount, useSolverBalanceFirst, decimals, maxAllowableOfferAmountFromSolver);
    }

    function _doTempDelete(address asset) internal {
        uint256 key1 = uint256(keccak256(abi.encodePacked(asset)));
        uint256 key2 = key1 + 1;
        uint256 key3 = key2 + 1;
        uint256 key4 = key3 + 1;

        assembly {
            tstore(key1, 0)
            tstore(key2, 0)
            tstore(key3, 0)
            tstore(key4, 0)
        }
    }

    function _baseDecimalsTempStore(address offer, AccountantWithRateProviders accountant) internal {
        uint256 key = uint256(keccak256(abi.encodePacked(offer)));
        uint8 decimals = accountant.decimals();

        assembly {
            tstore(key, decimals)
        }
    }

    function _baseDecimalsTempLoad(address offer) internal view returns (uint8) {
        uint256 key = uint256(keccak256(abi.encodePacked(offer)));
        uint8 decimals;

        assembly {
            decimals := tload(key)
        }

        return decimals;
    }

    function _baseDecimalsTempDelete(address offer) internal {
        uint256 key = uint256(keccak256(abi.encodePacked(offer)));

        assembly {
            tstore(key, 0)
        }
    }

    function _getMinOfferNeededForWant(
        uint256 wantAmount,
        uint256 priceToCheckAtomicPrice,
        ERC20 offer,
        uint8 wantDecimals
    )
        internal
        view
        returns (uint256 offerNeededForWant)
    {
        // handling cases where decimals could differ between offer and want
        // use tstore/tload to avoid external calls
        // @notice: in all nucleus deployments, offer and base decimals should be same, but other want assets could have
        // different decimals
        uint8 baseDecimals = _baseDecimalsTempLoad(address(offer));
        offerNeededForWant = Math.ceilDiv(wantAmount * (10 ** baseDecimals), priceToCheckAtomicPrice);
    }

    function _globalSlippageCheck(
        int256[] memory balanceDeltas,
        uint256[] memory assetPrices,
        int256 globalSlippagePriceMinimum,
        WantAssetData[] calldata wantAssets,
        TellerWithMultiAssetSupport teller
    )
        internal
    {
        int256 actualSlippage = 0;

        // AccountantWithRateProviders accountant = teller.accountant();
        ERC20 offer = ERC20(teller.vault());

        uint8 baseDecimals = _baseDecimalsTempLoad(address(offer));
        uint256 baseExchangeRate = AccountantWithRateProviders(teller.accountant()).getRate();

        uint256 i;
        for (i; i < wantAssets.length;) {
            ERC20 wantAsset = wantAssets[i].asset;
            //update the balance delta to reflect the actual change in balance
            balanceDeltas[i] = int256(wantAsset.balanceOf(msg.sender)) - balanceDeltas[i];
            (,, uint8 wantDecimals,) = _doTempLoad(address(wantAsset));

            // Convert balance delta to base decimals
            int256 scaledDelta = _changeDecimalsSigned(balanceDeltas[i], wantDecimals, baseDecimals);

            // Convert asset price to base decimals
            uint256 scaledPrice = _changeDecimals(assetPrices[i], wantDecimals, baseDecimals);

            // Calculate the slippage for this asset
            int256 assetSlippage = SignedMath.ternary(scaledDelta < 0, -1, int256(1))
                * int256(
                    Math.mulDiv(
                        SignedMath.abs(scaledDelta),
                        baseExchangeRate,
                        scaledPrice,
                        Math.Rounding.Floor // Round down for conservative estimate
                    )
                );
            actualSlippage += assetSlippage;

            // go ahead and delete the temp storage for this want asset
            _doTempDelete(address(wantAsset));

            unchecked {
                ++i;
            }
        }

        // Update the balance delta for the offer token
        balanceDeltas[i] = int256(offer.balanceOf(msg.sender)) - balanceDeltas[i];

        // Add the offer token's balance delta in terms of base token
        actualSlippage += SignedMath.ternary(balanceDeltas[balanceDeltas.length - 1] < 0, -1, int256(1))
            * int256(
                Math.mulDiv(
                    SignedMath.abs(balanceDeltas[balanceDeltas.length - 1]),
                    baseExchangeRate,
                    10 ** baseDecimals,
                    Math.Rounding.Floor // Round down for conservative estimate
                )
            );

        if (globalSlippagePriceMinimum > actualSlippage) {
            revert MultiAssetAtomicSolverRedeem___GlobalSlippageThresholdExceeded(
                globalSlippagePriceMinimum, balanceDeltas, actualSlippage
            );
        }
    }

    // Helper function to change decimals similar to one in AccountantWithRateProviders
    function _changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            return amount * (10 ** (toDecimals - fromDecimals));
        } else {
            return amount / (10 ** (fromDecimals - toDecimals));
        }
    }

    // Helper function to change decimals for signed integers
    function _changeDecimalsSigned(
        int256 amount,
        uint8 fromDecimals,
        uint8 toDecimals
    )
        internal
        pure
        returns (int256)
    {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            return amount * int256(10 ** (toDecimals - fromDecimals));
        } else {
            return amount / int256(10 ** (fromDecimals - toDecimals));
        }
    }

    function _doAllSolves(
        ERC20 offer,
        WantAssetData[] calldata wantAssets,
        TellerWithMultiAssetSupport teller,
        uint256[] memory assetPrices
    )
        internal
    {
        for (uint256 i = 0; i < wantAssets.length;) {
            bytes memory runData = abi.encode(
                SolveType.REDEEM,
                msg.sender,
                wantAssets[i].minimumAssetsOut,
                wantAssets[i].maxAssets,
                teller,
                assetPrices[i]
            );
            //check if there are orders to be filled, if not, skip to internal _multiAssetRedeemSolve function
            if (wantAssets[i].users.length == 0) {
                _multiAssetRedeemSolve(runData, offer, wantAssets[i].asset, 0, 0);
            } else {
                queue.solve(
                    offer,
                    wantAssets[i].asset,
                    wantAssets[i].users,
                    runData,
                    address(this),
                    wantAssets[i].clearingPriceForAsset
                );
            }
            unchecked {
                ++i;
            }
        }
    }

    function _multiAssetRedeemSolveSetup(
        ERC20 offer,
        WantAssetData[] calldata wantAssets,
        AccountantWithRateProviders accountant
    )
        internal
        returns (uint256[] memory, int256[] memory)
    {
        uint256[] memory assetPrices = new uint256[](wantAssets.length);

        // plus 1 for the offer/vault token
        int256[] memory balanceDeltas = new int256[](wantAssets.length + 1);

        address[] memory usedAddresses = new address[](wantAssets.length);

        uint256 i;
        for (i; i < wantAssets.length;) {
            // Checks if any want assets are duplicates,
            // since typically want assets supported will be
            // in the single digits, this does not need to be optimized with bit/bloom filtering
            // and enforcing order of want assets to be increasing in address is not feasible since
            // the order of want assets needs to correspond to which use existing balance and which use excess
            for (uint256 j = 0; j < i;) {
                address wantAssetAddress = address(wantAssets[i].asset);
                if (address(wantAssetAddress) == usedAddresses[j]) {
                    revert MultiAssetAtomicSolverRedeem___DuplicateWantAsset(wantAssetAddress);
                }
                unchecked {
                    ++j;
                }
            }
            // Get the rate in quote for each want asset
            assetPrices[i] = accountant.getRateInQuoteSafe(wantAssets[i].asset);
            // if price is 0, revert as either paused, not supported, or failed to get rate
            if (assetPrices[i] == 0) {
                revert MultiAssetAtomicSolverRedeem___FailedToSolve();
            }
            //set the temp store for the want asset which will be loaded after callback
            _doTempStore(
                wantAssets[i].asset,
                wantAssets[i].excessAssetAmount,
                wantAssets[i].useSolverBalanceFirst,
                wantAssets[i].maxAllowableOfferAmountFromSolver
            );
            // Set initial balance to calculate global slippage later
            balanceDeltas[i] = int256(wantAssets[i].asset.balanceOf(msg.sender));
            // Update the used addresses array for duplicate checking
            usedAddresses[i] = address(wantAssets[i].asset);
            unchecked {
                ++i;
            }
        }

        // store the solver balance for the offer asset at index wantAssets.length
        balanceDeltas[i] = int256(offer.balanceOf(msg.sender));

        return (assetPrices, balanceDeltas);
    }

    function _handleExcessOrBalanceAmounts(
        address solver,
        ERC20 want,
        ERC20 offer,
        TellerWithMultiAssetSupport teller,
        uint256 wantApprovalAmount,
        uint256 priceToCheckAtomicPrice
    )
        internal
    {
        // Find from tload the excessAssetAmount, useSolverBalanceFirst, decimals and maxAllowableOfferAmountFromSolver
        // for this want asset
        (
            uint256 excessAmount,
            bool useSolverBalanceFirst,
            uint8 wantDecimals,
            uint256 maxAllowableOfferAmountFromSolver
        ) = _doTempLoad(address(want));

        uint256 offerNeededForWant;

        if (useSolverBalanceFirst) {
            uint256 solverBalance = want.balanceOf(solver);
            // if the solver wants to use their balance first, check if it is enough to fill completely any wants
            // the wants can be comprised of
            // 1. wantApprovalAmount from user orders
            // 2. excessAmount from solver that would be needed to for example close any open positions, e.g. flash
            // swaps
            if (solverBalance >= wantApprovalAmount + excessAmount) {
                offerNeededForWant = 0;
            } else {
                offerNeededForWant = _getMinOfferNeededForWant(
                    wantApprovalAmount + excessAmount - solverBalance, priceToCheckAtomicPrice, offer, wantDecimals
                );

                // Check and handle offer amount, potentially getting more from solver
                offerNeededForWant =
                    _checkAndHandleOfferAmount(offerNeededForWant, maxAllowableOfferAmountFromSolver, solver, offer);
            }

            // Redeem the shares, sending assets to solver if any residual amount is needed
            if (offerNeededForWant > 0) {
                teller.bulkWithdraw(want, offerNeededForWant, wantApprovalAmount + excessAmount - solverBalance, solver);
            }
        } else {
            offerNeededForWant = _getMinOfferNeededForWant(
                wantApprovalAmount + excessAmount, priceToCheckAtomicPrice, offer, wantDecimals
            );

            // Check and handle offer amount, potentially getting more from solver
            offerNeededForWant =
                _checkAndHandleOfferAmount(offerNeededForWant, maxAllowableOfferAmountFromSolver, solver, offer);

            // Redeem the shares, sending assets to solver
            teller.bulkWithdraw(want, offerNeededForWant, wantApprovalAmount + excessAmount, solver);
        }
    }

    function _checkAndHandleOfferAmount(
        uint256 offerNeeded,
        uint256 maxAllowableOfferAmountFromSolver,
        address solver,
        ERC20 offer
    )
        internal
        returns (uint256)
    {
        uint256 currentBalance = offer.balanceOf(address(this));

        // Check if current balance is sufficient
        if (currentBalance >= offerNeeded) {
            return offerNeeded;
        }

        uint256 additionalOfferNeeded = offerNeeded - currentBalance;

        // Check if solver can provide the additional amount needed
        if (additionalOfferNeeded > maxAllowableOfferAmountFromSolver) {
            revert MultiAssetAtomicSolverRedeem___InsufficientOfferAmount(
                offerNeeded, currentBalance, maxAllowableOfferAmountFromSolver
            );
        }

        // Transfer the additional amount from solver
        offer.safeTransferFrom(solver, address(this), additionalOfferNeeded);

        return offerNeeded;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface that must be implemented by smart contracts in order to receive
 * ERC-1155 token transfers.
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC-1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC-1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 */
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }

    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

File 5 of 27 : IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

File 6 of 27 : ERC721Holder.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or
 * {IERC721-setApprovalForAll}.
 */
abstract contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

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

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

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) 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 Errors.FailedCall();
        }
    }
}

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

File 9 of 27 : Errors.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.20;

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

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

pragma solidity ^0.8.20;

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 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²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_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.

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

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

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

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

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

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

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, expect 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
    event OwnershipTransferred(address indexed user, address indexed newOwner);

    event AuthorityUpdated(address indexed user, Authority indexed newAuthority);

    address public owner;

    Authority public authority;

    constructor(address _owner, Authority _authority) {
        owner = _owner;
        authority = _authority;

        emit OwnershipTransferred(msg.sender, _owner);
        emit AuthorityUpdated(msg.sender, _authority);
    }

    modifier requiresAuth() virtual {
        require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");

        _;
    }

    function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
        Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.

        // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
        // aware that this makes protected functions uncallable even to the owner if the authority is out of order.
        return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
    }

    function setAuthority(Authority newAuthority) public virtual {
        // We check if the caller is the owner first because we want to ensure they can
        // always swap out the authority even if it's reverting or using up a lot of gas.
        require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));

        authority = newAuthority;

        emit AuthorityUpdated(msg.sender, newAuthority);
    }

    function transferOwnership(address newOwner) public virtual requiresAuth {
        owner = newOwner;

        emit OwnershipTransferred(msg.sender, newOwner);
    }
}

/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
    function canCall(
        address user,
        address target,
        bytes4 functionSig
    ) external view returns (bool);
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event Transfer(address indexed from, address indexed to, uint256 amount);

    event Approval(address indexed owner, address indexed spender, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                            METADATA STORAGE
    //////////////////////////////////////////////////////////////*/

    string public name;

    string public symbol;

    uint8 public immutable decimals;

    /*//////////////////////////////////////////////////////////////
                              ERC20 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public totalSupply;

    mapping(address => uint256) public balanceOf;

    mapping(address => mapping(address => uint256)) public allowance;

    /*//////////////////////////////////////////////////////////////
                            EIP-2612 STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 internal immutable INITIAL_CHAIN_ID;

    bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;

    mapping(address => uint256) public nonces;

    /*//////////////////////////////////////////////////////////////
                               CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    ) {
        name = _name;
        symbol = _symbol;
        decimals = _decimals;

        INITIAL_CHAIN_ID = block.chainid;
        INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
    }

    /*//////////////////////////////////////////////////////////////
                               ERC20 LOGIC
    //////////////////////////////////////////////////////////////*/

    function approve(address spender, uint256 amount) public virtual returns (bool) {
        allowance[msg.sender][spender] = amount;

        emit Approval(msg.sender, spender, amount);

        return true;
    }

    function transfer(address to, uint256 amount) public virtual returns (bool) {
        balanceOf[msg.sender] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(msg.sender, to, amount);

        return true;
    }

    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual returns (bool) {
        uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.

        if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;

        balanceOf[from] -= amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(from, to, amount);

        return true;
    }

    /*//////////////////////////////////////////////////////////////
                             EIP-2612 LOGIC
    //////////////////////////////////////////////////////////////*/

    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual {
        require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");

        // Unchecked because the only math done is incrementing
        // the owner's nonce which cannot realistically overflow.
        unchecked {
            address recoveredAddress = ecrecover(
                keccak256(
                    abi.encodePacked(
                        "\x19\x01",
                        DOMAIN_SEPARATOR(),
                        keccak256(
                            abi.encode(
                                keccak256(
                                    "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
                                ),
                                owner,
                                spender,
                                value,
                                nonces[owner]++,
                                deadline
                            )
                        )
                    )
                ),
                v,
                r,
                s
            );

            require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");

            allowance[recoveredAddress][spender] = value;
        }

        emit Approval(owner, spender, value);
    }

    function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
        return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
    }

    function computeDomainSeparator() internal view virtual returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                    keccak256(bytes(name)),
                    keccak256("1"),
                    block.chainid,
                    address(this)
                )
            );
    }

    /*//////////////////////////////////////////////////////////////
                        INTERNAL MINT/BURN LOGIC
    //////////////////////////////////////////////////////////////*/

    function _mint(address to, uint256 amount) internal virtual {
        totalSupply += amount;

        // Cannot overflow because the sum of all user
        // balances can't exceed the max uint256 value.
        unchecked {
            balanceOf[to] += amount;
        }

        emit Transfer(address(0), to, amount);
    }

    function _burn(address from, uint256 amount) internal virtual {
        balanceOf[from] -= amount;

        // Cannot underflow because a user's balance
        // will never be larger than the total supply.
        unchecked {
            totalSupply -= amount;
        }

        emit Transfer(from, address(0), amount);
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

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

import {SafeTransferLib} from "../utils/SafeTransferLib.sol";

/// @notice Minimalist and modern Wrapped Ether implementation.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
    using SafeTransferLib for address;

    event Deposit(address indexed from, uint256 amount);

    event Withdrawal(address indexed to, uint256 amount);

    function deposit() public payable virtual {
        _mint(msg.sender, msg.value);

        emit Deposit(msg.sender, msg.value);
    }

    function withdraw(uint256 amount) public virtual {
        _burn(msg.sender, amount);

        emit Withdrawal(msg.sender, amount);

        msg.sender.safeTransferETH(amount);
    }

    receive() external payable virtual {
        deposit();
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
    /*//////////////////////////////////////////////////////////////
                    SIMPLIFIED FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    uint256 internal constant MAX_UINT256 = 2**256 - 1;

    uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.

    function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
    }

    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
    }

    function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
    }

    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
        return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
    }

    /*//////////////////////////////////////////////////////////////
                    LOW LEVEL FIXED POINT OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function mulDivDown(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // Divide x * y by the denominator.
            z := div(mul(x, y), denominator)
        }
    }

    function mulDivUp(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
            if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
                revert(0, 0)
            }

            // If x * y modulo the denominator is strictly greater than 0,
            // 1 is added to round up the division of x * y by the denominator.
            z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
        }
    }

    function rpow(
        uint256 x,
        uint256 n,
        uint256 scalar
    ) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            switch x
            case 0 {
                switch n
                case 0 {
                    // 0 ** 0 = 1
                    z := scalar
                }
                default {
                    // 0 ** n = 0
                    z := 0
                }
            }
            default {
                switch mod(n, 2)
                case 0 {
                    // If n is even, store scalar in z for now.
                    z := scalar
                }
                default {
                    // If n is odd, store x in z for now.
                    z := x
                }

                // Shifting right by 1 is like dividing by 2.
                let half := shr(1, scalar)

                for {
                    // Shift n right by 1 before looping to halve it.
                    n := shr(1, n)
                } n {
                    // Shift n right by 1 each iteration to halve it.
                    n := shr(1, n)
                } {
                    // Revert immediately if x ** 2 would overflow.
                    // Equivalent to iszero(eq(div(xx, x), x)) here.
                    if shr(128, x) {
                        revert(0, 0)
                    }

                    // Store x squared.
                    let xx := mul(x, x)

                    // Round to the nearest number.
                    let xxRound := add(xx, half)

                    // Revert if xx + half overflowed.
                    if lt(xxRound, xx) {
                        revert(0, 0)
                    }

                    // Set x to scaled xxRound.
                    x := div(xxRound, scalar)

                    // If n is even:
                    if mod(n, 2) {
                        // Compute z * x.
                        let zx := mul(z, x)

                        // If z * x overflowed:
                        if iszero(eq(div(zx, x), z)) {
                            // Revert if x is non-zero.
                            if iszero(iszero(x)) {
                                revert(0, 0)
                            }
                        }

                        // Round to the nearest number.
                        let zxRound := add(zx, half)

                        // Revert if zx + half overflowed.
                        if lt(zxRound, zx) {
                            revert(0, 0)
                        }

                        // Return properly scaled zxRound.
                        z := div(zxRound, scalar)
                    }
                }
            }
        }
    }

    /*//////////////////////////////////////////////////////////////
                        GENERAL NUMBER UTILITIES
    //////////////////////////////////////////////////////////////*/

    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let y := x // We start y at x, 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 x >= 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 x. 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 x < 256 but we can just verify those cases exhaustively.

            // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
            // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
            // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), 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(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If x+1 is a perfect square, the Babylonian method cycles between
            // floor(sqrt(x)) and ceil(sqrt(x)). 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(x, z), z))
        }
    }

    function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Mod x by y. Note this will return
            // 0 instead of reverting if y is zero.
            z := mod(x, y)
        }
    }

    function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // Divide x by y. Note this will return
            // 0 instead of reverting if y is zero.
            r := div(x, y)
        }
    }

    function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Add 1 to x * y if x % y > 0. Note this will
            // return 0 instead of reverting if y is zero.
            z := add(gt(mod(x, y), 0), div(x, y))
        }
    }
}

File 20 of 27 : ReentrancyGuard.sol
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ReentrancyGuard.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    uint256 private locked = 1;

    modifier nonReentrant() virtual {
        require(locked == 1, "REENTRANCY");

        locked = 2;

        _;

        locked = 1;
    }
}

// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

import {ERC20} from "../tokens/ERC20.sol";

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.
library SafeTransferLib {
    /*//////////////////////////////////////////////////////////////
                             ETH OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferETH(address to, uint256 amount) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Transfer the ETH and store if it succeeded or not.
            success := call(gas(), to, amount, 0, 0, 0, 0)
        }

        require(success, "ETH_TRANSFER_FAILED");
    }

    /*//////////////////////////////////////////////////////////////
                            ERC20 OPERATIONS
    //////////////////////////////////////////////////////////////*/

    function safeTransferFrom(
        ERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument.
            mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
            )
        }

        require(success, "TRANSFER_FROM_FAILED");
    }

    function safeTransfer(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "TRANSFER_FAILED");
    }

    function safeApprove(
        ERC20 token,
        address to,
        uint256 amount
    ) internal {
        bool success;

        /// @solidity memory-safe-assembly
        assembly {
            // Get a pointer to some free memory.
            let freeMemoryPointer := mload(0x40)

            // Write the abi-encoded calldata into memory, beginning with the function selector.
            mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
            mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
            mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

            success := and(
                // Set success to whether the call reverted, if not we check it either
                // returned exactly 1 (can't just be non-zero data), or had no return data.
                or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                // Counterintuitively, this call must be positioned second to the or() call in the
                // surrounding and() call or else returndatasize() will be zero during the computation.
                call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
            )
        }

        require(success, "APPROVE_FAILED");
    }
}

File 22 of 27 : IAtomicSolver.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;

import { ERC20 } from "@solmate/tokens/ERC20.sol";

interface IAtomicSolver {
    /**
     * @notice This function must be implemented in order for an address to be a `solver`
     *         for the AtomicQueue
     * @param runData arbitrary bytes data that is dependent on how each solver is setup
     *        it could contain swap data, or flash loan data, etc..
     * @param initiator the address that initiated a solve
     * @param offer the ERC20 asset sent to the solver
     * @param want the ERC20 asset the solver must approve the queue for
     * @param assetsToOffer the amount of `offer` sent to the solver
     * @param assetsForWant the amount of `want` the solver must approve the queue for
     */
    function finishSolve(
        bytes calldata runData,
        address initiator,
        ERC20 offer,
        ERC20 want,
        uint256 assetsToOffer,
        uint256 assetsForWant
    )
        external;
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import { ERC1155Holder } from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import { FixedPointMathLib } from "@solmate/utils/FixedPointMathLib.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { BeforeTransferHook } from "src/interfaces/BeforeTransferHook.sol";
import { Auth, Authority } from "@solmate/auth/Auth.sol";

/**
 * @title BoringVault
 * @custom:security-contact [email protected]
 */
contract BoringVault is ERC20, Auth, ERC721Holder, ERC1155Holder {
    using Address for address;
    using SafeTransferLib for ERC20;
    using FixedPointMathLib for uint256;

    // ========================================= STATE =========================================

    /**
     * @notice Contract responsible for implementing `beforeTransfer`.
     */
    BeforeTransferHook public hook;

    //============================== EVENTS ===============================

    event Enter(address indexed from, address indexed asset, uint256 amount, address indexed to, uint256 shares);
    event Exit(address indexed to, address indexed asset, uint256 amount, address indexed from, uint256 shares);

    //============================== CONSTRUCTOR ===============================

    constructor(
        address _owner,
        string memory _name,
        string memory _symbol,
        uint8 _decimals
    )
        ERC20(_name, _symbol, _decimals)
        Auth(_owner, Authority(address(0)))
    { }

    //============================== MANAGE ===============================

    /**
     * @notice Allows manager to make an arbitrary function call from this contract.
     * @dev Callable by MANAGER_ROLE.
     */
    function manage(
        address target,
        bytes calldata data,
        uint256 value
    )
        external
        requiresAuth
        returns (bytes memory result)
    {
        result = target.functionCallWithValue(data, value);
    }

    /**
     * @notice Allows manager to make arbitrary function calls from this contract.
     * @dev Callable by MANAGER_ROLE.
     */
    function manage(
        address[] calldata targets,
        bytes[] calldata data,
        uint256[] calldata values
    )
        external
        requiresAuth
        returns (bytes[] memory results)
    {
        uint256 targetsLength = targets.length;
        results = new bytes[](targetsLength);
        for (uint256 i; i < targetsLength; ++i) {
            results[i] = targets[i].functionCallWithValue(data[i], values[i]);
        }
    }

    //============================== ENTER ===============================

    /**
     * @notice Allows minter to mint shares, in exchange for assets.
     * @dev If assetAmount is zero, no assets are transferred in.
     * @dev Callable by MINTER_ROLE.
     */
    function enter(
        address from,
        ERC20 asset,
        uint256 assetAmount,
        address to,
        uint256 shareAmount
    )
        external
        requiresAuth
    {
        // Transfer assets in
        if (assetAmount > 0) asset.safeTransferFrom(from, address(this), assetAmount);

        // Mint shares.
        _mint(to, shareAmount);

        emit Enter(from, address(asset), assetAmount, to, shareAmount);
    }

    //============================== EXIT ===============================

    /**
     * @notice Allows burner to burn shares, in exchange for assets.
     * @dev If assetAmount is zero, no assets are transferred out.
     * @dev Callable by BURNER_ROLE.
     */
    function exit(
        address to,
        ERC20 asset,
        uint256 assetAmount,
        address from,
        uint256 shareAmount
    )
        external
        requiresAuth
    {
        // Burn shares.
        _burn(from, shareAmount);

        // Transfer assets out.
        if (assetAmount > 0) asset.safeTransfer(to, assetAmount);

        emit Exit(to, address(asset), assetAmount, from, shareAmount);
    }

    //============================== BEFORE TRANSFER HOOK ===============================
    /**
     * @notice Sets the share locker.
     * @notice If set to zero address, the share locker logic is disabled.
     * @dev Callable by OWNER_ROLE.
     */
    function setBeforeTransferHook(address _hook) external requiresAuth {
        hook = BeforeTransferHook(_hook);
    }

    /**
     * @notice Check if from addresses shares are locked, reverting if so.
     */
    function _callBeforeTransfer(address from) internal view {
        if (address(hook) != address(0)) hook.beforeTransfer(from);
    }

    function transfer(address to, uint256 amount) public override returns (bool) {
        _callBeforeTransfer(msg.sender);
        return super.transfer(to, amount);
    }

    function transferFrom(address from, address to, uint256 amount) public override returns (bool) {
        _callBeforeTransfer(from);
        return super.transferFrom(from, to, amount);
    }

    //============================== RECEIVE ===============================

    receive() external payable { }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

import { FixedPointMathLib } from "@solmate/utils/FixedPointMathLib.sol";
import { IRateProvider } from "src/interfaces/IRateProvider.sol";
import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { BoringVault } from "src/base/BoringVault.sol";
import { Auth, Authority } from "@solmate/auth/Auth.sol";

/**
 * @title AccountantWithRateProviders
 * @custom:security-contact [email protected]
 */
contract AccountantWithRateProviders is Auth, IRateProvider {
    using FixedPointMathLib for uint256;
    using SafeTransferLib for ERC20;

    // ========================================= STRUCTS =========================================

    /**
     * @param payoutAddress the address `claimFees` sends fees to
     * @param feesOwedInBase total pending fees owed in terms of base
     * @param totalSharesLastUpdate total amount of shares the last exchange rate update
     * @param exchangeRate the current exchange rate in terms of base
     * @param allowedExchangeRateChangeUpper the max allowed change to exchange rate from an update
     * @param allowedExchangeRateChangeLower the min allowed change to exchange rate from an update
     * @param lastUpdateTimestamp the block timestamp of the last exchange rate update
     * @param isPaused whether or not this contract is paused
     * @param minimumUpdateDelayInSeconds the minimum amount of time that must pass between
     *        exchange rate updates, such that the update won't trigger the contract to be paused
     * @param managementFee the management fee
     */
    struct AccountantState {
        address payoutAddress;
        uint128 feesOwedInBase;
        uint128 totalSharesLastUpdate;
        uint96 exchangeRate;
        uint16 allowedExchangeRateChangeUpper;
        uint16 allowedExchangeRateChangeLower;
        uint64 lastUpdateTimestamp;
        bool isPaused;
        uint32 minimumUpdateDelayInSeconds;
        uint16 managementFee;
    }

    /**
     * @param isPeggedToBase whether or not the asset is 1:1 with the base asset
     * @param rateProvider the rate provider for this asset if `isPeggedToBase` is false
     */
    struct RateProviderData {
        bool isPeggedToBase;
        IRateProvider rateProvider;
    }

    // ========================================= STATE =========================================

    /**
     * @notice Store the accountant state in 3 packed slots.
     */
    AccountantState public accountantState;

    /**
     * @notice Maps ERC20s to their RateProviderData.
     */
    mapping(ERC20 => RateProviderData) public rateProviderData;

    //============================== ERRORS ===============================

    error AccountantWithRateProviders__UpperBoundTooSmall();
    error AccountantWithRateProviders__LowerBoundTooLarge();
    error AccountantWithRateProviders__ManagementFeeTooLarge();
    error AccountantWithRateProviders__Paused();
    error AccountantWithRateProviders__ZeroFeesOwed();
    error AccountantWithRateProviders__OnlyCallableByBoringVault();
    error AccountantWithRateProviders__UpdateDelayTooLarge();

    //============================== EVENTS ===============================

    event Paused();
    event Unpaused();
    event DelayInSecondsUpdated(uint32 oldDelay, uint32 newDelay);
    event UpperBoundUpdated(uint16 oldBound, uint16 newBound);
    event LowerBoundUpdated(uint16 oldBound, uint16 newBound);
    event ManagementFeeUpdated(uint16 oldFee, uint16 newFee);
    event PayoutAddressUpdated(address oldPayout, address newPayout);
    event RateProviderUpdated(address asset, bool isPegged, address rateProvider);
    event ExchangeRateUpdated(uint96 oldRate, uint96 newRate, uint64 currentTime);
    event FeesClaimed(address indexed feeAsset, uint256 amount);

    //============================== IMMUTABLES ===============================

    /**
     * @notice The base asset rates are provided in.
     */
    ERC20 public immutable base;

    /**
     * @notice The decimals rates are provided in.
     */
    uint8 public immutable decimals;

    /**
     * @notice The BoringVault this accountant is working with.
     *         Used to determine share supply for fee calculation.
     */
    BoringVault public immutable vault;

    /**
     * @notice One share of the BoringVault.
     */
    uint256 internal immutable ONE_SHARE;

    constructor(
        address _owner,
        address _vault,
        address payoutAddress,
        uint96 startingExchangeRate,
        address _base,
        uint16 allowedExchangeRateChangeUpper,
        uint16 allowedExchangeRateChangeLower,
        uint32 minimumUpdateDelayInSeconds,
        uint16 managementFee
    )
        Auth(_owner, Authority(address(0)))
    {
        base = ERC20(_base);
        decimals = ERC20(_base).decimals();
        vault = BoringVault(payable(_vault));
        ONE_SHARE = 10 ** vault.decimals();
        accountantState = AccountantState({
            payoutAddress: payoutAddress,
            feesOwedInBase: 0,
            totalSharesLastUpdate: uint128(vault.totalSupply()),
            exchangeRate: startingExchangeRate,
            allowedExchangeRateChangeUpper: allowedExchangeRateChangeUpper,
            allowedExchangeRateChangeLower: allowedExchangeRateChangeLower,
            lastUpdateTimestamp: uint64(block.timestamp),
            isPaused: false,
            minimumUpdateDelayInSeconds: minimumUpdateDelayInSeconds,
            managementFee: managementFee
        });
    }

    // ========================================= ADMIN FUNCTIONS =========================================
    /**
     * @notice Pause this contract, which prevents future calls to `updateExchangeRate`, and any safe rate
     *         calls will revert.
     * @dev Callable by MULTISIG_ROLE.
     */
    function pause() external requiresAuth {
        accountantState.isPaused = true;
        emit Paused();
    }

    /**
     * @notice Unpause this contract, which allows future calls to `updateExchangeRate`, and any safe rate
     *         calls will stop reverting.
     * @dev Callable by MULTISIG_ROLE.
     */
    function unpause() external requiresAuth {
        accountantState.isPaused = false;
        emit Unpaused();
    }

    /**
     * @notice Update the minimum time delay between `updateExchangeRate` calls.
     * @dev There are no input requirements, as it is possible the admin would want
     *      the exchange rate updated as frequently as needed.
     * @dev Callable by OWNER_ROLE.
     */
    function updateDelay(uint32 minimumUpdateDelayInSeconds) external requiresAuth {
        if (minimumUpdateDelayInSeconds > 14 days) revert AccountantWithRateProviders__UpdateDelayTooLarge();
        uint32 oldDelay = accountantState.minimumUpdateDelayInSeconds;
        accountantState.minimumUpdateDelayInSeconds = minimumUpdateDelayInSeconds;
        emit DelayInSecondsUpdated(oldDelay, minimumUpdateDelayInSeconds);
    }

    /**
     * @notice Update the allowed upper bound change of exchange rate between `updateExchangeRateCalls`.
     * @dev Callable by OWNER_ROLE.
     */
    function updateUpper(uint16 allowedExchangeRateChangeUpper) external requiresAuth {
        if (allowedExchangeRateChangeUpper < 1e4) revert AccountantWithRateProviders__UpperBoundTooSmall();
        uint16 oldBound = accountantState.allowedExchangeRateChangeUpper;
        accountantState.allowedExchangeRateChangeUpper = allowedExchangeRateChangeUpper;
        emit UpperBoundUpdated(oldBound, allowedExchangeRateChangeUpper);
    }

    /**
     * @notice Update the allowed lower bound change of exchange rate between `updateExchangeRateCalls`.
     * @dev Callable by OWNER_ROLE.
     */
    function updateLower(uint16 allowedExchangeRateChangeLower) external requiresAuth {
        if (allowedExchangeRateChangeLower > 1e4) revert AccountantWithRateProviders__LowerBoundTooLarge();
        uint16 oldBound = accountantState.allowedExchangeRateChangeLower;
        accountantState.allowedExchangeRateChangeLower = allowedExchangeRateChangeLower;
        emit LowerBoundUpdated(oldBound, allowedExchangeRateChangeLower);
    }

    /**
     * @notice Update the management fee to a new value.
     * @dev Callable by OWNER_ROLE.
     */
    function updateManagementFee(uint16 managementFee) external requiresAuth {
        if (managementFee > 0.2e4) revert AccountantWithRateProviders__ManagementFeeTooLarge();
        uint16 oldFee = accountantState.managementFee;
        accountantState.managementFee = managementFee;
        emit ManagementFeeUpdated(oldFee, managementFee);
    }

    /**
     * @notice Update the payout address fees are sent to.
     * @dev Callable by OWNER_ROLE.
     */
    function updatePayoutAddress(address payoutAddress) external requiresAuth {
        address oldPayout = accountantState.payoutAddress;
        accountantState.payoutAddress = payoutAddress;
        emit PayoutAddressUpdated(oldPayout, payoutAddress);
    }

    /**
     * @notice Update the rate provider data for a specific `asset`.
     * @dev Rate providers must return rates in terms of `base` or
     * an asset pegged to base and they must use the same decimals
     * as `asset`.
     * @dev Callable by OWNER_ROLE.
     */
    function setRateProviderData(ERC20 asset, bool isPeggedToBase, address rateProvider) external requiresAuth {
        rateProviderData[asset] =
            RateProviderData({ isPeggedToBase: isPeggedToBase, rateProvider: IRateProvider(rateProvider) });
        emit RateProviderUpdated(address(asset), isPeggedToBase, rateProvider);
    }

    // ========================================= UPDATE EXCHANGE RATE/FEES FUNCTIONS
    // =========================================

    /**
     * @notice Updates this contract exchangeRate.
     * @dev If new exchange rate is outside of accepted bounds, or if not enough time has passed, this
     *      will pause the contract, and this function will NOT calculate fees owed.
     * @dev Callable by UPDATE_EXCHANGE_RATE_ROLE.
     */
    function updateExchangeRate(uint96 newExchangeRate) external requiresAuth {
        AccountantState storage state = accountantState;
        if (state.isPaused) revert AccountantWithRateProviders__Paused();
        uint64 currentTime = uint64(block.timestamp);
        uint256 currentExchangeRate = state.exchangeRate;
        uint256 currentTotalShares = vault.totalSupply();
        if (
            currentTime < state.lastUpdateTimestamp + state.minimumUpdateDelayInSeconds
                || newExchangeRate > currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeUpper, 1e4)
                || newExchangeRate < currentExchangeRate.mulDivDown(state.allowedExchangeRateChangeLower, 1e4)
        ) {
            // Instead of reverting, pause the contract. This way the exchange rate updater is able to update the
            // exchange rate
            // to a better value, and pause it.
            state.isPaused = true;
        } else {
            // Only update fees if we are not paused.
            // Update fee accounting.
            uint256 shareSupplyToUse = currentTotalShares;
            // Use the minimum between current total supply and total supply for last update.
            if (state.totalSharesLastUpdate < shareSupplyToUse) {
                shareSupplyToUse = state.totalSharesLastUpdate;
            }

            // Determine management fees owned.
            uint256 timeDelta = currentTime - state.lastUpdateTimestamp;
            uint256 minimumAssets = newExchangeRate > currentExchangeRate
                ? shareSupplyToUse.mulDivDown(currentExchangeRate, ONE_SHARE)
                : shareSupplyToUse.mulDivDown(newExchangeRate, ONE_SHARE);
            uint256 managementFeesAnnual = minimumAssets.mulDivDown(state.managementFee, 1e4);
            uint256 newFeesOwedInBase = managementFeesAnnual.mulDivDown(timeDelta, 365 days);

            state.feesOwedInBase += uint128(newFeesOwedInBase);
        }

        state.exchangeRate = newExchangeRate;
        state.totalSharesLastUpdate = uint128(currentTotalShares);
        state.lastUpdateTimestamp = currentTime;

        emit ExchangeRateUpdated(uint96(currentExchangeRate), newExchangeRate, currentTime);
    }

    /**
     * @notice Claim pending fees.
     * @dev This function must be called by the BoringVault.
     * @dev This function will lose precision if the exchange rate
     *      decimals is greater than the feeAsset's decimals.
     */
    function claimFees(ERC20 feeAsset) external {
        if (msg.sender != address(vault)) revert AccountantWithRateProviders__OnlyCallableByBoringVault();

        AccountantState storage state = accountantState;
        if (state.isPaused) revert AccountantWithRateProviders__Paused();
        if (state.feesOwedInBase == 0) revert AccountantWithRateProviders__ZeroFeesOwed();

        // Determine amount of fees owed in feeAsset.
        uint256 feesOwedInFeeAsset;
        RateProviderData memory data = rateProviderData[feeAsset];
        if (address(feeAsset) == address(base)) {
            feesOwedInFeeAsset = state.feesOwedInBase;
        } else {
            uint8 feeAssetDecimals = ERC20(feeAsset).decimals();
            uint256 feesOwedInBaseUsingFeeAssetDecimals =
                changeDecimals(state.feesOwedInBase, decimals, feeAssetDecimals);
            if (data.isPeggedToBase) {
                feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals;
            } else {
                uint256 rate = data.rateProvider.getRate();
                feesOwedInFeeAsset = feesOwedInBaseUsingFeeAssetDecimals.mulDivDown(10 ** feeAssetDecimals, rate);
            }
        }
        // Zero out fees owed.
        state.feesOwedInBase = 0;
        // Transfer fee asset to payout address.
        feeAsset.safeTransferFrom(msg.sender, state.payoutAddress, feesOwedInFeeAsset);

        emit FeesClaimed(address(feeAsset), feesOwedInFeeAsset);
    }

    // ========================================= RATE FUNCTIONS =========================================

    /**
     * @notice Get this BoringVault's current rate in the base.
     */
    function getRate() public view returns (uint256 rate) {
        rate = accountantState.exchangeRate;
    }

    /**
     * @notice Get this BoringVault's current rate in the base.
     * @dev Revert if paused.
     */
    function getRateSafe() external view returns (uint256 rate) {
        if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
        rate = getRate();
    }

    /**
     * @notice Get this BoringVault's current rate in the provided quote.
     * @dev `quote` must have its RateProviderData set, else this will revert.
     * @dev This function will lose precision if the exchange rate
     *      decimals is greater than the quote's decimals.
     */
    function getRateInQuote(ERC20 quote) public view returns (uint256 rateInQuote) {
        if (address(quote) == address(base)) {
            rateInQuote = accountantState.exchangeRate;
        } else {
            RateProviderData memory data = rateProviderData[quote];
            uint8 quoteDecimals = ERC20(quote).decimals();
            uint256 exchangeRateInQuoteDecimals = changeDecimals(accountantState.exchangeRate, decimals, quoteDecimals);
            if (data.isPeggedToBase) {
                rateInQuote = exchangeRateInQuoteDecimals;
            } else {
                uint256 quoteRate = data.rateProvider.getRate();
                uint256 oneQuote = 10 ** quoteDecimals;
                rateInQuote = oneQuote.mulDivDown(exchangeRateInQuoteDecimals, quoteRate);
            }
        }
    }

    /**
     * @notice Get this BoringVault's current rate in the provided quote.
     * @dev `quote` must have its RateProviderData set, else this will revert.
     * @dev Revert if paused.
     */
    function getRateInQuoteSafe(ERC20 quote) external view returns (uint256 rateInQuote) {
        if (accountantState.isPaused) revert AccountantWithRateProviders__Paused();
        rateInQuote = getRateInQuote(quote);
    }

    // ========================================= INTERNAL HELPER FUNCTIONS =========================================
    /**
     * @notice Used to change the decimals of precision used for an amount.
     */
    function changeDecimals(uint256 amount, uint8 fromDecimals, uint8 toDecimals) internal pure returns (uint256) {
        if (fromDecimals == toDecimals) {
            return amount;
        } else if (fromDecimals < toDecimals) {
            return amount * 10 ** (toDecimals - fromDecimals);
        } else {
            return amount / 10 ** (fromDecimals - toDecimals);
        }
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

import { ERC20 } from "@solmate/tokens/ERC20.sol";
import { WETH } from "@solmate/tokens/WETH.sol";
import { BoringVault } from "src/base/BoringVault.sol";
import { AccountantWithRateProviders } from "src/base/Roles/AccountantWithRateProviders.sol";
import { FixedPointMathLib } from "@solmate/utils/FixedPointMathLib.sol";
import { SafeTransferLib } from "@solmate/utils/SafeTransferLib.sol";
import { BeforeTransferHook } from "src/interfaces/BeforeTransferHook.sol";
import { Auth, Authority } from "@solmate/auth/Auth.sol";
import { ReentrancyGuard } from "@solmate/utils/ReentrancyGuard.sol";

/**
 * @title TellerWithMultiAssetSupport
 * @custom:security-contact [email protected]
 */
contract TellerWithMultiAssetSupport is Auth, BeforeTransferHook, ReentrancyGuard {
    using FixedPointMathLib for uint256;
    using SafeTransferLib for ERC20;
    using SafeTransferLib for WETH;

    // ========================================= CONSTANTS =========================================

    /**
     * @notice Native address used to tell the contract to handle native asset deposits.
     */
    address internal constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    /**
     * @notice The maximum possible share lock period.
     */
    uint256 internal constant MAX_SHARE_LOCK_PERIOD = 3 days;

    // ========================================= STATE =========================================

    /**
     * @notice Mapping ERC20s to an isSupported bool.
     */
    mapping(ERC20 => bool) public isSupported;

    /**
     * @notice The deposit nonce used to map to a deposit hash.
     */
    uint96 public depositNonce = 1;

    /**
     * @notice After deposits, shares are locked to the msg.sender's address
     *         for `shareLockPeriod`.
     * @dev During this time all transfers from msg.sender will revert, and
     *      deposits are refundable.
     */
    uint64 public shareLockPeriod;

    /**
     * @notice Used to pause calls to `deposit` and `depositWithPermit`.
     */
    bool public isPaused;

    /**
     * @dev Maps deposit nonce to keccak256(address receiver, address depositAsset, uint256 depositAmount, uint256
     * shareAmount, uint256 timestamp, uint256 shareLockPeriod).
     */
    mapping(uint256 => bytes32) public publicDepositHistory;

    /**
     * @notice Maps user address to the time their shares will be unlocked.
     */
    mapping(address => uint256) public shareUnlockTime;

    //============================== ERRORS ===============================

    error TellerWithMultiAssetSupport__ShareLockPeriodTooLong();
    error TellerWithMultiAssetSupport__SharesAreLocked();
    error TellerWithMultiAssetSupport__SharesAreUnLocked();
    error TellerWithMultiAssetSupport__BadDepositHash();
    error TellerWithMultiAssetSupport__AssetNotSupported();
    error TellerWithMultiAssetSupport__ZeroAssets();
    error TellerWithMultiAssetSupport__MinimumMintNotMet();
    error TellerWithMultiAssetSupport__MinimumAssetsNotMet();
    error TellerWithMultiAssetSupport__PermitFailedAndAllowanceTooLow();
    error TellerWithMultiAssetSupport__ZeroShares();
    error TellerWithMultiAssetSupport__Paused();

    //============================== EVENTS ===============================

    event Paused();
    event Unpaused();
    event AssetAdded(address indexed asset);
    event AssetRemoved(address indexed asset);
    event Deposit(
        uint256 indexed nonce,
        address indexed receiver,
        address indexed depositAsset,
        uint256 depositAmount,
        uint256 shareAmount,
        uint256 depositTimestamp,
        uint256 shareLockPeriodAtTimeOfDeposit
    );
    event BulkDeposit(address indexed asset, uint256 depositAmount);
    event BulkWithdraw(address indexed asset, uint256 shareAmount);
    event DepositRefunded(uint256 indexed nonce, bytes32 depositHash, address indexed user);

    //============================== IMMUTABLES ===============================

    /**
     * @notice The BoringVault this contract is working with.
     */
    BoringVault public immutable vault;

    /**
     * @notice The AccountantWithRateProviders this contract is working with.
     */
    AccountantWithRateProviders public immutable accountant;

    /**
     * @notice One share of the BoringVault.
     */
    uint256 internal immutable ONE_SHARE;

    constructor(address _owner, address _vault, address _accountant) Auth(_owner, Authority(address(0))) {
        vault = BoringVault(payable(_vault));
        ONE_SHARE = 10 ** vault.decimals();
        accountant = AccountantWithRateProviders(_accountant);
    }

    // ========================================= ADMIN FUNCTIONS =========================================

    /**
     * @notice Pause this contract, which prevents future calls to `deposit` and `depositWithPermit`.
     * @dev Callable by MULTISIG_ROLE.
     */
    function pause() external requiresAuth {
        isPaused = true;
        emit Paused();
    }

    /**
     * @notice Unpause this contract, which allows future calls to `deposit` and `depositWithPermit`.
     * @dev Callable by MULTISIG_ROLE.
     */
    function unpause() external requiresAuth {
        isPaused = false;
        emit Unpaused();
    }

    /**
     * @notice Adds this asset as a deposit asset.
     * @dev The accountant must also support pricing this asset, else the `deposit` call will revert.
     * @dev Callable by OWNER_ROLE.
     */
    function addAsset(ERC20 asset) external requiresAuth {
        isSupported[asset] = true;
        emit AssetAdded(address(asset));
    }

    /**
     * @notice Removes this asset as a deposit asset.
     * @dev Callable by OWNER_ROLE.
     */
    function removeAsset(ERC20 asset) external requiresAuth {
        isSupported[asset] = false;
        emit AssetRemoved(address(asset));
    }

    /**
     * @notice Sets the share lock period.
     * @dev This not only locks shares to the user address, but also serves as the pending deposit period, where
     * deposits can be reverted.
     * @dev If a new shorter share lock period is set, users with pending share locks could make a new deposit to
     * receive 1 wei shares,
     *      and have their shares unlock sooner than their original deposit allows. This state would allow for the user
     * deposit to be refunded,
     *      but only if they have not transferred their shares out of there wallet. This is an accepted limitation, and
     * should be known when decreasing
     *      the share lock period.
     * @dev Callable by OWNER_ROLE.
     */
    function setShareLockPeriod(uint64 _shareLockPeriod) external requiresAuth {
        if (_shareLockPeriod > MAX_SHARE_LOCK_PERIOD) revert TellerWithMultiAssetSupport__ShareLockPeriodTooLong();
        shareLockPeriod = _shareLockPeriod;
    }

    // ========================================= BeforeTransferHook FUNCTIONS =========================================

    /**
     * @notice Implement beforeTransfer hook to check if shares are locked.
     */
    function beforeTransfer(address from) public view {
        if (shareUnlockTime[from] > block.timestamp) revert TellerWithMultiAssetSupport__SharesAreLocked();
    }

    // ========================================= REVERT DEPOSIT FUNCTIONS =========================================

    /**
     * @notice Allows DEPOSIT_REFUNDER_ROLE to revert a pending deposit.
     * @dev Once a deposit share lock period has passed, it can no longer be reverted.
     * @dev It is possible the admin does not setup the BoringVault to call the transfer hook,
     *      but this contract can still be saving share lock state. In the event this happens
     *      deposits are still refundable if the user has not transferred their shares.
     *      But there is no guarantee that the user has not transferred their shares.
     * @dev Callable by STRATEGIST_MULTISIG_ROLE.
     */
    function refundDeposit(
        uint256 nonce,
        address receiver,
        address depositAsset,
        uint256 depositAmount,
        uint256 shareAmount,
        uint256 depositTimestamp,
        uint256 shareLockUpPeriodAtTimeOfDeposit
    )
        external
        requiresAuth
    {
        if ((block.timestamp - depositTimestamp) > shareLockUpPeriodAtTimeOfDeposit) {
            // Shares are already unlocked, so we can not revert deposit.
            revert TellerWithMultiAssetSupport__SharesAreUnLocked();
        }
        bytes32 depositHash = keccak256(
            abi.encode(
                receiver, depositAsset, depositAmount, shareAmount, depositTimestamp, shareLockUpPeriodAtTimeOfDeposit
            )
        );
        if (publicDepositHistory[nonce] != depositHash) revert TellerWithMultiAssetSupport__BadDepositHash();

        // Delete hash to prevent refund gas.
        delete publicDepositHistory[nonce];

        // Burn shares and refund assets to receiver.
        vault.exit(receiver, ERC20(depositAsset), depositAmount, receiver, shareAmount);

        emit DepositRefunded(nonce, depositHash, receiver);
    }

    // ========================================= USER FUNCTIONS =========================================

    /**
     * @notice Allows users to deposit into the BoringVault, if this contract is not paused.
     * @dev Publicly callable.
     */
    function deposit(
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 minimumMint
    )
        external
        requiresAuth
        nonReentrant
        returns (uint256 shares)
    {
        if (isPaused) revert TellerWithMultiAssetSupport__Paused();
        if (!isSupported[depositAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, msg.sender);

        _afterPublicDeposit(msg.sender, depositAsset, depositAmount, shares, shareLockPeriod);
    }

    /**
     * @notice Allows users to deposit into BoringVault using permit.
     * @dev Publicly callable.
     */
    function depositWithPermit(
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 minimumMint,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        external
        requiresAuth
        nonReentrant
        returns (uint256 shares)
    {
        if (isPaused) revert TellerWithMultiAssetSupport__Paused();
        if (!isSupported[depositAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        // solhint-disable-next-line no-empty-blocks
        try depositAsset.permit(msg.sender, address(vault), depositAmount, deadline, v, r, s) { }
        catch {
            if (depositAsset.allowance(msg.sender, address(vault)) < depositAmount) {
                revert TellerWithMultiAssetSupport__PermitFailedAndAllowanceTooLow();
            }
        }
        shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, msg.sender);

        _afterPublicDeposit(msg.sender, depositAsset, depositAmount, shares, shareLockPeriod);
    }

    /**
     * @notice Allows on ramp role to deposit into this contract.
     * @dev Does NOT support native deposits.
     * @dev Callable by SOLVER_ROLE.
     */
    function bulkDeposit(
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 minimumMint,
        address to
    )
        external
        requiresAuth
        nonReentrant
        returns (uint256 shares)
    {
        if (!isSupported[depositAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        shares = _erc20Deposit(depositAsset, depositAmount, minimumMint, to);
        emit BulkDeposit(address(depositAsset), depositAmount);
    }

    /**
     * @notice Allows off ramp role to withdraw from this contract.
     * @dev Callable by SOLVER_ROLE.
     */
    function bulkWithdraw(
        ERC20 withdrawAsset,
        uint256 shareAmount,
        uint256 minimumAssets,
        address to
    )
        external
        requiresAuth
        returns (uint256 assetsOut)
    {
        if (!isSupported[withdrawAsset]) revert TellerWithMultiAssetSupport__AssetNotSupported();

        if (shareAmount == 0) revert TellerWithMultiAssetSupport__ZeroShares();
        assetsOut = shareAmount.mulDivDown(accountant.getRateInQuoteSafe(withdrawAsset), ONE_SHARE);
        if (assetsOut < minimumAssets) revert TellerWithMultiAssetSupport__MinimumAssetsNotMet();
        vault.exit(to, withdrawAsset, assetsOut, msg.sender, shareAmount);
        emit BulkWithdraw(address(withdrawAsset), shareAmount);
    }

    // ========================================= INTERNAL HELPER FUNCTIONS =========================================

    /**
     * @notice Implements a common ERC20 deposit into BoringVault.
     */
    function _erc20Deposit(
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 minimumMint,
        address to
    )
        internal
        returns (uint256 shares)
    {
        if (depositAmount == 0) revert TellerWithMultiAssetSupport__ZeroAssets();
        shares = depositAmount.mulDivDown(ONE_SHARE, accountant.getRateInQuoteSafe(depositAsset));
        if (shares < minimumMint) revert TellerWithMultiAssetSupport__MinimumMintNotMet();
        vault.enter(msg.sender, depositAsset, depositAmount, to, shares);
    }

    /**
     * @notice Handle share lock logic, and event.
     */
    function _afterPublicDeposit(
        address user,
        ERC20 depositAsset,
        uint256 depositAmount,
        uint256 shares,
        uint256 currentShareLockPeriod
    )
        internal
    {
        shareUnlockTime[user] = block.timestamp + currentShareLockPeriod;

        uint256 nonce = depositNonce;
        publicDepositHistory[nonce] =
            keccak256(abi.encode(user, depositAsset, depositAmount, shares, block.timestamp, currentShareLockPeriod));
        depositNonce++;
        emit Deposit(nonce, user, address(depositAsset), depositAmount, shares, block.timestamp, currentShareLockPeriod);
    }
}

// SPDX-License-Identifier: MIT
pragma solidity 0.8.25;

interface BeforeTransferHook {
    function beforeTransfer(address from) external view;
}

File 27 of 27 : IRateProvider.sol
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity ^0.8.0;

interface IRateProvider {
    function getRate() external view returns (uint256);
}

Settings
{
  "evmVersion": "cancun",
  "libraries": {},
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "remappings": [
    "@solmate/=lib/solmate/src/",
    "@forge-std/=lib/forge-std/src/",
    "forge-std/=lib/forge-std/src/",
    "@ds-test/=lib/forge-std/lib/ds-test/src/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "@ion-protocol/=lib/nucleus-boring-vault/lib/ion-protocol/src/",
    "@layerzerolabs/=node_modules/@layerzerolabs/",
    "@executooor/=lib/executooor/contracts/",
    "@uniswap-core/=lib/v3-core/contracts/",
    "@uniswap-periphery/=lib/v3-periphery/contracts/",
    "1inch-v2-contracts/=lib/1inch-v2-contracts/contracts/",
    "@axelar-network/=node_modules/@axelar-network/",
    "@balancer-labs/v2-interfaces/=lib/nucleus-boring-vault/lib/ion-protocol/lib/balancer-v2-monorepo/pkg/interfaces/",
    "@balancer-labs/v2-pool-stable/=lib/nucleus-boring-vault/lib/ion-protocol/lib/balancer-v2-monorepo/pkg/pool-stable/",
    "@chainlink/=node_modules/@chainlink/",
    "@chainlink/contracts/=lib/nucleus-boring-vault/lib/ion-protocol/lib/chainlink/contracts/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@openzeppelin/contracts-upgradeable/=lib/nucleus-boring-vault/lib/ion-protocol/lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v3-core/=lib/nucleus-boring-vault/lib/ion-protocol/lib/v3-core/",
    "@uniswap/v3-periphery/=lib/nucleus-boring-vault/lib/ion-protocol/lib/v3-periphery/",
    "balancer-v2-monorepo/=lib/nucleus-boring-vault/lib/ion-protocol/lib/",
    "chainlink/=lib/nucleus-boring-vault/lib/ion-protocol/lib/chainlink/",
    "createx/=lib/nucleus-boring-vault/lib/createx/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "executooor/=lib/executooor/contracts/",
    "forge-safe/=lib/nucleus-boring-vault/lib/ion-protocol/lib/forge-safe/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat-deploy/=node_modules/hardhat-deploy/",
    "ion-protocol/=lib/nucleus-boring-vault/lib/ion-protocol/",
    "nucleus-boring-vault/=lib/nucleus-boring-vault/",
    "openzeppelin-contracts-upgradeable/=lib/nucleus-boring-vault/lib/ion-protocol/lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "openzeppelin/=lib/nucleus-boring-vault/lib/createx/lib/openzeppelin-contracts/contracts/",
    "pendle-core-v2-public/=lib/nucleus-boring-vault/lib/ion-protocol/lib/pendle-core-v2-public/contracts/",
    "solady/=lib/nucleus-boring-vault/lib/ion-protocol/lib/solady/",
    "solarray/=lib/nucleus-boring-vault/lib/ion-protocol/lib/solarray/src/",
    "solidity-bytes-utils/=node_modules/solidity-bytes-utils/",
    "solidity-stringutils/=lib/nucleus-boring-vault/lib/ion-protocol/lib/forge-safe/lib/surl/lib/solidity-stringutils/",
    "solmate/=lib/solmate/src/",
    "surl/=lib/nucleus-boring-vault/lib/ion-protocol/lib/forge-safe/lib/surl/",
    "v3-core/=lib/v3-core/",
    "v3-periphery/=lib/v3-periphery/contracts/"
  ],
  "viaIR": true
}

Contract Security Audit

Contract ABI

API
[{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"contract IAtomicQueueUCP","name":"_queue","type":"address"},{"internalType":"address[]","name":"approvedSolvers","type":"address[]"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"MultiAssetAtomicSolverRedeem___AlreadyInSolveContext","type":"error"},{"inputs":[{"internalType":"address","name":"vault","type":"address"},{"internalType":"address","name":"teller","type":"address"}],"name":"MultiAssetAtomicSolverRedeem___BoringVaultTellerMismatch","type":"error"},{"inputs":[{"internalType":"address","name":"wantAsset","type":"address"}],"name":"MultiAssetAtomicSolverRedeem___DuplicateWantAsset","type":"error"},{"inputs":[],"name":"MultiAssetAtomicSolverRedeem___FailedToSolve","type":"error"},{"inputs":[{"internalType":"int256","name":"globalSlippagePriceMinimum","type":"int256"},{"internalType":"int256[]","name":"balanceDeltas","type":"int256[]"},{"internalType":"int256","name":"actualSlippage","type":"int256"}],"name":"MultiAssetAtomicSolverRedeem___GlobalSlippageThresholdExceeded","type":"error"},{"inputs":[{"internalType":"uint256","name":"redeemedAmount","type":"uint256"},{"internalType":"uint256","name":"requiredAmount","type":"uint256"}],"name":"MultiAssetAtomicSolverRedeem___InsufficientAssetsRedeemed","type":"error"},{"inputs":[{"internalType":"uint256","name":"offerNeeded","type":"uint256"},{"internalType":"uint256","name":"currentBalance","type":"uint256"},{"internalType":"uint256","name":"maxAllowableOfferAmountFromSolver","type":"uint256"}],"name":"MultiAssetAtomicSolverRedeem___InsufficientOfferAmount","type":"error"},{"inputs":[],"name":"MultiAssetAtomicSolverRedeem___InvalidCaller","type":"error"},{"inputs":[],"name":"MultiAssetAtomicSolverRedeem___MismatchedArrayLengths","type":"error"},{"inputs":[{"internalType":"address","name":"caller","type":"address"},{"internalType":"address","name":"queue","type":"address"}],"name":"MultiAssetAtomicSolverRedeem___OnlyQueue","type":"error"},{"inputs":[],"name":"MultiAssetAtomicSolverRedeem___OnlyRedeemAllowed","type":"error"},{"inputs":[{"internalType":"uint256","name":"actualAssets","type":"uint256"},{"internalType":"uint256","name":"maxAssets","type":"uint256"}],"name":"MultiAssetAtomicSolverRedeem___SolveMaxAssetsExceeded","type":"error"},{"inputs":[],"name":"MultiAssetAtomicSolverRedeem___WrongInitiator","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"inputs":[{"internalType":"bytes","name":"runData","type":"bytes"},{"internalType":"address","name":"initiator","type":"address"},{"internalType":"contract ERC20","name":"offer","type":"address"},{"internalType":"contract ERC20","name":"want","type":"address"},{"internalType":"uint256","name":"offerReceived","type":"uint256"},{"internalType":"uint256","name":"wantApprovalAmount","type":"uint256"}],"name":"finishSolve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isApprovedSolver","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract ERC20","name":"offer","type":"address"},{"components":[{"internalType":"contract ERC20","name":"asset","type":"address"},{"internalType":"uint256","name":"minimumAssetsOut","type":"uint256"},{"internalType":"uint256","name":"maxAssets","type":"uint256"},{"internalType":"uint256","name":"excessAssetAmount","type":"uint256"},{"internalType":"bool","name":"useSolverBalanceFirst","type":"bool"},{"internalType":"address[]","name":"users","type":"address[]"},{"internalType":"uint256","name":"clearingPriceForAsset","type":"uint256"},{"internalType":"uint256","name":"maxAllowableOfferAmountFromSolver","type":"uint256"}],"internalType":"struct MultiAssetAtomicSolverRedeemUCP.WantAssetData[]","name":"wantAssets","type":"tuple[]"},{"internalType":"contract TellerWithMultiAssetSupport","name":"teller","type":"address"},{"internalType":"int256","name":"globalSlippagePriceMinimum","type":"int256"},{"internalType":"address","name":"redeemCurrencyForExcessOffer","type":"address"}],"name":"multiAssetRedeemSolve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"queue","outputs":[{"internalType":"contract IAtomicQueueUCP","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"solvers","type":"address[]"}],"name":"toggleApprovedSolvers","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]

604060a060405234610197576121828038038061001b816101af565b92833981019160608284031261019757610034826101d4565b6020938484015160018060a01b039283821682036101975760408601516001600160401b039687821161019757019280601f8501121561019757835196871161019b576005938760051b898061008b8184016101af565b809b81520191830101928311610197578990818895949301905b838210610176575050505016801561015e575f80546001600160a01b03198116831782558516907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09080a36080525f5b845181101561012357828682841b87010151165f52600190818752845f208260ff19825416179055016100f5565b604051611f9990816101e9823960805181818161010f01528181610379015281816105530152818161087f0152818161154f015261160a0152f35b604051631e4fbdf760e01b81525f6004820152602490fd5b829394955091819261018882936101d4565b815201910187949392916100a5565b5f80fd5b634e487b7160e01b5f52604160045260245ffd5b6040519190601f01601f191682016001600160401b0381118382101761019b57604052565b51906001600160a01b03821682036101975756fe60806040526004361015610011575f80fd5b5f3560e01c80631644bcf5146108bb5780632ddd62ce146102e857806362218330146102ab578063715018a6146102545780638da5cb5b1461022d578063d87a482a1461013e578063e10d29ee146100fa5763f2fde38b14610071575f80fd5b346100f65760203660031901126100f65761008a611a23565b610092611bef565b6001600160a01b039081169081156100de575f54826001600160601b0360a01b8216175f55167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b604051631e4fbdf760e01b81525f6004820152602490fd5b5f80fd5b346100f6575f3660031901126100f6576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b346100f6576020806003193601126100f65760043567ffffffffffffffff81116100f657366023820112156100f657806004013561017b81611a8b565b916101896040519384611a69565b81835260248484019260051b820101913683116100f6576024859201905b8382106102165782856101b8611bef565b5f5b8151811015610214576001600160a01b0390816101d78285611ac2565b51165f5260019182855260ff908160405f20541615906101f78487611ac2565b51165f5283865260405f209160ff198354169116179055016101ba565b005b82809161022284611a39565b8152019101906101a7565b346100f6575f3660031901126100f6575f546040516001600160a01b039091168152602090f35b346100f6575f3660031901126100f65761026c611bef565b5f80546001600160a01b0319811682556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346100f65760203660031901126100f6576001600160a01b036102cc611a23565b165f526001602052602060ff60405f2054166040519015158152f35b346100f65760c03660031901126100f65767ffffffffffffffff6004358181116100f657366023820112156100f65780600401359182116100f6576024810190828101903660248301116100f6576024356001600160a01b038116908190036100f6576044356001600160a01b03811690036100f6576064356001600160a01b03811690036100f65730036108a9577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031633036108625760209103126100f657803560028110156100f657806103d25760405163a903bc4d60e01b8152600490fd5b6001146103db57005b5f6020604051936103f582601f19601f8401160186611a69565b808552808286019485378401015260c0828051810103126100f6576002905110156100f6576040810151906001600160a01b03821682036100f657608081015160a0820151916001600160a01b03831683036100f65760c0015160405163fbfa77cf60e01b81529091906020816004816001600160a01b0388165afa908115610690575f91610833575b506001600160a01b0390811660443590911603610808578060a435116107e857506104b46064356001600160a01b0316611c46565b92949291159050610750576040516370a0823160e01b81526001600160a01b03868116600483015290939060209085906024908290606435165afa938415610690575f9461071c575b5061050a8560a435611b03565b841061069b5750505f905b816105e1575b505050505b60a43561052957005b6105449060a4359030906001600160a01b0316606435611d84565b60405163095ea7b360e01b81527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316600482015260a43560248201526020905f90604490826064355af13d15601f3d1160015f5114161716156105ab57005b60405162461bcd60e51b815260206004820152600e60248201526d1054141493d59157d1905253115160921b6044820152606490fd5b6105fb6020936105f66106459660a435611b03565b611bd1565b604051633e64ce9960e01b8152606480356001600160a01b0390811660048401526024830195909552604482019290925292861690830152909283919082905f9082906084820190565b03926001600160a01b03165af1801561069057610665575b80808061051b565b602090813d8311610689575b61067b8183611a69565b810103126100f6578161065d565b503d610671565b6040513d5f823e3d90fd5b6106d06106ae856105f68860a435611b03565b6106ca6106c56044356001600160a01b0316611c1a565b611bde565b90611d2a565b90801561070a5761070492604435926001600160a01b038916926001906106fa905f198401611d20565b0190151502611ea1565b90610515565b634e487b715f5260126020526024601cfd5b9093506020813d602011610748575b8161073860209383611a69565b810103126100f6575192866104fd565b3d915061072b565b92906107616106ae8360a435611b03565b92801561070a5761079f946020946105fb9261079692604435926001600160a01b038b16926001906106fa905f198401611d20565b9260a435611b03565b03926001600160a01b03165af18015610690576107bd575b50610520565b602090813d83116107e1575b6107d38183611a69565b810103126100f657816107b7565b503d6107c9565b604490604051906308a9e02b60e01b825260a43560048301526024820152fd5b6040516340d2153760e01b81526001600160a01b036044803582166004840152908516602483015290fd5b610855915060203d60201161085b575b61084d8183611a69565b810190611aa3565b8561047f565b503d610843565b60405163e34780db60e01b81523360048201526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166024820152604490fd5b6040516312d4921560e31b8152600490fd5b346100f65760a03660031901126100f6576108d4611a23565b6024359067ffffffffffffffff82116100f657366023830112156100f65767ffffffffffffffff8260040135116100f657366024836004013560051b840101116100f6576044356001600160a01b03811681036100f657608435926001600160a01b03841684036100f657335f52600160205260ff60405f20541615611a1257604051634fb3ccc560e01b8152936020856004816001600160a01b0387165afa948515610690575f956119f1575b506040516001600160601b03198560601b166020820152601481526109a681611a4d565b805160209182012060405163313ce56760e01b815291826004816001600160a01b038b165afa918215610690575f926119d0575b505d6109e98260040135611a8b565b906109f76040519283611a69565b6004830135808352610a0890611a8b565b601f190136602084013760048301356001810110610d9757610a306001846004013501611a8b565b95610a3e6040519788611a69565b6004840135600101808852610a5290611a8b565b601f1901366020890137610a698460040135611a8b565b90610a776040519283611a69565b6004850135808352601f1990610a8c90611a8b565b013660208401375f915b856004013583106116de5750506040516370a0823160e01b8152336004820152906020826024816001600160a01b038b165afa918215610690575f926116a8575b50610ae29088611ac2565b525f5b8360040135811061110957506001600160a01b03811615611036576040516370a0823160e01b81523060048201526020816024816001600160a01b038a165afa908115610690575f91611004575b5060405191633e64ce9960e01b835260018060a01b0316600483015260248201525f60448201523360648201526020816084815f60018060a01b0389165af1801561069057610fd9575b505b60405163fbfa77cf60e01b81525f9290916020836004816001600160a01b0389165afa908115610690576004935f92610fb8575b506020610bc86001600160a01b038416611c1a565b604051634fb3ccc560e01b815290979095869182906001600160a01b03165afa938415610690576004946020915f91610f9b575b506040516333cd77e760e11b815295869182906001600160a01b03165afa938415610690575f94610f67575b50915f925b81600401358410610ddf5750506040516370a0823160e01b815233600482015290602090829060249082906001600160a01b03165afa908115610690575f91610dab575b50610c8a610c9191610c83848a611ac2565b5190611b7c565b9187611ac2565b5284515f1990818101908111610d9757610cac5f9188611ac2565b511260011902600118908651908101908111610d9757610cfc94610cf693610ce8610cda610cf0948b611ac2565b51928360ff1d918291611bde565b930118611e09565b90611b94565b90611bb6565b918260643513610d33575f8260405160208101916001600160601b03199060601b16825260148152610d2d81611a4d565b5190205d005b6040516001629772bb60e01b031981526064803560048301526060602483015282519082018190525f949193506084840192602001905b808610610d7f57505082935060448301520390fd5b90926020806001928651815201940195019490610d6a565b634e487b7160e01b5f52601160045260245ffd5b90506020813d602011610dd7575b81610dc660209383611a69565b810103126100f65751610c8a610c71565b3d9150610db9565b9092610dfb610df682866004013560248801611b10565b611b32565b6040516370a0823160e01b815233600482015290966020826024816001600160a01b038c165afa918215610690578b8985948c935f91610f25575b50610e9d84610e8c610cf69686610e86610e7a5f98610e61610eab99610eb99f9c8d610c8391611ac2565b610e6b8c86611ac2565b526001600160a01b0316611c46565b509a9150508992611ac2565b51611cb1565b94610e978a8c611ac2565b51611d3d565b8b8460ff1d80860118611e09565b911260011902600118611b94565b9560405160208101916001600160601b03199060601b16825260148152610edf81611a4d565b51902090600182018211610d9757600282016001830111610d9757600382016002830111610d97575f600383826001955d828582015d82600282015d015d019290610c2d565b9550505050506020823d602011610f5f575b81610f4460209383611a69565b810103126100f657905182919089908c908a90610e9d610e36565b3d9150610f37565b9093506020813d602011610f93575b81610f8360209383611a69565b810103126100f657519288610c28565b3d9150610f76565b610fb29150823d841161085b5761084d8183611a69565b8a610bfc565b610fd291925060203d60201161085b5761084d8183611a69565b9088610bb3565b602090813d8311610ffd575b610fef8183611a69565b810103126100f65785610b7d565b503d610fe5565b90506020813d60201161102e575b8161101f60209383611a69565b810103126100f6575187610b33565b3d9150611012565b506040516370a0823160e01b81523060048201526020816024816001600160a01b0389165afa908115610690575f916110d7575b505f60446020926040519063a9059cbb60e01b8252336004830152602482015282885af13d15601f3d1160015f5114161716610b7f5760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606490fd5b90506020813d602011611101575b816110f260209383611a69565b810103126100f657515f61106a565b3d91506110e5565b602061111d82866004013560248801611b10565b013590604061113482876004013560248901611b10565b01356111408286611ac2565b519060405193600160208601523360408601526060850152608084015260018060a01b03871660a084015260c083015260c082528160e081011067ffffffffffffffff60e0840111176116625760e082016040526111b36111a982876004013560248901611b10565b60a0810190611b46565b15159050611509576111d0610df682876004013560248901611b10565b60c0838051810103126100f6576002602084015110156100f65760408301516001600160a01b03811681036100f65760a0840151936001600160a01b03851685036100f65760c0015160405163fbfa77cf60e01b81529094906020816004816001600160a01b0386165afa908115610690575f916114ea575b506001600160a01b03908116908b16036114bf576001600160a01b038316948a9061127387611c46565b9392949190505f146113ec57506040516370a0823160e01b81526001600160a01b038616600482015297602090899060249082905afa978815610690575f986113b8575b508288106113675750505f905b816112da575b5050505050600191505b01610ae5565b6112e960209596975f92611bd1565b604051633e64ce9960e01b81526001600160a01b0397881660048201526024810193909352604483015292851660648201529384926084928492165af180156106905761133c575b8080808085946112ca565b602090813d8311611360575b6113528183611a69565b810103126100f65787611331565b503d611348565b61138a8d6106ca6106c561137b8c88611bd1565b926001600160a01b0316611c1a565b90801561070a576113b2928e926001600160a01b038816926001906106fa905f198401611d20565b906112c4565b9097506020813d6020116113e4575b816113d460209383611a69565b810103126100f65751968e6112b7565b3d91506113c7565b6114129192969798506106c561140c9160018060a09997991b0316611c1a565b85611d2a565b94811561070a576020955f9261143f928f926001600160a01b038716926001906106fa905f198401611d20565b604051633e64ce9960e01b81526001600160a01b039788166004820152602481019190915260448101949094529085166064840152919384926084928492165af1801561069057611494575b506001906112d4565b602090813d83116114b8575b6114aa8183611a69565b810103126100f6578761148b565b503d6114a0565b6040516340d2153760e01b81526001600160a01b038b81166004830152919091166024820152604490fd5b611503915060203d60201161085b5761084d8183611a69565b8c611249565b61151e610df682876004013560248901611b10565b916115346111a983886004013560248a01611b10565b909160c061154a858a6004013560248c01611b10565b0135917f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163b156100f657604051633ea1420760e11b81526001600160a01b03808d166004830152909616602487015260c0604487015260c486018190529192859260e484019291905f905b80821061167657505050602091825f9585936003198585030160648601528051928391828652018685015e828201850187905230608485015260a4840152601f01601f191601030181837f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03165af1801561069057611648575b600191506112d4565b67ffffffffffffffff82116116625760019160405261163f565b634e487b7160e01b5f52604160045260245ffd5b91959450919260019060209081906001600160a01b036116958a611a39565b16815201960192018794959392916115be565b9091506020813d6020116116d6575b816116c460209383611a69565b810103126100f6575190610ae2610ad7565b3d91506116b7565b90915f5b81811061197757506116ff610df682886004013560248a01611b10565b604051634104b9ed60e11b81526001600160a01b039182166004820152906020908290602490829088165afa908115610690575f91611945575b506117448287611ac2565b5261174f8186611ac2565b51156119335761176a610df682886004013560248a01611b10565b90606061177f82896004013560248b01611b10565b0135916080611796838a6004013560248c01611b10565b01359081151582036100f65760e06117b6848b6004013560248d01611b10565b01359160405160208101906001600160601b03198460601b168252601481526117de81611a4d565b51902090600182018211610d9757600282016001830111610d9757600382016002830111610d975760405163313ce56760e01b815292602090849060049082906001600160a01b03165afa908115610690576024966003945f93611902575b50835d600183015d600282015d015d60206001600160a01b0361186a610df68460048c0135878d01611b10565b16604051938480926370a0823160e01b82523360048301525afa8015610690575f906118cf575b6001925061189f828c611ac2565b52818060a01b036118bb610df6838a6004013560248c01611b10565b166118c68285611ac2565b52019190610a96565b506020823d6020116118fa575b816118e960209383611a69565b810103126100f65760019151611891565b3d91506118dc565b61192591935060203d60201161192c575b61191d8183611a69565b810190611aea565b915f61183d565b503d611913565b60405163121d85b560e11b8152600490fd5b90506020813d60201161196f575b8161196060209383611a69565b810103126100f657518a611739565b3d9150611953565b6001600160a01b03611994610df68460048b013560248c01611b10565b166001600160a01b036119a78386611ac2565b511681146119b857506001016116e2565b6024906040519063096449b160e01b82526004820152fd5b6119ea91925060203d60201161192c5761191d8183611a69565b90876109da565b611a0b91955060203d60201161085b5761084d8183611a69565b9385610982565b637e94ab9360e11b60805260046080fd5b600435906001600160a01b03821682036100f657565b35906001600160a01b03821682036100f657565b6040810190811067ffffffffffffffff82111761166257604052565b90601f8019910116810190811067ffffffffffffffff82111761166257604052565b67ffffffffffffffff81116116625760051b60200190565b908160209103126100f657516001600160a01b03811681036100f65790565b8051821015611ad65760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b908160209103126100f6575160ff811681036100f65790565b91908201809211610d9757565b9190811015611ad65760051b8101359060fe19813603018212156100f6570190565b356001600160a01b03811681036100f65790565b903590601e19813603018212156100f6570180359067ffffffffffffffff82116100f657602001918160051b360383136100f657565b81810392915f138015828513169184121617610d9757565b81810292915f8212600160ff1b821416610d97578184051490151715610d9757565b9190915f8382019384129112908015821691151617610d9757565b91908203918211610d9757565b60ff16604d8111610d9757600a0a90565b5f546001600160a01b03163303611c0257565b60405163118cdaa760e01b8152336004820152602490fd5b60405160208101916001600160601b03199060601b16825260148152611c3f81611a4d565b5190205c90565b60405160208101916001600160601b03199060601b16825260148152611c6b81611a4d565b51902060018101808211610d97576002820192838211610d97576003830192838511610d97575c93915c92915c915c90565b9060ff8091169116039060ff8211610d9757565b9160ff811660ff83168181145f14611cca575050505090565b1015611ce4576106c5611ce19392610cf092611c9d565b90565b6106c590611cf192611c9d565b908115611d0c57600160ff1b81145f19831416610d97570590565b634e487b7160e01b5f52601260045260245ffd5b8115611d0c570490565b81810292918115918404141715610d9757565b909160ff811660ff84168181145f14611d5857505050905090565b1015611d6e576106c5611ce1936106ca92611c9d565b6106c5611d7e91611ce194611c9d565b90611d20565b915f8093602095606494604051946323b872dd60e01b865260018060a01b03809216600487015216602485015260448401525af13d15601f3d1160015f511416171615611dcd57565b60405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606490fd5b91818302915f1981850993838086109503948086039514611e945784831115611e7c5790829109815f038216809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b82634e487b715f52156003026011186020526024601cfd5b505090611ce19250611d20565b6040516370a0823160e01b81523060048201529093909290916020846024816001600160a01b0387165afa938415610690575f94611f2f575b5084841015611f2857611eed8486611bd1565b93818511611f0457505090611ce192913091611d84565b6064918691604051926311314cb960e01b8452600484015260248301526044820152fd5b5050505090565b9093506020813d602011611f5b575b81611f4b60209383611a69565b810103126100f65751925f611eda565b3d9150611f3e56fea2646970667358221220bdf8ddcadd5d274f0bb4bef26d6fa68671da194ec2d41960ade5a0e45b5042ed64736f6c634300081900330000000000000000000000006e6a79c033ebee27c80444daca7f9aed8bb06045000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e5000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000010000000000000000000000004dfa7088727a8683da8e56f83b615688dbe93ec7

Deployed Bytecode

0x60806040526004361015610011575f80fd5b5f3560e01c80631644bcf5146108bb5780632ddd62ce146102e857806362218330146102ab578063715018a6146102545780638da5cb5b1461022d578063d87a482a1461013e578063e10d29ee146100fa5763f2fde38b14610071575f80fd5b346100f65760203660031901126100f65761008a611a23565b610092611bef565b6001600160a01b039081169081156100de575f54826001600160601b0360a01b8216175f55167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b604051631e4fbdf760e01b81525f6004820152602490fd5b5f80fd5b346100f6575f3660031901126100f6576040517f000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e56001600160a01b03168152602090f35b346100f6576020806003193601126100f65760043567ffffffffffffffff81116100f657366023820112156100f657806004013561017b81611a8b565b916101896040519384611a69565b81835260248484019260051b820101913683116100f6576024859201905b8382106102165782856101b8611bef565b5f5b8151811015610214576001600160a01b0390816101d78285611ac2565b51165f5260019182855260ff908160405f20541615906101f78487611ac2565b51165f5283865260405f209160ff198354169116179055016101ba565b005b82809161022284611a39565b8152019101906101a7565b346100f6575f3660031901126100f6575f546040516001600160a01b039091168152602090f35b346100f6575f3660031901126100f65761026c611bef565b5f80546001600160a01b0319811682556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b346100f65760203660031901126100f6576001600160a01b036102cc611a23565b165f526001602052602060ff60405f2054166040519015158152f35b346100f65760c03660031901126100f65767ffffffffffffffff6004358181116100f657366023820112156100f65780600401359182116100f6576024810190828101903660248301116100f6576024356001600160a01b038116908190036100f6576044356001600160a01b03811690036100f6576064356001600160a01b03811690036100f65730036108a9577f000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e56001600160a01b031633036108625760209103126100f657803560028110156100f657806103d25760405163a903bc4d60e01b8152600490fd5b6001146103db57005b5f6020604051936103f582601f19601f8401160186611a69565b808552808286019485378401015260c0828051810103126100f6576002905110156100f6576040810151906001600160a01b03821682036100f657608081015160a0820151916001600160a01b03831683036100f65760c0015160405163fbfa77cf60e01b81529091906020816004816001600160a01b0388165afa908115610690575f91610833575b506001600160a01b0390811660443590911603610808578060a435116107e857506104b46064356001600160a01b0316611c46565b92949291159050610750576040516370a0823160e01b81526001600160a01b03868116600483015290939060209085906024908290606435165afa938415610690575f9461071c575b5061050a8560a435611b03565b841061069b5750505f905b816105e1575b505050505b60a43561052957005b6105449060a4359030906001600160a01b0316606435611d84565b60405163095ea7b360e01b81527f000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e56001600160a01b0316600482015260a43560248201526020905f90604490826064355af13d15601f3d1160015f5114161716156105ab57005b60405162461bcd60e51b815260206004820152600e60248201526d1054141493d59157d1905253115160921b6044820152606490fd5b6105fb6020936105f66106459660a435611b03565b611bd1565b604051633e64ce9960e01b8152606480356001600160a01b0390811660048401526024830195909552604482019290925292861690830152909283919082905f9082906084820190565b03926001600160a01b03165af1801561069057610665575b80808061051b565b602090813d8311610689575b61067b8183611a69565b810103126100f6578161065d565b503d610671565b6040513d5f823e3d90fd5b6106d06106ae856105f68860a435611b03565b6106ca6106c56044356001600160a01b0316611c1a565b611bde565b90611d2a565b90801561070a5761070492604435926001600160a01b038916926001906106fa905f198401611d20565b0190151502611ea1565b90610515565b634e487b715f5260126020526024601cfd5b9093506020813d602011610748575b8161073860209383611a69565b810103126100f6575192866104fd565b3d915061072b565b92906107616106ae8360a435611b03565b92801561070a5761079f946020946105fb9261079692604435926001600160a01b038b16926001906106fa905f198401611d20565b9260a435611b03565b03926001600160a01b03165af18015610690576107bd575b50610520565b602090813d83116107e1575b6107d38183611a69565b810103126100f657816107b7565b503d6107c9565b604490604051906308a9e02b60e01b825260a43560048301526024820152fd5b6040516340d2153760e01b81526001600160a01b036044803582166004840152908516602483015290fd5b610855915060203d60201161085b575b61084d8183611a69565b810190611aa3565b8561047f565b503d610843565b60405163e34780db60e01b81523360048201526001600160a01b037f000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e5166024820152604490fd5b6040516312d4921560e31b8152600490fd5b346100f65760a03660031901126100f6576108d4611a23565b6024359067ffffffffffffffff82116100f657366023830112156100f65767ffffffffffffffff8260040135116100f657366024836004013560051b840101116100f6576044356001600160a01b03811681036100f657608435926001600160a01b03841684036100f657335f52600160205260ff60405f20541615611a1257604051634fb3ccc560e01b8152936020856004816001600160a01b0387165afa948515610690575f956119f1575b506040516001600160601b03198560601b166020820152601481526109a681611a4d565b805160209182012060405163313ce56760e01b815291826004816001600160a01b038b165afa918215610690575f926119d0575b505d6109e98260040135611a8b565b906109f76040519283611a69565b6004830135808352610a0890611a8b565b601f190136602084013760048301356001810110610d9757610a306001846004013501611a8b565b95610a3e6040519788611a69565b6004840135600101808852610a5290611a8b565b601f1901366020890137610a698460040135611a8b565b90610a776040519283611a69565b6004850135808352601f1990610a8c90611a8b565b013660208401375f915b856004013583106116de5750506040516370a0823160e01b8152336004820152906020826024816001600160a01b038b165afa918215610690575f926116a8575b50610ae29088611ac2565b525f5b8360040135811061110957506001600160a01b03811615611036576040516370a0823160e01b81523060048201526020816024816001600160a01b038a165afa908115610690575f91611004575b5060405191633e64ce9960e01b835260018060a01b0316600483015260248201525f60448201523360648201526020816084815f60018060a01b0389165af1801561069057610fd9575b505b60405163fbfa77cf60e01b81525f9290916020836004816001600160a01b0389165afa908115610690576004935f92610fb8575b506020610bc86001600160a01b038416611c1a565b604051634fb3ccc560e01b815290979095869182906001600160a01b03165afa938415610690576004946020915f91610f9b575b506040516333cd77e760e11b815295869182906001600160a01b03165afa938415610690575f94610f67575b50915f925b81600401358410610ddf5750506040516370a0823160e01b815233600482015290602090829060249082906001600160a01b03165afa908115610690575f91610dab575b50610c8a610c9191610c83848a611ac2565b5190611b7c565b9187611ac2565b5284515f1990818101908111610d9757610cac5f9188611ac2565b511260011902600118908651908101908111610d9757610cfc94610cf693610ce8610cda610cf0948b611ac2565b51928360ff1d918291611bde565b930118611e09565b90611b94565b90611bb6565b918260643513610d33575f8260405160208101916001600160601b03199060601b16825260148152610d2d81611a4d565b5190205d005b6040516001629772bb60e01b031981526064803560048301526060602483015282519082018190525f949193506084840192602001905b808610610d7f57505082935060448301520390fd5b90926020806001928651815201940195019490610d6a565b634e487b7160e01b5f52601160045260245ffd5b90506020813d602011610dd7575b81610dc660209383611a69565b810103126100f65751610c8a610c71565b3d9150610db9565b9092610dfb610df682866004013560248801611b10565b611b32565b6040516370a0823160e01b815233600482015290966020826024816001600160a01b038c165afa918215610690578b8985948c935f91610f25575b50610e9d84610e8c610cf69686610e86610e7a5f98610e61610eab99610eb99f9c8d610c8391611ac2565b610e6b8c86611ac2565b526001600160a01b0316611c46565b509a9150508992611ac2565b51611cb1565b94610e978a8c611ac2565b51611d3d565b8b8460ff1d80860118611e09565b911260011902600118611b94565b9560405160208101916001600160601b03199060601b16825260148152610edf81611a4d565b51902090600182018211610d9757600282016001830111610d9757600382016002830111610d97575f600383826001955d828582015d82600282015d015d019290610c2d565b9550505050506020823d602011610f5f575b81610f4460209383611a69565b810103126100f657905182919089908c908a90610e9d610e36565b3d9150610f37565b9093506020813d602011610f93575b81610f8360209383611a69565b810103126100f657519288610c28565b3d9150610f76565b610fb29150823d841161085b5761084d8183611a69565b8a610bfc565b610fd291925060203d60201161085b5761084d8183611a69565b9088610bb3565b602090813d8311610ffd575b610fef8183611a69565b810103126100f65785610b7d565b503d610fe5565b90506020813d60201161102e575b8161101f60209383611a69565b810103126100f6575187610b33565b3d9150611012565b506040516370a0823160e01b81523060048201526020816024816001600160a01b0389165afa908115610690575f916110d7575b505f60446020926040519063a9059cbb60e01b8252336004830152602482015282885af13d15601f3d1160015f5114161716610b7f5760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606490fd5b90506020813d602011611101575b816110f260209383611a69565b810103126100f657515f61106a565b3d91506110e5565b602061111d82866004013560248801611b10565b013590604061113482876004013560248901611b10565b01356111408286611ac2565b519060405193600160208601523360408601526060850152608084015260018060a01b03871660a084015260c083015260c082528160e081011067ffffffffffffffff60e0840111176116625760e082016040526111b36111a982876004013560248901611b10565b60a0810190611b46565b15159050611509576111d0610df682876004013560248901611b10565b60c0838051810103126100f6576002602084015110156100f65760408301516001600160a01b03811681036100f65760a0840151936001600160a01b03851685036100f65760c0015160405163fbfa77cf60e01b81529094906020816004816001600160a01b0386165afa908115610690575f916114ea575b506001600160a01b03908116908b16036114bf576001600160a01b038316948a9061127387611c46565b9392949190505f146113ec57506040516370a0823160e01b81526001600160a01b038616600482015297602090899060249082905afa978815610690575f986113b8575b508288106113675750505f905b816112da575b5050505050600191505b01610ae5565b6112e960209596975f92611bd1565b604051633e64ce9960e01b81526001600160a01b0397881660048201526024810193909352604483015292851660648201529384926084928492165af180156106905761133c575b8080808085946112ca565b602090813d8311611360575b6113528183611a69565b810103126100f65787611331565b503d611348565b61138a8d6106ca6106c561137b8c88611bd1565b926001600160a01b0316611c1a565b90801561070a576113b2928e926001600160a01b038816926001906106fa905f198401611d20565b906112c4565b9097506020813d6020116113e4575b816113d460209383611a69565b810103126100f65751968e6112b7565b3d91506113c7565b6114129192969798506106c561140c9160018060a09997991b0316611c1a565b85611d2a565b94811561070a576020955f9261143f928f926001600160a01b038716926001906106fa905f198401611d20565b604051633e64ce9960e01b81526001600160a01b039788166004820152602481019190915260448101949094529085166064840152919384926084928492165af1801561069057611494575b506001906112d4565b602090813d83116114b8575b6114aa8183611a69565b810103126100f6578761148b565b503d6114a0565b6040516340d2153760e01b81526001600160a01b038b81166004830152919091166024820152604490fd5b611503915060203d60201161085b5761084d8183611a69565b8c611249565b61151e610df682876004013560248901611b10565b916115346111a983886004013560248a01611b10565b909160c061154a858a6004013560248c01611b10565b0135917f000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e56001600160a01b03163b156100f657604051633ea1420760e11b81526001600160a01b03808d166004830152909616602487015260c0604487015260c486018190529192859260e484019291905f905b80821061167657505050602091825f9585936003198585030160648601528051928391828652018685015e828201850187905230608485015260a4840152601f01601f191601030181837f000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e56001600160a01b03165af1801561069057611648575b600191506112d4565b67ffffffffffffffff82116116625760019160405261163f565b634e487b7160e01b5f52604160045260245ffd5b91959450919260019060209081906001600160a01b036116958a611a39565b16815201960192018794959392916115be565b9091506020813d6020116116d6575b816116c460209383611a69565b810103126100f6575190610ae2610ad7565b3d91506116b7565b90915f5b81811061197757506116ff610df682886004013560248a01611b10565b604051634104b9ed60e11b81526001600160a01b039182166004820152906020908290602490829088165afa908115610690575f91611945575b506117448287611ac2565b5261174f8186611ac2565b51156119335761176a610df682886004013560248a01611b10565b90606061177f82896004013560248b01611b10565b0135916080611796838a6004013560248c01611b10565b01359081151582036100f65760e06117b6848b6004013560248d01611b10565b01359160405160208101906001600160601b03198460601b168252601481526117de81611a4d565b51902090600182018211610d9757600282016001830111610d9757600382016002830111610d975760405163313ce56760e01b815292602090849060049082906001600160a01b03165afa908115610690576024966003945f93611902575b50835d600183015d600282015d015d60206001600160a01b0361186a610df68460048c0135878d01611b10565b16604051938480926370a0823160e01b82523360048301525afa8015610690575f906118cf575b6001925061189f828c611ac2565b52818060a01b036118bb610df6838a6004013560248c01611b10565b166118c68285611ac2565b52019190610a96565b506020823d6020116118fa575b816118e960209383611a69565b810103126100f65760019151611891565b3d91506118dc565b61192591935060203d60201161192c575b61191d8183611a69565b810190611aea565b915f61183d565b503d611913565b60405163121d85b560e11b8152600490fd5b90506020813d60201161196f575b8161196060209383611a69565b810103126100f657518a611739565b3d9150611953565b6001600160a01b03611994610df68460048b013560248c01611b10565b166001600160a01b036119a78386611ac2565b511681146119b857506001016116e2565b6024906040519063096449b160e01b82526004820152fd5b6119ea91925060203d60201161192c5761191d8183611a69565b90876109da565b611a0b91955060203d60201161085b5761084d8183611a69565b9385610982565b637e94ab9360e11b60805260046080fd5b600435906001600160a01b03821682036100f657565b35906001600160a01b03821682036100f657565b6040810190811067ffffffffffffffff82111761166257604052565b90601f8019910116810190811067ffffffffffffffff82111761166257604052565b67ffffffffffffffff81116116625760051b60200190565b908160209103126100f657516001600160a01b03811681036100f65790565b8051821015611ad65760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b908160209103126100f6575160ff811681036100f65790565b91908201809211610d9757565b9190811015611ad65760051b8101359060fe19813603018212156100f6570190565b356001600160a01b03811681036100f65790565b903590601e19813603018212156100f6570180359067ffffffffffffffff82116100f657602001918160051b360383136100f657565b81810392915f138015828513169184121617610d9757565b81810292915f8212600160ff1b821416610d97578184051490151715610d9757565b9190915f8382019384129112908015821691151617610d9757565b91908203918211610d9757565b60ff16604d8111610d9757600a0a90565b5f546001600160a01b03163303611c0257565b60405163118cdaa760e01b8152336004820152602490fd5b60405160208101916001600160601b03199060601b16825260148152611c3f81611a4d565b5190205c90565b60405160208101916001600160601b03199060601b16825260148152611c6b81611a4d565b51902060018101808211610d97576002820192838211610d97576003830192838511610d97575c93915c92915c915c90565b9060ff8091169116039060ff8211610d9757565b9160ff811660ff83168181145f14611cca575050505090565b1015611ce4576106c5611ce19392610cf092611c9d565b90565b6106c590611cf192611c9d565b908115611d0c57600160ff1b81145f19831416610d97570590565b634e487b7160e01b5f52601260045260245ffd5b8115611d0c570490565b81810292918115918404141715610d9757565b909160ff811660ff84168181145f14611d5857505050905090565b1015611d6e576106c5611ce1936106ca92611c9d565b6106c5611d7e91611ce194611c9d565b90611d20565b915f8093602095606494604051946323b872dd60e01b865260018060a01b03809216600487015216602485015260448401525af13d15601f3d1160015f511416171615611dcd57565b60405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606490fd5b91818302915f1981850993838086109503948086039514611e945784831115611e7c5790829109815f038216809204600280826003021880830282030280830282030280830282030280830282030280830282030280920290030293600183805f03040190848311900302920304170290565b82634e487b715f52156003026011186020526024601cfd5b505090611ce19250611d20565b6040516370a0823160e01b81523060048201529093909290916020846024816001600160a01b0387165afa938415610690575f94611f2f575b5084841015611f2857611eed8486611bd1565b93818511611f0457505090611ce192913091611d84565b6064918691604051926311314cb960e01b8452600484015260248301526044820152fd5b5050505090565b9093506020813d602011611f5b575b81611f4b60209383611a69565b810103126100f65751925f611eda565b3d9150611f3e56fea2646970667358221220bdf8ddcadd5d274f0bb4bef26d6fa68671da194ec2d41960ade5a0e45b5042ed64736f6c63430008190033

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

0000000000000000000000006e6a79c033ebee27c80444daca7f9aed8bb06045000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e5000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000010000000000000000000000004dfa7088727a8683da8e56f83b615688dbe93ec7

-----Decoded View---------------
Arg [0] : _owner (address): 0x6E6a79C033ebEE27C80444DaCA7F9aed8BB06045
Arg [1] : _queue (address): 0x228C44Bb4885C6633F4b6C83f14622f37D5112E5
Arg [2] : approvedSolvers (address[]): 0x4dfa7088727a8683DA8E56F83B615688dbE93ec7

-----Encoded View---------------
5 Constructor Arguments found :
Arg [0] : 0000000000000000000000006e6a79c033ebee27c80444daca7f9aed8bb06045
Arg [1] : 000000000000000000000000228c44bb4885c6633f4b6c83f14622f37d5112e5
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000060
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000001
Arg [4] : 0000000000000000000000004dfa7088727a8683da8e56f83b615688dbe93ec7


Block Transaction Gas Used Reward
view all blocks ##produced##

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
[ Download: CSV Export  ]

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