ETH Price: $2,038.97 (+3.96%)
 

Overview

ETH Balance

0 ETH

Eth 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 found.

Latest 1 internal transaction

Advanced mode:
Parent Transaction Hash Method Block
From
To
0x60806040235486322025-10-10 16:50:11143 days ago1760115011  Contract Creation0 ETH
Loading...
Loading
Loading...
Loading
Cross-Chain Transactions

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

Similar Match Source Code
This contract matches the deployed Bytecode of the Source Code for Contract 0x519b944e...Fbb8580d1
The constructor portion of the code might be different and could alter the actual behaviour of the contract

Contract Name:
MellowWithdrawalSubcompressor

Compiler Version
v0.8.23+commit.f704f362

Optimization Enabled:
Yes with 1000 runs

Other Settings:
shanghai EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundaiton, 2025.
pragma solidity ^0.8.23;

import {ICreditAccountV3} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditAccountV3.sol";
import {ICreditManagerV3} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditManagerV3.sol";

import {IWithdrawalSubcompressor} from "../../../interfaces/IWithdrawalSubcompressor.sol";
import {
    WithdrawalOutput,
    WithdrawableAsset,
    RequestableWithdrawal,
    ClaimableWithdrawal,
    PendingWithdrawal,
    WithdrawalLib
} from "../../../types/WithdrawalInfo.sol";
import {MultiCall} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditFacadeV3.sol";

import {MellowWithdrawalPhantomToken} from
    "@gearbox-protocol/integrations-v3/contracts/helpers/mellow/MellowWithdrawalPhantomToken.sol";
import {
    IMellowMultiVault,
    IMellowWithdrawalQueue,
    IEigenLayerWithdrawalQueue,
    Subvault,
    MellowProtocol
} from "@gearbox-protocol/integrations-v3/contracts/integrations/mellow/IMellowMultiVault.sol";
import {IMellowClaimerAdapter} from
    "@gearbox-protocol/integrations-v3/contracts/interfaces/mellow/IMellowClaimerAdapter.sol";
import {IMellow4626VaultAdapter} from
    "@gearbox-protocol/integrations-v3/contracts/interfaces/mellow/IMellow4626VaultAdapter.sol";
import {IERC4626Adapter} from "@gearbox-protocol/integrations-v3/contracts/interfaces/erc4626/IERC4626Adapter.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";

struct EpochData {
    bool isClaimed;
    uint256 sharesToClaim;
    uint256 claimableAssets;
}

struct EigenLayerWithdrawal {
    address staker;
    address delegatedTo;
    address withdrawer;
    uint256 nonce;
    uint32 startBlock;
    address[] strategies;
    uint256[] scaledShares;
}

interface ISymbioticSubvault {
    function nextEpochStart() external view returns (uint256);
    function epochDuration() external view returns (uint256);
    function withdrawalsOf(uint256 epoch, address withdrawalQueue) external view returns (uint256);
}

interface IEigenLayerDelegation {
    function minWithdrawalDelayBlocks() external view returns (uint256);
}

interface IEigenLayerWithdrawalQueueExt is IEigenLayerWithdrawalQueue {
    function delegation() external view returns (address);

    function latestWithdrawableBlock() external view returns (uint256);

    function convertScaledSharesToShares(
        EigenLayerWithdrawal memory withdrawal,
        uint256 scaledShares,
        uint256 totalScaledShares
    ) external view returns (uint256);

    function getWithdrawalRequest(uint256 index, address account)
        external
        view
        returns (
            EigenLayerWithdrawal memory data,
            bool isClaimed,
            uint256 assets,
            uint256 shares,
            uint256 accountShares
        );

    function isolatedVault() external view returns (address);
    function strategy() external view returns (address);
}

interface IEigenLayerIsolatedVault {
    function sharesToUnderlyingView(address strategy, uint256 shares) external view returns (uint256);
}

interface ISymbioticWithdrawalQueue {
    function getCurrentEpoch() external view returns (uint256);
    function getAccountData(address account)
        external
        view
        returns (uint256 sharesToClaimPrev, uint256 sharesToClaim, uint256 claimableAssets, uint256 claimEpoch);
    function getEpochData(uint256 epoch) external view returns (EpochData memory);
}

interface IMellowMultiVaultExt is IMellowMultiVault {
    function withdrawalStrategy() external view returns (address);
}

struct MellowWithdrawalAmounts {
    uint256 subvaultIndex;
    uint256 claimable;
    uint256 pending;
    uint256 staked;
}

interface IMellowWithdrawalStrategy {
    function calculateWithdrawalAmounts(address multiVault, uint256 amount)
        external
        view
        returns (MellowWithdrawalAmounts[] memory amounts);
}

contract MellowWithdrawalSubcompressor is IWithdrawalSubcompressor {
    using WithdrawalLib for PendingWithdrawal[];

    uint256 public constant version = 3_10;
    bytes32 public constant contractType = "GLOBAL::MELLOW_WD_SC";

    function getWithdrawableAssets(address, address token) external view returns (WithdrawableAsset[] memory) {
        address multiVault = MellowWithdrawalPhantomToken(token).multiVault();
        address asset = IERC4626(multiVault).asset();

        WithdrawableAsset[] memory withdrawableAssets = new WithdrawableAsset[](1);
        withdrawableAssets[0] = WithdrawableAsset(multiVault, token, asset, _getWithdrawalLength(multiVault));

        return withdrawableAssets;
    }

    function getCurrentWithdrawals(address creditAccount, address token)
        external
        view
        returns (ClaimableWithdrawal[] memory, PendingWithdrawal[] memory)
    {
        address multiVault = MellowWithdrawalPhantomToken(token).multiVault();

        ClaimableWithdrawal[] memory claimableWithdrawals = new ClaimableWithdrawal[](1);
        claimableWithdrawals[0] = _getClaimableWithdrawal(creditAccount, token, multiVault);

        if (claimableWithdrawals[0].outputs.length == 0 || claimableWithdrawals[0].outputs[0].amount == 0) {
            claimableWithdrawals = new ClaimableWithdrawal[](0);
        }

        PendingWithdrawal[] memory pendingWithdrawals = _getPendingWithdrawals(creditAccount, multiVault);

        for (uint256 i = 0; i < pendingWithdrawals.length; ++i) {
            pendingWithdrawals[i].withdrawalPhantomToken = token;
        }

        return (claimableWithdrawals, pendingWithdrawals);
    }

    function getWithdrawalRequestResult(address creditAccount, address token, address withdrawalToken, uint256 amount)
        external
        view
        returns (RequestableWithdrawal memory requestableWithdrawal)
    {
        requestableWithdrawal.token = token;
        requestableWithdrawal.amountIn = amount;

        uint256 assets = IERC4626(token).convertToAssets(amount);

        address withdrawalStrategy = IMellowMultiVaultExt(token).withdrawalStrategy();

        MellowWithdrawalAmounts[] memory amounts =
            IMellowWithdrawalStrategy(withdrawalStrategy).calculateWithdrawalAmounts(token, assets);

        uint256 liquid = assets;

        for (uint256 i = 0; i < amounts.length; ++i) {
            Subvault memory subvault = IMellowMultiVault(token).subvaultAt(amounts[i].subvaultIndex);

            if (subvault.protocol == MellowProtocol.SYMBIOTIC) {
                liquid -= amounts[i].staked + amounts[i].pending;
            } else if (subvault.protocol == MellowProtocol.EIGEN_LAYER) {
                liquid -= amounts[i].staked + amounts[i].pending;
            }
        }

        if (liquid < assets) {
            requestableWithdrawal.outputs = new WithdrawalOutput[](2);
            requestableWithdrawal.outputs[0] = WithdrawalOutput(IERC4626(token).asset(), false, liquid);
            requestableWithdrawal.outputs[1] = WithdrawalOutput(withdrawalToken, true, assets - liquid);
        } else {
            requestableWithdrawal.outputs = new WithdrawalOutput[](1);
            requestableWithdrawal.outputs[0] = WithdrawalOutput(IERC4626(token).asset(), false, assets);
        }

        requestableWithdrawal.requestCalls = new MultiCall[](2);

        address creditManager = ICreditAccountV3(creditAccount).creditManager();

        address vaultAdapter = ICreditManagerV3(creditManager).contractToAdapter(token);

        requestableWithdrawal.requestCalls[0] = MultiCall({
            target: vaultAdapter,
            callData: abi.encodeCall(IERC4626Adapter.redeem, (amount, address(0), address(0)))
        });

        address claimer = MellowWithdrawalPhantomToken(withdrawalToken).claimer();

        address claimerAdapter = ICreditManagerV3(creditManager).contractToAdapter(claimer);

        (uint256[] memory subvaultIndices, uint256[][] memory withdrawalIndices) =
            IMellowClaimerAdapter(claimerAdapter).getMultiVaultSubvaultIndices(token);

        requestableWithdrawal.requestCalls[1] = MultiCall({
            target: claimerAdapter,
            callData: abi.encodeCall(IMellowClaimerAdapter.multiAccept, (token, subvaultIndices, withdrawalIndices))
        });

        requestableWithdrawal.claimableAt = block.timestamp + _getWithdrawalLength(token);

        return requestableWithdrawal;
    }

    function _getPendingWithdrawals(address creditAccount, address multiVault)
        internal
        view
        returns (PendingWithdrawal[] memory pendingWithdrawals)
    {
        address asset = IERC4626(multiVault).asset();

        uint256 nSubvaults = IMellowMultiVault(multiVault).subvaultsCount();

        for (uint256 i = 0; i < nSubvaults; ++i) {
            Subvault memory subvault = IMellowMultiVault(multiVault).subvaultAt(i);

            if (subvault.withdrawalQueue == address(0)) continue;

            uint256 pendingAssets = IMellowWithdrawalQueue(subvault.withdrawalQueue).pendingAssetsOf(creditAccount);

            if (pendingAssets > 0) {
                pendingWithdrawals = pendingWithdrawals.concat(
                    _getSubvaultPendingWithdrawals(
                        creditAccount, multiVault, subvault.protocol, subvault.vault, subvault.withdrawalQueue, asset
                    )
                );
            }
        }

        return pendingWithdrawals;
    }

    function _getSubvaultPendingWithdrawals(
        address creditAccount,
        address multiVault,
        MellowProtocol protocol,
        address subvault,
        address withdrawalQueue,
        address asset
    ) internal view returns (PendingWithdrawal[] memory pendingWithdrawals) {
        if (protocol == MellowProtocol.SYMBIOTIC) {
            (uint256 sharesToClaimPrev, uint256 sharesToClaim,, uint256 claimEpoch) =
                ISymbioticWithdrawalQueue(withdrawalQueue).getAccountData(creditAccount);

            uint256 currentEpoch = ISymbioticWithdrawalQueue(withdrawalQueue).getCurrentEpoch();

            if (claimEpoch < currentEpoch) {
                return pendingWithdrawals;
            } else if (claimEpoch == currentEpoch) {
                pendingWithdrawals = new PendingWithdrawal[](1);
                pendingWithdrawals[0].token = multiVault;
                pendingWithdrawals[0].expectedOutputs = new WithdrawalOutput[](1);

                uint256 expectedAmount =
                    _getSymbioticExpectedWithdrawal(subvault, withdrawalQueue, sharesToClaim, currentEpoch);

                pendingWithdrawals[0].expectedOutputs[0] = WithdrawalOutput(asset, false, expectedAmount);
                pendingWithdrawals[0].claimableAt = ISymbioticSubvault(subvault).nextEpochStart();
            } else if (claimEpoch == currentEpoch + 1) {
                pendingWithdrawals = new PendingWithdrawal[](2);

                pendingWithdrawals[0].token = multiVault;
                pendingWithdrawals[0].expectedOutputs = new WithdrawalOutput[](1);

                uint256 expectedAmount =
                    _getSymbioticExpectedWithdrawal(subvault, withdrawalQueue, sharesToClaim, currentEpoch + 1);

                pendingWithdrawals[0].expectedOutputs[0] = WithdrawalOutput(asset, false, expectedAmount);
                pendingWithdrawals[0].claimableAt =
                    ISymbioticSubvault(subvault).nextEpochStart() + ISymbioticSubvault(subvault).epochDuration();

                if (sharesToClaimPrev > 0) {
                    pendingWithdrawals[1].token = multiVault;
                    pendingWithdrawals[1].expectedOutputs = new WithdrawalOutput[](1);

                    expectedAmount =
                        _getSymbioticExpectedWithdrawal(subvault, withdrawalQueue, sharesToClaimPrev, currentEpoch);

                    pendingWithdrawals[1].expectedOutputs[0] = WithdrawalOutput(asset, false, expectedAmount);
                    pendingWithdrawals[1].claimableAt = ISymbioticSubvault(subvault).nextEpochStart();
                }
            }
        }

        if (protocol == MellowProtocol.EIGEN_LAYER) {
            (, uint256[] memory withdrawals,) =
                IEigenLayerWithdrawalQueueExt(withdrawalQueue).getAccountData(creditAccount, type(uint256).max, 0, 0, 0);

            uint256 latestWithdrawableBlock = IEigenLayerWithdrawalQueueExt(withdrawalQueue).latestWithdrawableBlock();

            pendingWithdrawals = new PendingWithdrawal[](withdrawals.length);

            for (uint256 i = 0; i < withdrawals.length; ++i) {
                (EigenLayerWithdrawal memory withdrawal,,, uint256 shares, uint256 accountShares) =
                    IEigenLayerWithdrawalQueueExt(withdrawalQueue).getWithdrawalRequest(withdrawals[i], creditAccount);

                if (withdrawal.startBlock > latestWithdrawableBlock && accountShares > 0) {
                    pendingWithdrawals[i].token = multiVault;
                    pendingWithdrawals[i].expectedOutputs = new WithdrawalOutput[](1);

                    uint256 unscaledShares = IEigenLayerWithdrawalQueueExt(withdrawalQueue).convertScaledSharesToShares(
                        withdrawal, accountShares, shares
                    );

                    uint256 expectedAmount = IEigenLayerIsolatedVault(
                        IEigenLayerWithdrawalQueueExt(withdrawalQueue).isolatedVault()
                    ).sharesToUnderlyingView(IEigenLayerWithdrawalQueueExt(withdrawalQueue).strategy(), unscaledShares);

                    pendingWithdrawals[i].expectedOutputs[0] = WithdrawalOutput(asset, false, expectedAmount);
                    pendingWithdrawals[i].claimableAt =
                        block.timestamp + 12 * (withdrawal.startBlock - latestWithdrawableBlock);
                }
            }
        }
    }

    function _getClaimableWithdrawal(address creditAccount, address withdrawalToken, address multiVault)
        internal
        view
        returns (ClaimableWithdrawal memory withdrawal)
    {
        address asset = IERC4626(multiVault).asset();

        withdrawal.token = multiVault;
        withdrawal.withdrawalPhantomToken = withdrawalToken;
        withdrawal.outputs = new WithdrawalOutput[](1);
        withdrawal.outputs[0] = WithdrawalOutput(asset, false, 0);

        uint256 nSubvaults = IMellowMultiVault(multiVault).subvaultsCount();

        for (uint256 i = 0; i < nSubvaults; ++i) {
            Subvault memory subvault = IMellowMultiVault(multiVault).subvaultAt(i);

            if (subvault.withdrawalQueue == address(0)) continue;

            uint256 claimableAssets = IMellowWithdrawalQueue(subvault.withdrawalQueue).claimableAssetsOf(creditAccount);

            withdrawal.outputs[0].amount += claimableAssets;
        }

        if (withdrawal.outputs[0].amount == 0) {
            return withdrawal;
        }

        withdrawal.withdrawalTokenSpent = withdrawal.outputs[0].amount;

        withdrawal.claimCalls = new MultiCall[](1);

        address claimerAdapter;

        {
            address claimer = MellowWithdrawalPhantomToken(withdrawalToken).claimer();
            address creditManager = ICreditAccountV3(creditAccount).creditManager();

            claimerAdapter = ICreditManagerV3(creditManager).contractToAdapter(claimer);
        }

        (uint256[] memory subvaultIndices, uint256[][] memory withdrawalIndices) =
            IMellowClaimerAdapter(claimerAdapter).getUserSubvaultIndices(multiVault, creditAccount);

        withdrawal.claimCalls[0] = MultiCall(
            address(claimerAdapter),
            abi.encodeWithSelector(
                IMellowClaimerAdapter.multiAcceptAndClaim.selector,
                multiVault,
                subvaultIndices,
                withdrawalIndices,
                creditAccount,
                withdrawal.outputs[0].amount
            )
        );

        return withdrawal;
    }

    function _getWithdrawalLength(address multiVault) internal view returns (uint256) {
        uint256 withdrawalLength = 0;

        uint256 nSubvaults = IMellowMultiVault(multiVault).subvaultsCount();

        for (uint256 i = 0; i < nSubvaults; ++i) {
            Subvault memory subvault = IMellowMultiVault(multiVault).subvaultAt(i);

            if (subvault.protocol == MellowProtocol.SYMBIOTIC) {
                uint256 symbioticWithdrawalLength = ISymbioticSubvault(subvault.vault).nextEpochStart()
                    + ISymbioticSubvault(subvault.vault).epochDuration() - block.timestamp;
                if (symbioticWithdrawalLength > withdrawalLength) {
                    withdrawalLength = symbioticWithdrawalLength;
                }
            }

            if (subvault.protocol == MellowProtocol.EIGEN_LAYER) {
                uint256 eigenLayerWithdrawalLength = IEigenLayerDelegation(
                    IEigenLayerWithdrawalQueueExt(subvault.withdrawalQueue).delegation()
                ).minWithdrawalDelayBlocks() * 12;
                if (eigenLayerWithdrawalLength > withdrawalLength) {
                    withdrawalLength = eigenLayerWithdrawalLength;
                }
            }
        }

        return withdrawalLength;
    }

    function _getSymbioticExpectedWithdrawal(
        address subvault,
        address withdrawalQueue,
        uint256 sharesToClaim,
        uint256 epoch
    ) internal view returns (uint256) {
        EpochData memory epochData = ISymbioticWithdrawalQueue(withdrawalQueue).getEpochData(epoch);

        uint256 totalWithdrawals = ISymbioticSubvault(subvault).withdrawalsOf(epoch, withdrawalQueue);

        return sharesToClaim * totalWithdrawals / epochData.sharesToClaim;
    }
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IVersion} from "./base/IVersion.sol";

/// @title Credit account V3 interface
interface ICreditAccountV3 is IVersion {
    function factory() external view returns (address);

    function creditManager() external view returns (address);

    function safeTransfer(address token, address to, uint256 amount) external;

    function execute(address target, bytes calldata data) external returns (bytes memory result);

    function rescue(address target, bytes calldata data) external;
}

File 3 of 37 : ICreditManagerV3.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IVersion} from "./base/IVersion.sol";

/// @notice Debt management type
///         - `INCREASE_DEBT` borrows additional funds from the pool, updates account's debt and cumulative interest index
///         - `DECREASE_DEBT` repays debt components (quota interest and fees -> base interest and fees -> debt principal)
///           and updates all corresponding state variables (base interest index, quota interest and fees, debt).
///           When repaying all the debt, ensures that account has no enabled quotas.
enum ManageDebtAction {
    INCREASE_DEBT,
    DECREASE_DEBT
}

/// @notice Collateral/debt calculation mode
///         - `GENERIC_PARAMS` returns generic data like account debt and cumulative indexes
///         - `DEBT_ONLY` is same as `GENERIC_PARAMS` but includes more detailed debt info, like accrued base/quota
///           interest and fees
///         - `FULL_COLLATERAL_CHECK_LAZY` checks whether account is sufficiently collateralized in a lazy fashion,
///           i.e. it stops iterating over collateral tokens once TWV reaches the desired target.
///           Since it may return underestimated TWV, it's only available for internal use.
///         - `DEBT_COLLATERAL` is same as `DEBT_ONLY` but also returns total value and total LT-weighted value of
///           account's tokens, this mode is used during account liquidation
///         - `DEBT_COLLATERAL_SAFE_PRICES` is same as `DEBT_COLLATERAL` but uses safe prices from price oracle
enum CollateralCalcTask {
    GENERIC_PARAMS,
    DEBT_ONLY,
    FULL_COLLATERAL_CHECK_LAZY,
    DEBT_COLLATERAL,
    DEBT_COLLATERAL_SAFE_PRICES
}

struct CreditAccountInfo {
    uint256 debt;
    uint256 cumulativeIndexLastUpdate;
    uint128 cumulativeQuotaInterest;
    uint128 quotaFees;
    uint256 enabledTokensMask;
    uint16 flags;
    uint64 lastDebtUpdate;
    address borrower;
}

struct CollateralDebtData {
    uint256 debt;
    uint256 cumulativeIndexNow;
    uint256 cumulativeIndexLastUpdate;
    uint128 cumulativeQuotaInterest;
    uint256 accruedInterest;
    uint256 accruedFees;
    uint256 totalDebtUSD;
    uint256 totalValue;
    uint256 totalValueUSD;
    uint256 twvUSD;
    uint256 enabledTokensMask;
    uint256 quotedTokensMask;
    address[] quotedTokens;
    address _poolQuotaKeeper;
}

struct CollateralTokenData {
    address token;
    uint16 ltInitial;
    uint16 ltFinal;
    uint40 timestampRampStart;
    uint24 rampDuration;
}

interface ICreditManagerV3Events {
    /// @notice Emitted when new credit configurator is set
    event SetCreditConfigurator(address indexed newConfigurator);
}

/// @title Credit manager V3 interface
interface ICreditManagerV3 is IVersion, ICreditManagerV3Events {
    function pool() external view returns (address);

    function underlying() external view returns (address);

    function creditFacade() external view returns (address);

    function creditConfigurator() external view returns (address);

    function accountFactory() external view returns (address);

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

    // ------------------ //
    // ACCOUNT MANAGEMENT //
    // ------------------ //

    function openCreditAccount(address onBehalfOf) external returns (address);

    function closeCreditAccount(address creditAccount) external;

    function liquidateCreditAccount(
        address creditAccount,
        CollateralDebtData calldata collateralDebtData,
        address to,
        bool isExpired
    ) external returns (uint256 remainingFunds, uint256 loss);

    function manageDebt(address creditAccount, uint256 amount, uint256 enabledTokensMask, ManageDebtAction action)
        external
        returns (uint256 newDebt, uint256, uint256);

    function addCollateral(address payer, address creditAccount, address token, uint256 amount)
        external
        returns (uint256);

    function withdrawCollateral(address creditAccount, address token, uint256 amount, address to)
        external
        returns (uint256);

    function externalCall(address creditAccount, address target, bytes calldata callData)
        external
        returns (bytes memory result);

    function approveToken(address creditAccount, address token, address spender, uint256 amount) external;

    // -------- //
    // ADAPTERS //
    // -------- //

    function adapterToContract(address adapter) external view returns (address targetContract);

    function contractToAdapter(address targetContract) external view returns (address adapter);

    function execute(bytes calldata data) external returns (bytes memory result);

    function approveCreditAccount(address token, uint256 amount) external;

    function setActiveCreditAccount(address creditAccount) external;

    function getActiveCreditAccountOrRevert() external view returns (address creditAccount);

    // ----------------- //
    // COLLATERAL CHECKS //
    // ----------------- //

    function priceOracle() external view returns (address);

    function fullCollateralCheck(
        address creditAccount,
        uint256 enabledTokensMask,
        uint256[] calldata collateralHints,
        uint16 minHealthFactor,
        bool useSafePrices
    ) external returns (uint256);

    function isLiquidatable(address creditAccount, uint16 minHealthFactor) external view returns (bool);

    function calcDebtAndCollateral(address creditAccount, CollateralCalcTask task)
        external
        view
        returns (CollateralDebtData memory cdd);

    // ------ //
    // QUOTAS //
    // ------ //

    function poolQuotaKeeper() external view returns (address);

    function quotedTokensMask() external view returns (uint256);

    function updateQuota(address creditAccount, address token, int96 quotaChange, uint96 minQuota, uint96 maxQuota)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    // --------------------- //
    // CREDIT MANAGER PARAMS //
    // --------------------- //

    function maxEnabledTokens() external view returns (uint8);

    function fees()
        external
        view
        returns (
            uint16 feeInterest,
            uint16 feeLiquidation,
            uint16 liquidationDiscount,
            uint16 feeLiquidationExpired,
            uint16 liquidationDiscountExpired
        );

    function collateralTokensCount() external view returns (uint8);

    function getTokenMaskOrRevert(address token) external view returns (uint256 tokenMask);

    function getTokenByMask(uint256 tokenMask) external view returns (address token);

    function liquidationThresholds(address token) external view returns (uint16 lt);

    function ltParams(address token)
        external
        view
        returns (uint16 ltInitial, uint16 ltFinal, uint40 timestampRampStart, uint24 rampDuration);

    function collateralTokenByMask(uint256 tokenMask)
        external
        view
        returns (address token, uint16 liquidationThreshold);

    // ------------ //
    // ACCOUNT INFO //
    // ------------ //

    function creditAccountInfo(address creditAccount)
        external
        view
        returns (
            uint256 debt,
            uint256 cumulativeIndexLastUpdate,
            uint128 cumulativeQuotaInterest,
            uint128 quotaFees,
            uint256 enabledTokensMask,
            uint16 flags,
            uint64 lastDebtUpdate,
            address borrower
        );

    function getBorrowerOrRevert(address creditAccount) external view returns (address borrower);

    function flagsOf(address creditAccount) external view returns (uint16);

    function setFlagFor(address creditAccount, uint16 flag, bool value) external;

    function enabledTokensMaskOf(address creditAccount) external view returns (uint256);

    function creditAccounts() external view returns (address[] memory);

    function creditAccounts(uint256 offset, uint256 limit) external view returns (address[] memory);

    function creditAccountsLen() external view returns (uint256);

    // ------------- //
    // CONFIGURATION //
    // ------------- //

    function addToken(address token) external;

    function setCollateralTokenData(
        address token,
        uint16 ltInitial,
        uint16 ltFinal,
        uint40 timestampRampStart,
        uint24 rampDuration
    ) external;

    function setFees(
        uint16 feeInterest,
        uint16 feeLiquidation,
        uint16 liquidationDiscount,
        uint16 feeLiquidationExpired,
        uint16 liquidationDiscountExpired
    ) external;

    function setContractAllowance(address adapter, address targetContract) external;

    function setCreditFacade(address creditFacade) external;

    function setPriceOracle(address priceOracle) external;

    function setCreditConfigurator(address creditConfigurator) external;
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2025.
pragma solidity ^0.8.23;

import {IVersion} from "@gearbox-protocol/core-v3/contracts/interfaces/base/IVersion.sol";
import {
    WithdrawableAsset,
    RequestableWithdrawal,
    ClaimableWithdrawal,
    PendingWithdrawal
} from "../types/WithdrawalInfo.sol";

interface IWithdrawalSubcompressor is IVersion {
    function getWithdrawableAssets(address creditManager, address token)
        external
        view
        returns (WithdrawableAsset[] memory);

    function getCurrentWithdrawals(address creditAccount, address token)
        external
        view
        returns (ClaimableWithdrawal[] memory, PendingWithdrawal[] memory);

    function getWithdrawalRequestResult(address creditAccount, address token, address withdrawalToken, uint256 amount)
        external
        view
        returns (RequestableWithdrawal memory);
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2025.
pragma solidity ^0.8.23;

import {MultiCall} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditFacadeV3.sol";

struct WithdrawalOutput {
    address token;
    bool isDelayed;
    uint256 amount;
}

struct WithdrawableAsset {
    address token;
    address withdrawalPhantomToken;
    address underlying;
    uint256 withdrawalLength;
}

struct RequestableWithdrawal {
    address token;
    uint256 amountIn;
    WithdrawalOutput[] outputs;
    MultiCall[] requestCalls;
    uint256 claimableAt;
}

struct ClaimableWithdrawal {
    address token;
    address withdrawalPhantomToken;
    uint256 withdrawalTokenSpent;
    WithdrawalOutput[] outputs;
    MultiCall[] claimCalls;
}

struct PendingWithdrawal {
    address token;
    address withdrawalPhantomToken;
    WithdrawalOutput[] expectedOutputs;
    uint256 claimableAt;
}

library WithdrawalLib {
    function push(WithdrawableAsset[] memory w, WithdrawableAsset memory asset)
        internal
        pure
        returns (WithdrawableAsset[] memory)
    {
        WithdrawableAsset[] memory newWithdrawableAssets = new WithdrawableAsset[](w.length + 1);
        for (uint256 i = 0; i < w.length; i++) {
            newWithdrawableAssets[i] = w[i];
        }
        newWithdrawableAssets[w.length] = asset;
        return newWithdrawableAssets;
    }

    function concat(WithdrawableAsset[] memory w0, WithdrawableAsset[] memory w1)
        internal
        pure
        returns (WithdrawableAsset[] memory)
    {
        WithdrawableAsset[] memory newWithdrawableAssets = new WithdrawableAsset[](w0.length + w1.length);
        for (uint256 i = 0; i < w0.length; i++) {
            newWithdrawableAssets[i] = w0[i];
        }
        for (uint256 i = 0; i < w1.length; i++) {
            newWithdrawableAssets[w0.length + i] = w1[i];
        }
        return newWithdrawableAssets;
    }

    function concat(RequestableWithdrawal[] memory w0, RequestableWithdrawal[] memory w1)
        internal
        pure
        returns (RequestableWithdrawal[] memory)
    {
        RequestableWithdrawal[] memory withdrawals = new RequestableWithdrawal[](w0.length + w1.length);
        for (uint256 i = 0; i < w0.length; i++) {
            withdrawals[i] = w0[i];
        }
        for (uint256 i = 0; i < w1.length; i++) {
            withdrawals[w0.length + i] = w1[i];
        }
        return withdrawals;
    }

    function push(ClaimableWithdrawal[] memory w, ClaimableWithdrawal memory withdrawal)
        internal
        pure
        returns (ClaimableWithdrawal[] memory)
    {
        ClaimableWithdrawal[] memory newClaimableWithdrawals = new ClaimableWithdrawal[](w.length + 1);
        for (uint256 i = 0; i < w.length; i++) {
            newClaimableWithdrawals[i] = w[i];
        }
        newClaimableWithdrawals[w.length] = withdrawal;
        return newClaimableWithdrawals;
    }

    function concat(ClaimableWithdrawal[] memory w0, ClaimableWithdrawal[] memory w1)
        internal
        pure
        returns (ClaimableWithdrawal[] memory)
    {
        ClaimableWithdrawal[] memory withdrawals = new ClaimableWithdrawal[](w0.length + w1.length);
        for (uint256 i = 0; i < w0.length; i++) {
            withdrawals[i] = w0[i];
        }
        for (uint256 i = 0; i < w1.length; i++) {
            withdrawals[w0.length + i] = w1[i];
        }
        return withdrawals;
    }

    function push(PendingWithdrawal[] memory w, PendingWithdrawal memory withdrawal)
        internal
        pure
        returns (PendingWithdrawal[] memory)
    {
        PendingWithdrawal[] memory newPendingWithdrawals = new PendingWithdrawal[](w.length + 1);
        for (uint256 i = 0; i < w.length; i++) {
            newPendingWithdrawals[i] = w[i];
        }
        newPendingWithdrawals[w.length] = withdrawal;
        return newPendingWithdrawals;
    }

    function concat(PendingWithdrawal[] memory w0, PendingWithdrawal[] memory w1)
        internal
        pure
        returns (PendingWithdrawal[] memory)
    {
        PendingWithdrawal[] memory withdrawals = new PendingWithdrawal[](w0.length + w1.length);
        for (uint256 i = 0; i < w0.length; i++) {
            withdrawals[i] = w0[i];
        }
        for (uint256 i = 0; i < w1.length; i++) {
            withdrawals[w0.length + i] = w1[i];
        }
        return withdrawals;
    }

    function filterEmpty(PendingWithdrawal[] memory pendingWithdrawals)
        internal
        pure
        returns (PendingWithdrawal[] memory)
    {
        PendingWithdrawal[] memory filteredPendingWithdrawals = new PendingWithdrawal[](0);
        for (uint256 i = 0; i < pendingWithdrawals.length; i++) {
            if (pendingWithdrawals[i].expectedOutputs.length > 0) {
                for (uint256 j = 0; j < pendingWithdrawals[i].expectedOutputs.length; j++) {
                    if (pendingWithdrawals[i].expectedOutputs[j].amount > 0) {
                        filteredPendingWithdrawals = push(filteredPendingWithdrawals, pendingWithdrawals[i]);
                        break;
                    }
                }
            }
        }

        return filteredPendingWithdrawals;
    }

    function filterEmpty(ClaimableWithdrawal[] memory claimableWithdrawals)
        internal
        pure
        returns (ClaimableWithdrawal[] memory)
    {
        ClaimableWithdrawal[] memory filteredClaimableWithdrawals = new ClaimableWithdrawal[](0);
        for (uint256 i = 0; i < claimableWithdrawals.length; i++) {
            if (claimableWithdrawals[i].outputs.length > 0) {
                for (uint256 j = 0; j < claimableWithdrawals[i].outputs.length; j++) {
                    if (claimableWithdrawals[i].outputs[j].amount > 0) {
                        filteredClaimableWithdrawals = push(filteredClaimableWithdrawals, claimableWithdrawals[i]);
                        break;
                    }
                }
            }
        }

        return filteredClaimableWithdrawals;
    }
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {AllowanceAction} from "./ICreditConfiguratorV3.sol";
import "./ICreditFacadeV3Multicall.sol";
import {IACLTrait} from "./base/IACLTrait.sol";
import {PriceUpdate} from "./base/IPriceFeedStore.sol";
import {IVersion} from "./base/IVersion.sol";

/// @notice Multicall element
/// @param target Call target, which is either credit facade or adapter
/// @param callData Call data
struct MultiCall {
    address target;
    bytes callData;
}

/// @notice Debt limits packed into a single slot
/// @param minDebt Minimum debt amount per credit account
/// @param maxDebt Maximum debt amount per credit account
struct DebtLimits {
    uint128 minDebt;
    uint128 maxDebt;
}

/// @notice Collateral check params
/// @param collateralHints Optional array of token masks to check first to reduce the amount of computation
///        when known subset of account's collateral tokens covers all the debt
/// @param minHealthFactor Min account's health factor in bps in order not to revert
struct FullCheckParams {
    uint256[] collateralHints;
    uint16 minHealthFactor;
}

interface ICreditFacadeV3Events {
    /// @notice Emitted when a new credit account is opened
    event OpenCreditAccount(
        address indexed creditAccount, address indexed onBehalfOf, address indexed caller, uint256 referralCode
    );

    /// @notice Emitted when account is closed
    event CloseCreditAccount(address indexed creditAccount, address indexed borrower);

    /// @notice Emitted when account is liquidated
    event LiquidateCreditAccount(
        address indexed creditAccount, address indexed liquidator, address to, uint256 remainingFunds
    );

    /// @notice Emitted when account is partially liquidated
    event PartiallyLiquidateCreditAccount(
        address indexed creditAccount,
        address indexed token,
        address indexed liquidator,
        uint256 repaidDebt,
        uint256 seizedCollateral,
        uint256 fee
    );

    /// @notice Emitted when collateral is added to account
    event AddCollateral(address indexed creditAccount, address indexed token, uint256 amount);

    /// @notice Emitted when collateral is withdrawn from account
    event WithdrawCollateral(address indexed creditAccount, address indexed token, uint256 amount, address to);

    /// @notice Emitted when a multicall is started
    event StartMultiCall(address indexed creditAccount, address indexed caller);

    /// @notice Emitted when phantom token is withdrawn by account
    event WithdrawPhantomToken(address indexed creditAccount, address indexed token, uint256 amount);

    /// @notice Emitted when a call from account to an external contract is made during a multicall
    event Execute(address indexed creditAccount, address indexed targetContract);

    /// @notice Emitted when a multicall is finished
    event FinishMultiCall();
}

/// @title Credit facade V3 interface
interface ICreditFacadeV3 is IVersion, IACLTrait, ICreditFacadeV3Events {
    function creditManager() external view returns (address);

    function underlying() external view returns (address);

    function treasury() external view returns (address);

    function priceFeedStore() external view returns (address);

    function degenNFT() external view returns (address);

    function weth() external view returns (address);

    function botList() external view returns (address);

    function maxDebtPerBlockMultiplier() external view returns (uint8);

    function maxQuotaMultiplier() external view returns (uint256);

    function expirable() external view returns (bool);

    function expirationDate() external view returns (uint40);

    function debtLimits() external view returns (uint128 minDebt, uint128 maxDebt);

    function lossPolicy() external view returns (address);

    function forbiddenTokenMask() external view returns (uint256);

    // ------------------ //
    // ACCOUNT MANAGEMENT //
    // ------------------ //

    function openCreditAccount(address onBehalfOf, MultiCall[] calldata calls, uint256 referralCode)
        external
        payable
        returns (address creditAccount);

    function closeCreditAccount(address creditAccount, MultiCall[] calldata calls) external payable;

    function liquidateCreditAccount(
        address creditAccount,
        address to,
        MultiCall[] calldata calls,
        bytes memory lossPolicyData
    ) external;

    function liquidateCreditAccount(address creditAccount, address to, MultiCall[] calldata calls) external;

    function partiallyLiquidateCreditAccount(
        address creditAccount,
        address token,
        uint256 repaidAmount,
        uint256 minSeizedAmount,
        address to,
        PriceUpdate[] calldata priceUpdates
    ) external returns (uint256 seizedAmount);

    function multicall(address creditAccount, MultiCall[] calldata calls) external payable;

    function botMulticall(address creditAccount, MultiCall[] calldata calls) external;

    // ------------- //
    // CONFIGURATION //
    // ------------- //

    function setExpirationDate(uint40 newExpirationDate) external;

    function setDebtLimits(uint128 newMinDebt, uint128 newMaxDebt, uint8 newMaxDebtPerBlockMultiplier) external;

    function setLossPolicy(address newLossPolicy) external;

    function setTokenAllowance(address token, AllowanceAction allowance) external;

    function pause() external;

    function unpause() external;
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.23;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IMellowMultiVault, IMellowWithdrawalQueue, Subvault} from "../../integrations/mellow/IMellowMultiVault.sol";
import {PhantomERC20} from "../PhantomERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {MultiCall} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditFacadeV3.sol";
import {IPhantomToken} from "@gearbox-protocol/core-v3/contracts/interfaces/base/IPhantomToken.sol";

/// @title MellowLRT withdrawal phantom token
/// @notice Phantom ERC-20 token that represents the balance of the pending and claimable withdrawals in Mellow vaults
contract MellowWithdrawalPhantomToken is PhantomERC20, Ownable, IPhantomToken {
    event SetClaimer(address indexed claimer);

    error SubvaultClaimerMismatchException();

    bytes32 public constant override contractType = "PHANTOM_TOKEN::MELLOW_WITHDRAWAL";

    uint256 public constant override version = 3_11;

    address public immutable multiVault;

    address public claimer;

    /// @notice Constructor
    /// @param _ioProxy The address of the Instance Owner proxy
    /// @param _multiVault The MultiVault where the pending assets are tracked
    /// @param _claimer The address of the initial Claimer contract
    constructor(address _ioProxy, address _multiVault, address _claimer)
        PhantomERC20(
            IERC4626(_multiVault).asset(),
            string.concat("Mellow withdrawn ", IERC20Metadata(IERC4626(_multiVault).asset()).name()),
            string.concat("wd", IERC20Metadata(IERC4626(_multiVault).asset()).symbol()),
            IERC20Metadata(IERC4626(_multiVault).asset()).decimals()
        )
    {
        _transferOwnership(_ioProxy);

        multiVault = _multiVault;
        claimer = _claimer;
    }

    /// @notice Returns the amount of assets pending/claimable for withdrawal
    /// @param account The account for which the calculation is performed
    function balanceOf(address account) public view returns (uint256 balance) {
        uint256 nSubvaults = IMellowMultiVault(multiVault).subvaultsCount();

        for (uint256 i = 0; i < nSubvaults; ++i) {
            Subvault memory subvault = IMellowMultiVault(multiVault).subvaultAt(i);

            if (subvault.withdrawalQueue == address(0)) continue;

            balance += IMellowWithdrawalQueue(subvault.withdrawalQueue).pendingAssetsOf(account)
                + IMellowWithdrawalQueue(subvault.withdrawalQueue).claimableAssetsOf(account);
        }
    }

    /// @notice Returns phantom token's target contract and underlying
    function getPhantomTokenInfo() external view override returns (address, address) {
        return (claimer, underlying);
    }

    function serialize() external view override returns (bytes memory) {
        return abi.encode(claimer, underlying);
    }

    /// @notice Sets the address of the Claimer contract
    function setClaimer(address _claimer) external onlyOwner {
        if (_claimer != claimer) {
            uint256 nSubvaults = IMellowMultiVault(multiVault).subvaultsCount();

            for (uint256 i = 0; i < nSubvaults; ++i) {
                Subvault memory subvault = IMellowMultiVault(multiVault).subvaultAt(i);

                if (subvault.withdrawalQueue == address(0)) continue;

                address queueClaimer = IMellowWithdrawalQueue(subvault.withdrawalQueue).claimer();

                if (queueClaimer != _claimer) revert SubvaultClaimerMismatchException();
            }

            claimer = _claimer;
            emit SetClaimer(_claimer);
        }
    }
}

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

enum MellowProtocol {
    SYMBIOTIC,
    EIGEN_LAYER,
    ERC4626
}

struct Subvault {
    MellowProtocol protocol;
    address vault;
    address withdrawalQueue;
}

interface IMellowMultiVault {
    function asset() external view returns (address);
    function withdrawalQueue() external view returns (address);
    function subvaultsCount() external view returns (uint256);
    function subvaultAt(uint256 index) external view returns (Subvault memory);
    function depositWhitelist() external view returns (bool);
}

interface IMellowWithdrawalQueue {
    function pendingAssetsOf(address account) external view returns (uint256);
    function claimableAssetsOf(address account) external view returns (uint256);
    function claimer() external view returns (address);
}

interface IEigenLayerWithdrawalQueue {
    function getAccountData(
        address account,
        uint256 withdrawalsLimit,
        uint256 withdrawalsOffset,
        uint256 transferredWithdrawalsLimit,
        uint256 transferredWithdrawalsOffset
    )
        external
        view
        returns (uint256 claimableAssets, uint256[] memory withdrawals, uint256[] memory transferredWithdrawals);
}

// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.23;

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

struct MellowMultiVaultStatus {
    address multiVault;
    address stakedPhantomToken;
    bool allowed;
}

interface IMellowClaimerAdapterEvents {
    event SetMultiVaultStatus(address indexed multiVault, bool allowed);
}

interface IMellowClaimerAdapterExceptions {
    /// @notice Error thrown when the actually claimed amount is less than the requested amount
    error InsufficientClaimedException();

    /// @notice Thrown when the staked phantom token field does not match the multivault
    error InvalidMultiVaultException();

    /// @notice Thrown when the staked phantom token added with the vault has incorrect parameters
    error InvalidStakedPhantomTokenException();

    /// @notice Thrown when the multivault is not allowed
    error MultiVaultNotAllowedException();
}

/// @title Mellow ERC4626 Vault adapter interface
/// @notice Interface for the adapter to interact with Mellow's ERC4626 vaults
interface IMellowClaimerAdapter is
    IPhantomTokenAdapter,
    IMellowClaimerAdapterExceptions,
    IMellowClaimerAdapterEvents
{
    function multiAccept(address multiVault, uint256[] calldata subvaultIndices, uint256[][] calldata indices)
        external
        returns (bool);

    function multiAcceptAndClaim(
        address multiVault,
        uint256[] calldata subvaultIndices,
        uint256[][] calldata indices,
        address,
        uint256 maxAssets
    ) external returns (bool);

    function getMultiVaultSubvaultIndices(address multiVault)
        external
        view
        returns (uint256[] memory subvaultIndices, uint256[][] memory withdrawalIndices);

    function getUserSubvaultIndices(address multiVault, address user)
        external
        view
        returns (uint256[] memory subvaultIndices, uint256[][] memory withdrawalIndices);

    function allowedMultiVaults() external view returns (address[] memory);

    function setMultiVaultStatusBatch(MellowMultiVaultStatus[] calldata multivaults) external;
}

File 10 of 37 : IMellow4626VaultAdapter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.23;

import {IERC4626Adapter} from "../erc4626/IERC4626Adapter.sol";

/// @title Mellow ERC4626 Vault adapter interface
/// @notice Interface for the adapter to interact with Mellow's ERC4626 vaults
interface IMellow4626VaultAdapter is IERC4626Adapter {
    /// @notice Thrown when the multivault in the staked phantom token does not match the one in the adapter
    error InvalidMultiVaultException();
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.23;

import {IAdapter} from "@gearbox-protocol/core-v3/contracts/interfaces/base/IAdapter.sol";

interface IERC4626Adapter is IAdapter {
    function asset() external view returns (address);

    function vault() external view returns (address);

    function deposit(uint256 assets, address) external returns (bool useSafePrices);

    function depositDiff(uint256 leftoverAmount) external returns (bool useSafePrices);

    function mint(uint256 shares, address) external returns (bool useSafePrices);

    function withdraw(uint256 assets, address, address) external returns (bool useSafePrices);

    function redeem(uint256 shares, address, address) external returns (bool useSafePrices);

    function redeemDiff(uint256 leftoverAmount) external returns (bool useSafePrices);
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

/// @title Version interface
/// @notice Defines contract version and type
interface IVersion {
    /// @notice Contract version
    function version() external view returns (uint256);

    /// @notice Contract type
    function contractType() external view returns (bytes32);
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IACLTrait} from "./base/IACLTrait.sol";
import {IVersion} from "./base/IVersion.sol";

enum AllowanceAction {
    FORBID,
    ALLOW
}

interface ICreditConfiguratorV3Events {
    // ------ //
    // TOKENS //
    // ------ //

    /// @notice Emitted when a token is made recognizable as collateral in the credit manager
    event AddCollateralToken(address indexed token);

    /// @notice Emitted when a new collateral token liquidation threshold is set
    event SetTokenLiquidationThreshold(address indexed token, uint16 liquidationThreshold);

    /// @notice Emitted when a collateral token liquidation threshold ramping is scheduled
    event ScheduleTokenLiquidationThresholdRamp(
        address indexed token,
        uint16 liquidationThresholdInitial,
        uint16 liquidationThresholdFinal,
        uint40 timestampRampStart,
        uint40 timestampRampEnd
    );

    /// @notice Emitted when a collateral token is forbidden
    event ForbidToken(address indexed token);

    /// @notice Emitted when a previously forbidden collateral token is allowed
    event AllowToken(address indexed token);

    // -------- //
    // ADAPTERS //
    // -------- //

    /// @notice Emitted when a new adapter and its target contract are allowed in the credit manager
    event AllowAdapter(address indexed targetContract, address indexed adapter);

    /// @notice Emitted when adapter and its target contract are forbidden in the credit manager
    event ForbidAdapter(address indexed targetContract, address indexed adapter);

    // -------------- //
    // CREDIT MANAGER //
    // -------------- //

    /// @notice Emitted when new fee parameters are set in the credit manager
    event UpdateFees(
        uint16 feeLiquidation, uint16 liquidationPremium, uint16 feeLiquidationExpired, uint16 liquidationPremiumExpired
    );

    // -------- //
    // UPGRADES //
    // -------- //

    /// @notice Emitted when a new price oracle is set in the credit manager
    event SetPriceOracle(address indexed priceOracle);

    /// @notice Emitted when a new facade is connected to the credit manager
    event SetCreditFacade(address indexed creditFacade);

    /// @notice Emitted when credit manager's configurator contract is upgraded
    event CreditConfiguratorUpgraded(address indexed creditConfigurator);

    // ------------- //
    // CREDIT FACADE //
    // ------------- //

    /// @notice Emitted when new debt principal limits are set
    event SetBorrowingLimits(uint256 minDebt, uint256 maxDebt);

    /// @notice Emitted when a new max debt per block multiplier is set
    event SetMaxDebtPerBlockMultiplier(uint8 maxDebtPerBlockMultiplier);

    /// @notice Emitted when new loss policy is set
    event SetLossPolicy(address indexed lossPolicy);

    /// @notice Emitted when a new expiration timestamp is set in the credit facade
    event SetExpirationDate(uint40 expirationDate);
}

/// @title Credit configurator V3 interface
interface ICreditConfiguratorV3 is IVersion, IACLTrait, ICreditConfiguratorV3Events {
    function creditManager() external view returns (address);

    function creditFacade() external view returns (address);

    function underlying() external view returns (address);

    // ------ //
    // TOKENS //
    // ------ //

    function makeAllTokensQuoted() external;

    function addCollateralToken(address token, uint16 liquidationThreshold) external;

    function setLiquidationThreshold(address token, uint16 liquidationThreshold) external;

    function rampLiquidationThreshold(
        address token,
        uint16 liquidationThresholdFinal,
        uint40 rampStart,
        uint24 rampDuration
    ) external;

    function forbidToken(address token) external;

    function allowToken(address token) external;

    // -------- //
    // ADAPTERS //
    // -------- //

    function allowedAdapters() external view returns (address[] memory);

    function allowAdapter(address adapter) external;

    function forbidAdapter(address adapter) external;

    // -------------- //
    // CREDIT MANAGER //
    // -------------- //

    function setFees(
        uint16 feeLiquidation,
        uint16 liquidationPremium,
        uint16 feeLiquidationExpired,
        uint16 liquidationPremiumExpired
    ) external;

    // -------- //
    // UPGRADES //
    // -------- //

    function setPriceOracle(address newPriceOracle) external;

    function setCreditFacade(address newCreditFacade, bool migrateParams) external;

    function upgradeCreditConfigurator(address newCreditConfigurator) external;

    // ------------- //
    // CREDIT FACADE //
    // ------------- //

    function setDebtLimits(uint128 newMinDebt, uint128 newMaxDebt) external;

    function setMaxDebtPerBlockMultiplier(uint8 newMaxDebtLimitPerBlockMultiplier) external;

    function forbidBorrowing() external;

    function setLossPolicy(address newLossPolicy) external;

    function setExpirationDate(uint40 newExpirationDate) external;
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {BalanceDelta} from "../libraries/BalancesLogic.sol";
import {PriceUpdate} from "./base/IPriceFeedStore.sol";

// ----------- //
// PERMISSIONS //
// ----------- //

// NOTE: permissions 1 << 3, 1 << 4 and 1 << 7 were used by now deprecated methods, thus non-consecutive values

uint192 constant ADD_COLLATERAL_PERMISSION = 1 << 0;
uint192 constant INCREASE_DEBT_PERMISSION = 1 << 1;
uint192 constant DECREASE_DEBT_PERMISSION = 1 << 2;
uint192 constant WITHDRAW_COLLATERAL_PERMISSION = 1 << 5;
uint192 constant UPDATE_QUOTA_PERMISSION = 1 << 6;
uint192 constant SET_BOT_PERMISSIONS_PERMISSION = 1 << 8;
uint192 constant EXTERNAL_CALLS_PERMISSION = 1 << 16;

uint192 constant ALL_PERMISSIONS = ADD_COLLATERAL_PERMISSION | WITHDRAW_COLLATERAL_PERMISSION | UPDATE_QUOTA_PERMISSION
    | INCREASE_DEBT_PERMISSION | DECREASE_DEBT_PERMISSION | SET_BOT_PERMISSIONS_PERMISSION | EXTERNAL_CALLS_PERMISSION;
uint192 constant OPEN_CREDIT_ACCOUNT_PERMISSIONS = ALL_PERMISSIONS & ~DECREASE_DEBT_PERMISSION;
uint192 constant CLOSE_CREDIT_ACCOUNT_PERMISSIONS = ALL_PERMISSIONS & ~INCREASE_DEBT_PERMISSION;
uint192 constant LIQUIDATE_CREDIT_ACCOUNT_PERMISSIONS =
    EXTERNAL_CALLS_PERMISSION | ADD_COLLATERAL_PERMISSION | WITHDRAW_COLLATERAL_PERMISSION;

// ----- //
// FLAGS //
// ----- //

/// @dev Indicates that collateral check after the multicall can be skipped, set to true on account closure or liquidation
uint256 constant SKIP_COLLATERAL_CHECK_FLAG = 1 << 192;

/// @dev Indicates that external calls from credit account to adapters were made during multicall,
///      set to true on the first call to the adapter
uint256 constant EXTERNAL_CONTRACT_WAS_CALLED_FLAG = 1 << 193;

/// @dev Indicates that the price updates call should be skipped, set to true on liquidation when the first call
///      of the multicall is `onDemandPriceUpdates`
uint256 constant SKIP_PRICE_UPDATES_CALL_FLAG = 1 << 194;

/// @dev Indicates that collateral check must revert if any forbidden token is encountered on the account,
///      set to true after risky operations, such as `increaseDebt` or `withdrawCollateral`
uint256 constant REVERT_ON_FORBIDDEN_TOKENS_FLAG = 1 << 195;

/// @dev Indicates that collateral check must be performed using safe prices, set to true on `withdrawCollateral`
///      or if account has enabled forbidden tokens
uint256 constant USE_SAFE_PRICES_FLAG = 1 << 196;

/// @title Credit facade V3 multicall interface
/// @dev Unless specified otherwise, all these methods are only available in `openCreditAccount`,
///      `closeCreditAccount`, `multicall`, and, with account owner's permission, `botMulticall`
interface ICreditFacadeV3Multicall {
    /// @notice Applies on-demand price feed updates
    /// @param updates Array of price updates, see `PriceUpdate` for details
    /// @dev Reverts if placed not at the first position in the multicall
    /// @dev This method is available in all kinds of multicalls
    function onDemandPriceUpdates(PriceUpdate[] calldata updates) external;

    /// @notice Stores expected token balances (current balance + delta) after operations for a slippage check.
    ///         Normally, a check is performed automatically at the end of the multicall, but more fine-grained
    ///         behavior can be achieved by placing `storeExpectedBalances` and `compareBalances` where needed.
    /// @param balanceDeltas Array of (token, minBalanceDelta) pairs, deltas are allowed to be negative
    /// @dev Reverts if expected balances are already set
    /// @dev This method is available in all kinds of multicalls
    function storeExpectedBalances(BalanceDelta[] calldata balanceDeltas) external;

    /// @notice Performs a slippage check ensuring that current token balances are greater than saved expected ones
    /// @dev Resets stored expected balances
    /// @dev Reverts if expected balances are not stored
    /// @dev This method is available in all kinds of multicalls
    function compareBalances() external;

    /// @notice Adds collateral to account.
    ///         Only the underlying token counts towards account's collateral value by default, while all other tokens
    ///         must be enabled as collateral by "purchasing" quota for it. Holding non-enabled token on account with
    ///         non-zero debt poses a risk of losing it entirely to the liquidator. Adding non-enabled tokens is still
    ///         supported to allow users to later swap them into enabled ones in the same multicall.
    /// @param token Token to add
    /// @param amount Amount to add
    /// @dev Requires token approval from caller to the credit manager
    /// @dev This method can also be called during liquidation
    function addCollateral(address token, uint256 amount) external;

    /// @notice Adds collateral to account using signed EIP-2612 permit message.
    ///         Only the underlying token counts towards account's collateral value by default, while all other tokens
    ///         must be enabled as collateral by "purchasing" quota for it. Holding non-enabled token on account with
    ///         non-zero debt poses a risk of losing it entirely to the liquidator. Adding non-enabled tokens is still
    ///         supported to allow users to later swap them into enabled ones in the same multicall.
    /// @param token Token to add
    /// @param amount Amount to add
    /// @param deadline Permit deadline
    /// @dev `v`, `r`, `s` must be a valid signature of the permit message from caller to the credit manager
    /// @dev This method can also be called during liquidation
    function addCollateralWithPermit(address token, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;

    /// @notice Increases account's debt
    /// @param amount Underlying amount to borrow
    /// @dev Increasing debt is prohibited when closing an account
    /// @dev Increasing debt is prohibited if it was previously updated in the same block
    /// @dev The resulting debt amount must be within allowed limits
    /// @dev Increasing debt is prohibited if there are forbidden tokens enabled as collateral on the account
    /// @dev After debt increase, total amount borrowed by the credit manager in the current block must not exceed
    ///      the limit defined in the facade
    function increaseDebt(uint256 amount) external;

    /// @notice Decreases account's debt
    /// @param amount Underlying amount to repay, value above account's total debt indicates full repayment
    /// @dev Decreasing debt is prohibited when opening an account
    /// @dev Decreasing debt is prohibited if it was previously updated in the same block
    /// @dev The resulting debt amount must be above allowed minimum or zero (maximum is not checked here
    ///      to allow small repayments and partial liquidations in case configurator lowers it)
    /// @dev Full repayment brings account into a special mode that skips collateral checks and thus requires
    ///      an account to have no potential debt sources, e.g., all quotas must be disabled
    function decreaseDebt(uint256 amount) external;

    /// @notice Updates account's quota for a token
    /// @param token Collateral token to update the quota for (can't be underlying)
    /// @param quotaChange Desired quota change in underlying token units (`type(int96).min` to disable quota)
    /// @param minQuota Minimum resulting account's quota for token required not to revert
    /// @dev Enables token as collateral if quota is increased from zero, disables if decreased to zero
    /// @dev Quota increase is prohibited for forbidden tokens
    /// @dev Quota update is prohibited if account has zero debt
    /// @dev Resulting account's quota for token must not exceed the limit defined in the facade
    function updateQuota(address token, int96 quotaChange, uint96 minQuota) external;

    /// @notice Withdraws collateral from account
    /// @param token Token to withdraw
    /// @param amount Amount to withdraw, `type(uint256).max` to withdraw all balance
    /// @param to Token recipient
    /// @dev This method can also be called during liquidation
    /// @dev Withdrawals are prohibited in multicalls if there are forbidden tokens enabled as collateral on the account
    /// @dev Withdrawals activate safe pricing (min of main and reserve feeds) in collateral check
    /// @dev If `token` is a phantom token, it's withdrawn first, and its `depositedToken` is then sent to the recipient.
    ///      No slippage prevention mechanism is provided as withdrawals are assumed to happen at non-manipulatable rate.
    ///      Although an adapter call is made in process, permission for external calls is not required.
    function withdrawCollateral(address token, uint256 amount, address to) external;

    /// @notice Sets advanced collateral check parameters
    /// @param collateralHints Optional array of token masks to check first to reduce the amount of computation
    ///        when known subset of account's collateral tokens covers all the debt. Underlying token is always
    ///        checked last so it's forbidden to pass its mask.
    /// @param minHealthFactor Min account's health factor in bps in order not to revert, must be at least 10000
    /// @dev This method can't be called during closure or liquidation
    function setFullCheckParams(uint256[] calldata collateralHints, uint16 minHealthFactor) external;

    /// @notice Sets `bot`'s permissions to manage account to `permissions`
    /// @param bot Bot to set permissions for
    /// @param permissions A bitmask encoding bot permissions
    /// @dev Reverts if `permissions` has unexpected bits enabled or doesn't match permissions required by `bot`
    function setBotPermissions(address bot, uint192 permissions) external;
}

File 16 of 37 : IACLTrait.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

interface IACLTrait {
    function acl() external view returns (address);
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

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

struct PriceUpdate {
    address priceFeed;
    bytes data;
}

interface IPriceFeedStore {
    function getStalenessPeriod(address priceFeed) external view returns (uint32);
    function updatePrices(PriceUpdate[] calldata updates) external;
}

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

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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 v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;

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

/// @dev PhantomERC20 is a pseudo-ERC20 that only implements totalSupply and balanceOf
/// @notice Used to track positions that do not issue an explicit share token
///         This is an abstract contract and balanceOf is implemented by concrete instances
abstract contract PhantomERC20 is IERC20Metadata {
    address public immutable underlying;

    string public symbol;
    string public override name;
    uint8 public immutable override decimals;

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

    function totalSupply() external view virtual override returns (uint256) {
        return IERC20Metadata(underlying).totalSupply();
    }

    function transfer(address, uint256) external pure override returns (bool) {
        return false;
    }

    function allowance(address, address) external pure override returns (uint256) {
        return 0;
    }

    function approve(address, uint256) external pure override returns (bool) {
        return false;
    }

    function transferFrom(address, address, uint256) external pure override returns (bool) {
        return false;
    }
}

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

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

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IVersion} from "./IVersion.sol";
import {IStateSerializer} from "./IStateSerializer.sol";

/// @title Phantom token interface
/// @notice Broadly speaking, by saying "phantom" we imply that token is not transferable. In Gearbox, we use such tokens
///         to track balances of non-tokenized positions in integrated protocols to allow those to be used as collateral.
/// @dev Phantom tokens must have type `PHANTOM_TOKEN::{POSTFIX}`
interface IPhantomToken is IVersion, IStateSerializer {
    /// @notice Returns phantom token's target contract and deposited token
    function getPhantomTokenInfo() external view returns (address target, address depositedToken);
}

/// @title Phantom token withdrawer interface
/// @notice Though only the `balanceOf()` function is needed for token to serve as collateral, some services can suffer
///         from its non-transferability, including liquidators or bots that don't have permissions for external calls.
///         To mitigate this, phantom token withdrawals from credit accounts automatically start with withdrawal of
///         deposited token from the integrated protocol via an adapter call defined by this interface.
/// @dev While theoretically possible, we assume that phantom tokens can't be nested
interface IPhantomTokenWithdrawer {
    /// @notice Withdraws phantom token for its deposited token
    function withdrawPhantomToken(address token, uint256 amount) external returns (bool useSafePrices);
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2025.
pragma solidity ^0.8.23;

import {IAdapter} from "@gearbox-protocol/core-v3/contracts/interfaces/base/IAdapter.sol";
import {IPhantomTokenWithdrawer} from "@gearbox-protocol/core-v3/contracts/interfaces/base/IPhantomToken.sol";

/// @title Phantom token adapter interface
interface IPhantomTokenAdapter is IAdapter, IPhantomTokenWithdrawer {
    /// @notice Thrown when attempting to deposit or withdraw a token that is not the staked phantom token
    error IncorrectStakedPhantomTokenException();

    /// @notice Provides a generic interface for deposits, which is useful for external integrations,
    ///         e.g., when one needs to move an arbitrary phantom token between accounts.
    function depositPhantomToken(address token, uint256 amount) external returns (bool);
}

// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IVersion} from "./IVersion.sol";
import {IStateSerializer} from "./IStateSerializer.sol";

/// @title Adapter interface
/// @notice Generic interface for an adapter that can be used to interact with external protocols.
///         Adapters can be assumed to be non-malicious since they are developed by Gearbox DAO.
/// @dev Adapters must have type `ADAPTER::{POSTFIX}`
interface IAdapter is IVersion, IStateSerializer {
    /// @notice Credit manager this adapter is connected to
    /// @dev Assumed to be an immutable state variable
    function creditManager() external view returns (address);

    /// @notice Target contract adapter helps to interact with
    /// @dev Assumed to be an immutable state variable
    function targetContract() external view returns (address);
}

// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@1inch/solidity-utils/contracts/libraries/SafeERC20.sol";

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

struct Balance {
    address token;
    uint256 balance;
}

struct BalanceWithMask {
    address token;
    uint256 tokenMask;
    uint256 balance;
}

struct BalanceDelta {
    address token;
    int256 amount;
}

enum Comparison {
    GREATER_OR_EQUAL,
    LESS_OR_EQUAL
}

/// @title Balances logic library
/// @notice Implements functions for before-and-after balance comparisons
library BalancesLogic {
    using BitMask for uint256;
    using SafeCast for int256;
    using SafeCast for uint256;
    using SafeERC20 for IERC20;

    /// @dev Compares current `token` balance with `value`
    /// @param token Token to check balance for
    /// @param value Value to compare current token balance with
    /// @param comparison Whether current balance must be greater/less than or equal to `value`
    function checkBalance(address creditAccount, address token, uint256 value, Comparison comparison)
        internal
        view
        returns (bool)
    {
        uint256 current = IERC20(token).safeBalanceOf(creditAccount);
        return (comparison == Comparison.GREATER_OR_EQUAL && current >= value)
            || (comparison == Comparison.LESS_OR_EQUAL && current <= value); // U:[BLL-1]
    }

    /// @dev Returns an array of expected token balances after operations
    /// @param creditAccount Credit account to compute balances for
    /// @param deltas Array of expected token balance changes
    function storeBalances(address creditAccount, BalanceDelta[] memory deltas)
        internal
        view
        returns (Balance[] memory balances)
    {
        uint256 len = deltas.length;
        balances = new Balance[](len); // U:[BLL-2]
        for (uint256 i = 0; i < len;) {
            int256 balance = IERC20(deltas[i].token).safeBalanceOf(creditAccount).toInt256();
            balances[i] = Balance({token: deltas[i].token, balance: (balance + deltas[i].amount).toUint256()}); // U:[BLL-2]
            unchecked {
                ++i;
            }
        }
    }

    /// @dev Compares current balances with the previously stored ones
    /// @param creditAccount Credit account to compare balances for
    /// @param balances Array of previously stored balances
    /// @param comparison Whether current balances must be greater/less than or equal to stored ones
    /// @return failedToken The first token for which the condition specified by `comparison` fails, if any
    function compareBalances(address creditAccount, Balance[] memory balances, Comparison comparison)
        internal
        view
        returns (address failedToken)
    {
        unchecked {
            uint256 len = balances.length;
            for (uint256 i; i < len; ++i) {
                if (!BalancesLogic.checkBalance(creditAccount, balances[i].token, balances[i].balance, comparison)) {
                    return balances[i].token; // U:[BLL-3]
                }
            }
        }
    }

    /// @dev Returns balances of specified tokens on the credit account
    /// @param creditAccount Credit account to compute balances for
    /// @param tokensMask Bit mask of tokens to compute balances for
    /// @param getTokenByMaskFn Function that returns token's address by its mask
    function storeBalances(
        address creditAccount,
        uint256 tokensMask,
        function (uint256) view returns (address) getTokenByMaskFn
    ) internal view returns (BalanceWithMask[] memory balances) {
        if (tokensMask == 0) return balances;

        balances = new BalanceWithMask[](tokensMask.calcEnabledTokens()); // U:[BLL-4]
        unchecked {
            uint256 i;
            while (tokensMask != 0) {
                uint256 tokenMask = tokensMask.lsbMask();
                tokensMask ^= tokenMask;

                address token = getTokenByMaskFn(tokenMask);
                balances[i] = BalanceWithMask({
                    token: token,
                    tokenMask: tokenMask,
                    balance: IERC20(token).safeBalanceOf(creditAccount)
                }); // U:[BLL-4]
                ++i;
            }
        }
    }

    /// @dev Compares current balances of specified tokens with the previously stored ones
    /// @param creditAccount Credit account to compare balances for
    /// @param tokensMask Bit mask of tokens to compare balances for
    /// @param balances Array of previously stored balances
    /// @param comparison Whether current balances must be greater/less than or equal to stored ones
    /// @return failedToken The first token for which the condition specified by `comparison` fails, if any
    /// @dev This function assumes that `tokensMask` encodes a subset of tokens from `balances`
    function compareBalances(
        address creditAccount,
        uint256 tokensMask,
        BalanceWithMask[] memory balances,
        Comparison comparison
    ) internal view returns (address failedToken) {
        if (tokensMask == 0) return address(0);

        unchecked {
            uint256 len = balances.length;
            for (uint256 i; i < len; ++i) {
                if (tokensMask & balances[i].tokenMask == 0) continue;
                if (!BalancesLogic.checkBalance(creditAccount, balances[i].token, balances[i].balance, comparison)) {
                    return balances[i].token; // U:[BLL-5]
                }
            }
        }
    }
}

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

pragma solidity ^0.8.0;

/**
 * @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 27 of 37 : IStateSerializer.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

/// @title State serializer interface
/// @notice Generic interface for a contract that can serialize its state into a bytes array
interface IStateSerializer {
    /// @notice Serializes the state of the contract into a bytes array `serializedData`
    function serialize() external view returns (bytes memory serializedData);
}

File 28 of 37 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        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
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        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
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        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
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        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
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @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
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @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
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "../interfaces/IDaiLikePermit.sol";
import "../interfaces/IPermit2.sol";
import "../interfaces/IWETH.sol";
import "../libraries/RevertReasonForwarder.sol";

/**
 * @title Implements efficient safe methods for ERC20 interface.
 * @notice Compared to the standard ERC20, this implementation offers several enhancements:
 * 1. more gas-efficient, providing significant savings in transaction costs.
 * 2. support for different permit implementations
 * 3. forceApprove functionality
 * 4. support for WETH deposit and withdraw
 */
library SafeERC20 {
    error SafeTransferFailed();
    error SafeTransferFromFailed();
    error ForceApproveFailed();
    error SafeIncreaseAllowanceFailed();
    error SafeDecreaseAllowanceFailed();
    error SafePermitBadLength();
    error Permit2TransferAmountTooHigh();

    // Uniswap Permit2 address
    address private constant _PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
    bytes4 private constant _PERMIT_LENGTH_ERROR = 0x68275857;  // SafePermitBadLength.selector
    uint256 private constant _RAW_CALL_GAS_LIMIT = 5000;

    /**
     * @notice Fetches the balance of a specific ERC20 token held by an account.
     * Consumes less gas then regular `ERC20.balanceOf`.
     * @param token The IERC20 token contract for which the balance will be fetched.
     * @param account The address of the account whose token balance will be fetched.
     * @return tokenBalance The balance of the specified ERC20 token held by the account.
     */
    function safeBalanceOf(
        IERC20 token,
        address account
    ) internal view returns(uint256 tokenBalance) {
        bytes4 selector = IERC20.balanceOf.selector;
        assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
            mstore(0x00, selector)
            mstore(0x04, account)
            let success := staticcall(gas(), token, 0x00, 0x24, 0x00, 0x20)
            tokenBalance := mload(0)

            if or(iszero(success), lt(returndatasize(), 0x20)) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
        }
    }

    /**
     * @notice Attempts to safely transfer tokens from one address to another.
     * @dev If permit2 is true, uses the Permit2 standard; otherwise uses the standard ERC20 transferFrom. 
     * Either requires `true` in return data, or requires target to be smart-contract and empty return data.
     * @param token The IERC20 token contract from which the tokens will be transferred.
     * @param from The address from which the tokens will be transferred.
     * @param to The address to which the tokens will be transferred.
     * @param amount The amount of tokens to transfer.
     * @param permit2 If true, uses the Permit2 standard for the transfer; otherwise uses the standard ERC20 transferFrom.
     */
    function safeTransferFromUniversal(
        IERC20 token,
        address from,
        address to,
        uint256 amount,
        bool permit2
    ) internal {
        if (permit2) {
            safeTransferFromPermit2(token, from, to, amount);
        } else {
            safeTransferFrom(token, from, to, amount);
        }
    }

    /**
     * @notice Attempts to safely transfer tokens from one address to another using the ERC20 standard.
     * @dev Either requires `true` in return data, or requires target to be smart-contract and empty return data.
     * @param token The IERC20 token contract from which the tokens will be transferred.
     * @param from The address from which the tokens will be transferred.
     * @param to The address to which the tokens will be transferred.
     * @param amount The amount of tokens to transfer.
     */
    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        bytes4 selector = token.transferFrom.selector;
        bool success;
        assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
            let data := mload(0x40)

            mstore(data, selector)
            mstore(add(data, 0x04), from)
            mstore(add(data, 0x24), to)
            mstore(add(data, 0x44), amount)
            success := call(gas(), token, 0, data, 100, 0x0, 0x20)
            if success {
                switch returndatasize()
                case 0 {
                    success := gt(extcodesize(token), 0)
                }
                default {
                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))
                }
            }
        }
        if (!success) revert SafeTransferFromFailed();
    }

    /**
     * @notice Attempts to safely transfer tokens from one address to another using the Permit2 standard.
     * @dev Either requires `true` in return data, or requires target to be smart-contract and empty return data.
     * @param token The IERC20 token contract from which the tokens will be transferred.
     * @param from The address from which the tokens will be transferred.
     * @param to The address to which the tokens will be transferred.
     * @param amount The amount of tokens to transfer.
     */
    function safeTransferFromPermit2(
        IERC20 token,
        address from,
        address to,
        uint256 amount
    ) internal {
        if (amount > type(uint160).max) revert Permit2TransferAmountTooHigh();
        bytes4 selector = IPermit2.transferFrom.selector;
        bool success;
        assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
            let data := mload(0x40)

            mstore(data, selector)
            mstore(add(data, 0x04), from)
            mstore(add(data, 0x24), to)
            mstore(add(data, 0x44), amount)
            mstore(add(data, 0x64), token)
            success := call(gas(), _PERMIT2, 0, data, 0x84, 0x0, 0x0)
            if success {
                success := gt(extcodesize(_PERMIT2), 0)
            }
        }
        if (!success) revert SafeTransferFromFailed();
    }

    /**
     * @notice Attempts to safely transfer tokens to another address.
     * @dev Either requires `true` in return data, or requires target to be smart-contract and empty return data.
     * @param token The IERC20 token contract from which the tokens will be transferred.
     * @param to The address to which the tokens will be transferred.
     * @param value The amount of tokens to transfer.
     */
    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        if (!_makeCall(token, token.transfer.selector, to, value)) {
            revert SafeTransferFailed();
        }
    }

    /**
     * @notice Attempts to approve a spender to spend a certain amount of tokens.
     * @dev If `approve(from, to, amount)` fails, it tries to set the allowance to zero, and retries the `approve` call.
     * @param token The IERC20 token contract on which the call will be made.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     */
    function forceApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        if (!_makeCall(token, token.approve.selector, spender, value)) {
            if (
                !_makeCall(token, token.approve.selector, spender, 0) ||
                !_makeCall(token, token.approve.selector, spender, value)
            ) {
                revert ForceApproveFailed();
            }
        }
    }

    /**
     * @notice Safely increases the allowance of a spender.
     * @dev Increases with safe math check. Checks if the increased allowance will overflow, if yes, then it reverts the transaction.
     * Then uses `forceApprove` to increase the allowance.
     * @param token The IERC20 token contract on which the call will be made.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to increase the allowance by.
     */
    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 allowance = token.allowance(address(this), spender);
        if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();
        forceApprove(token, spender, allowance + value);
    }

    /**
     * @notice Safely decreases the allowance of a spender.
     * @dev Decreases with safe math check. Checks if the decreased allowance will underflow, if yes, then it reverts the transaction.
     * Then uses `forceApprove` to increase the allowance.
     * @param token The IERC20 token contract on which the call will be made.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to decrease the allowance by.
     */
    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 allowance = token.allowance(address(this), spender);
        if (value > allowance) revert SafeDecreaseAllowanceFailed();
        forceApprove(token, spender, allowance - value);
    }

    /**
     * @notice Attempts to execute the `permit` function on the provided token with the sender and contract as parameters.
     * Permit type is determined automatically based on permit calldata (IERC20Permit, IDaiLikePermit, and IPermit2).
     * @dev Wraps `tryPermit` function and forwards revert reason if permit fails.
     * @param token The IERC20 token to execute the permit function on.
     * @param permit The permit data to be used in the function call.
     */
    function safePermit(IERC20 token, bytes calldata permit) internal {
        if (!tryPermit(token, msg.sender, address(this), permit)) RevertReasonForwarder.reRevert();
    }

    /**
     * @notice Attempts to execute the `permit` function on the provided token with custom owner and spender parameters. 
     * Permit type is determined automatically based on permit calldata (IERC20Permit, IDaiLikePermit, and IPermit2).
     * @dev Wraps `tryPermit` function and forwards revert reason if permit fails.
     * @param token The IERC20 token to execute the permit function on.
     * @param owner The owner of the tokens for which the permit is made.
     * @param spender The spender allowed to spend the tokens by the permit.
     * @param permit The permit data to be used in the function call.
     */
    function safePermit(IERC20 token, address owner, address spender, bytes calldata permit) internal {
        if (!tryPermit(token, owner, spender, permit)) RevertReasonForwarder.reRevert();
    }

    /**
     * @notice Attempts to execute the `permit` function on the provided token with the sender and contract as parameters.
     * @dev Invokes `tryPermit` with sender as owner and contract as spender.
     * @param token The IERC20 token to execute the permit function on.
     * @param permit The permit data to be used in the function call.
     * @return success Returns true if the permit function was successfully executed, false otherwise.
     */
    function tryPermit(IERC20 token, bytes calldata permit) internal returns(bool success) {
        return tryPermit(token, msg.sender, address(this), permit);
    }

    /**
     * @notice The function attempts to call the permit function on a given ERC20 token.
     * @dev The function is designed to support a variety of permit functions, namely: IERC20Permit, IDaiLikePermit, and IPermit2.
     * It accommodates both Compact and Full formats of these permit types.
     * Please note, it is expected that the `expiration` parameter for the compact Permit2 and the `deadline` parameter 
     * for the compact Permit are to be incremented by one before invoking this function. This approach is motivated by
     * gas efficiency considerations; as the unlimited expiration period is likely to be the most common scenario, and 
     * zeros are cheaper to pass in terms of gas cost. Thus, callers should increment the expiration or deadline by one
     * before invocation for optimized performance.
     * @param token The address of the ERC20 token on which to call the permit function.
     * @param owner The owner of the tokens. This address should have signed the off-chain permit.
     * @param spender The address which will be approved for transfer of tokens.
     * @param permit The off-chain permit data, containing different fields depending on the type of permit function.
     * @return success A boolean indicating whether the permit call was successful.
     */
    function tryPermit(IERC20 token, address owner, address spender, bytes calldata permit) internal returns(bool success) {
        // load function selectors for different permit standards
        bytes4 permitSelector = IERC20Permit.permit.selector;
        bytes4 daiPermitSelector = IDaiLikePermit.permit.selector;
        bytes4 permit2Selector = IPermit2.permit.selector;
        assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
            let ptr := mload(0x40)

            // Switch case for different permit lengths, indicating different permit standards
            switch permit.length
            // Compact IERC20Permit
            case 100 {
                mstore(ptr, permitSelector)     // store selector
                mstore(add(ptr, 0x04), owner)   // store owner
                mstore(add(ptr, 0x24), spender) // store spender

                // Compact IERC20Permit.permit(uint256 value, uint32 deadline, uint256 r, uint256 vs)
                {  // stack too deep
                    let deadline := shr(224, calldataload(add(permit.offset, 0x20))) // loads permit.offset 0x20..0x23
                    let vs := calldataload(add(permit.offset, 0x44))                 // loads permit.offset 0x44..0x63

                    calldatacopy(add(ptr, 0x44), permit.offset, 0x20)            // store value     = copy permit.offset 0x00..0x19
                    mstore(add(ptr, 0x64), sub(deadline, 1))                     // store deadline  = deadline - 1
                    mstore(add(ptr, 0x84), add(27, shr(255, vs)))                // store v         = most significant bit of vs + 27 (27 or 28)
                    calldatacopy(add(ptr, 0xa4), add(permit.offset, 0x24), 0x20) // store r         = copy permit.offset 0x24..0x43
                    mstore(add(ptr, 0xc4), shr(1, shl(1, vs)))                   // store s         = vs without most significant bit
                }
                // IERC20Permit.permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
                success := call(gas(), token, 0, ptr, 0xe4, 0, 0)
            }
            // Compact IDaiLikePermit
            case 72 {
                mstore(ptr, daiPermitSelector)  // store selector
                mstore(add(ptr, 0x04), owner)   // store owner
                mstore(add(ptr, 0x24), spender) // store spender

                // Compact IDaiLikePermit.permit(uint32 nonce, uint32 expiry, uint256 r, uint256 vs)
                {  // stack too deep
                    let expiry := shr(224, calldataload(add(permit.offset, 0x04))) // loads permit.offset 0x04..0x07
                    let vs := calldataload(add(permit.offset, 0x28))               // loads permit.offset 0x28..0x47

                    mstore(add(ptr, 0x44), shr(224, calldataload(permit.offset))) // store nonce   = copy permit.offset 0x00..0x03
                    mstore(add(ptr, 0x64), sub(expiry, 1))                        // store expiry  = expiry - 1
                    mstore(add(ptr, 0x84), true)                                  // store allowed = true
                    mstore(add(ptr, 0xa4), add(27, shr(255, vs)))                 // store v       = most significant bit of vs + 27 (27 or 28)
                    calldatacopy(add(ptr, 0xc4), add(permit.offset, 0x08), 0x20)  // store r       = copy permit.offset 0x08..0x27
                    mstore(add(ptr, 0xe4), shr(1, shl(1, vs)))                    // store s       = vs without most significant bit
                }
                // IDaiLikePermit.permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)
                success := call(gas(), token, 0, ptr, 0x104, 0, 0)
            }
            // IERC20Permit
            case 224 {
                mstore(ptr, permitSelector)
                calldatacopy(add(ptr, 0x04), permit.offset, permit.length) // copy permit calldata
                // IERC20Permit.permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
                success := call(gas(), token, 0, ptr, 0xe4, 0, 0)
            }
            // IDaiLikePermit
            case 256 {
                mstore(ptr, daiPermitSelector)
                calldatacopy(add(ptr, 0x04), permit.offset, permit.length) // copy permit calldata
                // IDaiLikePermit.permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s)
                success := call(gas(), token, 0, ptr, 0x104, 0, 0)
            }
            // Compact IPermit2
            case 96 {
                // Compact IPermit2.permit(uint160 amount, uint32 expiration, uint32 nonce, uint32 sigDeadline, uint256 r, uint256 vs)
                mstore(ptr, permit2Selector)  // store selector
                mstore(add(ptr, 0x04), owner) // store owner
                mstore(add(ptr, 0x24), token) // store token

                calldatacopy(add(ptr, 0x50), permit.offset, 0x14)             // store amount = copy permit.offset 0x00..0x13
                // and(0xffffffffffff, ...) - conversion to uint48 
                mstore(add(ptr, 0x64), and(0xffffffffffff, sub(shr(224, calldataload(add(permit.offset, 0x14))), 1))) // store expiration = ((permit.offset 0x14..0x17 - 1) & 0xffffffffffff)
                mstore(add(ptr, 0x84), shr(224, calldataload(add(permit.offset, 0x18)))) // store nonce = copy permit.offset 0x18..0x1b
                mstore(add(ptr, 0xa4), spender)                               // store spender
                // and(0xffffffffffff, ...) - conversion to uint48
                mstore(add(ptr, 0xc4), and(0xffffffffffff, sub(shr(224, calldataload(add(permit.offset, 0x1c))), 1))) // store sigDeadline = ((permit.offset 0x1c..0x1f - 1) & 0xffffffffffff)
                mstore(add(ptr, 0xe4), 0x100)                                 // store offset = 256
                mstore(add(ptr, 0x104), 0x40)                                 // store length = 64
                calldatacopy(add(ptr, 0x124), add(permit.offset, 0x20), 0x20) // store r      = copy permit.offset 0x20..0x3f
                calldatacopy(add(ptr, 0x144), add(permit.offset, 0x40), 0x20) // store vs     = copy permit.offset 0x40..0x5f
                // IPermit2.permit(address owner, PermitSingle calldata permitSingle, bytes calldata signature)
                success := call(gas(), _PERMIT2, 0, ptr, 0x164, 0, 0)
            }
            // IPermit2
            case 352 {
                mstore(ptr, permit2Selector)
                calldatacopy(add(ptr, 0x04), permit.offset, permit.length) // copy permit calldata
                // IPermit2.permit(address owner, PermitSingle calldata permitSingle, bytes calldata signature)
                success := call(gas(), _PERMIT2, 0, ptr, 0x164, 0, 0)
            }
            // Unknown
            default {
                mstore(ptr, _PERMIT_LENGTH_ERROR)
                revert(ptr, 4)
            }
        }
    }

    /**
     * @dev Executes a low level call to a token contract, making it resistant to reversion and erroneous boolean returns.
     * @param token The IERC20 token contract on which the call will be made.
     * @param selector The function signature that is to be called on the token contract.
     * @param to The address to which the token amount will be transferred.
     * @param amount The token amount to be transferred.
     * @return success A boolean indicating if the call was successful. Returns 'true' on success and 'false' on failure. 
     * In case of success but no returned data, validates that the contract code exists.
     * In case of returned data, ensures that it's a boolean `true`.
     */
    function _makeCall(
        IERC20 token,
        bytes4 selector,
        address to,
        uint256 amount
    ) private returns (bool success) {
        assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
            let data := mload(0x40)

            mstore(data, selector)
            mstore(add(data, 0x04), to)
            mstore(add(data, 0x24), amount)
            success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)
            if success {
                switch returndatasize()
                case 0 {
                    success := gt(extcodesize(token), 0)
                }
                default {
                    success := and(gt(returndatasize(), 31), eq(mload(0), 1))
                }
            }
        }
    }

    /**
     * @notice Safely deposits a specified amount of Ether into the IWETH contract. Consumes less gas then regular `IWETH.deposit`.
     * @param weth The IWETH token contract.
     * @param amount The amount of Ether to deposit into the IWETH contract.
     */
    function safeDeposit(IWETH weth, uint256 amount) internal {
        if (amount > 0) {
            bytes4 selector = IWETH.deposit.selector;
            assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
                mstore(0, selector)
                if iszero(call(gas(), weth, amount, 0, 4, 0, 0)) {
                    returndatacopy(0, 0, returndatasize())
                    revert(0, returndatasize())
                }
            }
        }
    }

    /**
     * @notice Safely withdraws a specified amount of wrapped Ether from the IWETH contract. Consumes less gas then regular `IWETH.withdraw`.
     * @dev Uses inline assembly to interact with the IWETH contract.
     * @param weth The IWETH token contract.
     * @param amount The amount of wrapped Ether to withdraw from the IWETH contract.
     */
    function safeWithdraw(IWETH weth, uint256 amount) internal {
        bytes4 selector = IWETH.withdraw.selector;
        assembly ("memory-safe") {  // solhint-disable-line no-inline-assembly
            mstore(0, selector)
            mstore(4, amount)
            if iszero(call(gas(), weth, 0, 0, 0x24, 0, 0)) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
        }
    }

    /**
     * @notice Safely withdraws a specified amount of wrapped Ether from the IWETH contract to a specified recipient.
     * Consumes less gas then regular `IWETH.withdraw`.
     * @param weth The IWETH token contract.
     * @param amount The amount of wrapped Ether to withdraw from the IWETH contract.
     * @param to The recipient of the withdrawn Ether.
     */
    function safeWithdrawTo(IWETH weth, uint256 amount, address to) internal {
        safeWithdraw(weth, amount);
        if (to != address(this)) {
            assembly ("memory-safe") {  // solhint-disable-line no-inline-assembly
                if iszero(call(_RAW_CALL_GAS_LIMIT, to, amount, 0, 0, 0, 0)) {
                    let ptr := mload(0x40)
                    returndatacopy(ptr, 0, returndatasize())
                    revert(ptr, returndatasize())
                }
            }
        }
    }
}

// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

import {IncorrectParameterException} from "../interfaces/IExceptions.sol";

/// @title Bit mask library
/// @notice Implements functions that manipulate bit masks
///         Bit masks are utilized extensively by Gearbox to efficiently store token sets (enabled tokens on accounts
///         or forbidden tokens) and check for set inclusion. A mask is a uint256 number that has its i-th bit set to
///         1 if i-th item is included into the set. For example, each token has a mask equal to 2**i, so set inclusion
///         can be checked by checking tokenMask & setMask != 0.
library BitMask {
    /// @dev Calculates the number of `1` bits
    /// @param enabledTokensMask Bit mask to compute the number of `1` bits in
    function calcEnabledTokens(uint256 enabledTokensMask) internal pure returns (uint256 totalTokensEnabled) {
        unchecked {
            while (enabledTokensMask > 0) {
                enabledTokensMask &= enabledTokensMask - 1; // U:[BM-3]
                ++totalTokensEnabled; // U:[BM-3]
            }
        }
    }

    /// @dev Enables bits from the second mask in the first mask
    /// @param enabledTokenMask The initial mask
    /// @param bitsToEnable Mask of bits to enable
    function enable(uint256 enabledTokenMask, uint256 bitsToEnable) internal pure returns (uint256) {
        return enabledTokenMask | bitsToEnable; // U:[BM-4]
    }

    /// @dev Disables bits from the second mask in the first mask
    /// @param enabledTokenMask The initial mask
    /// @param bitsToDisable Mask of bits to disable
    function disable(uint256 enabledTokenMask, uint256 bitsToDisable) internal pure returns (uint256) {
        return enabledTokenMask & ~bitsToDisable; // U:[BM-4]
    }

    /// @dev Computes a new mask with sets of new enabled and disabled bits
    /// @dev bitsToEnable and bitsToDisable are applied sequentially to original mask
    /// @param enabledTokensMask The initial mask
    /// @param bitsToEnable Mask with bits to enable
    /// @param bitsToDisable Mask with bits to disable
    function enableDisable(uint256 enabledTokensMask, uint256 bitsToEnable, uint256 bitsToDisable)
        internal
        pure
        returns (uint256)
    {
        return (enabledTokensMask | bitsToEnable) & (~bitsToDisable); // U:[BM-5]
    }

    /// @dev Returns a mask with only the least significant bit of `mask` enabled
    /// @dev This function can be used to efficiently iterate over enabled bits in a mask
    function lsbMask(uint256 mask) internal pure returns (uint256) {
        unchecked {
            return mask & uint256(-int256(mask)); // U:[BM-6]
        }
    }
}

File 31 of 37 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

// EIP-2612 is Final as of 2022-11-01. This file is deprecated.

import "./IERC20Permit.sol";

File 32 of 37 : IDaiLikePermit.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IDaiLikePermit {
    function permit(
        address holder,
        address spender,
        uint256 nonce,
        uint256 expiry,
        bool allowed,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IPermit2 {
    struct PermitDetails {
        // ERC20 token address
        address token;
        // the maximum amount allowed to spend
        uint160 amount;
        // timestamp at which a spender's token allowances become invalid
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }
    /// @notice The permit message signed for a single token allownce
    struct PermitSingle {
        // the permit data for a single token alownce
        PermitDetails details;
        // address permissioned on the allowed tokens
        address spender;
        // deadline on the permit signature
        uint256 sigDeadline;
    }
    /// @notice Packed allowance
    struct PackedAllowance {
        // amount allowed
        uint160 amount;
        // permission expiry
        uint48 expiration;
        // an incrementing value indexed per owner,token,and spender for each signature
        uint48 nonce;
    }

    function transferFrom(address user, address spender, uint160 amount, address token) external;

    function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external;

    function allowance(address user, address token, address spender) external view returns (PackedAllowance memory);
}

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IWETH is IERC20 {
    event Deposit(address indexed dst, uint wad);

    event Withdrawal(address indexed src, uint wad);

    function deposit() external payable;

    function withdraw(uint256 amount) external;
}

File 35 of 37 : RevertReasonForwarder.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @title Revert reason forwarder.
library RevertReasonForwarder {
    /// @dev Forwards latest externall call revert.
    function reRevert() internal pure {
        // bubble up revert reason from latest external call
        assembly ("memory-safe") { // solhint-disable-line no-inline-assembly
            let ptr := mload(0x40)
            returndatacopy(ptr, 0, returndatasize())
            revert(ptr, returndatasize())
        }
    }
}

File 36 of 37 : IExceptions.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2024.
pragma solidity ^0.8.17;

// ------- //
// GENERAL //
// ------- //

/// @notice Thrown on attempting to set an important address to zero address
error ZeroAddressException();

/// @notice Thrown when attempting to pass a zero amount to a funding-related operation
error AmountCantBeZeroException();

/// @notice Thrown on incorrect input parameter
error IncorrectParameterException();

/// @notice Thrown when balance is insufficient to perform an operation
error InsufficientBalanceException();

/// @notice Thrown if parameter is out of range
error ValueOutOfRangeException();

/// @notice Thrown when trying to send ETH to a contract that is not allowed to receive ETH directly
error ReceiveIsNotAllowedException();

/// @notice Thrown on attempting to set an EOA as an important contract in the system
error AddressIsNotContractException(address);

/// @notice Thrown on attempting to receive a token that is not a collateral token or was forbidden
error TokenNotAllowedException();

/// @notice Thrown on attempting to add a token that is already in a collateral list
error TokenAlreadyAddedException();

/// @notice Thrown when attempting to use quota-related logic for a token that is not quoted in quota keeper
error TokenIsNotQuotedException();

/// @notice Thrown on attempting to interact with an address that is not a valid target contract
error TargetContractNotAllowedException();

/// @notice Thrown if function is not implemented
error NotImplementedException();

// ------------------ //
// CONTRACTS REGISTER //
// ------------------ //

/// @notice Thrown when an address is expected to be a registered credit manager, but is not
error RegisteredCreditManagerOnlyException();

/// @notice Thrown when an address is expected to be a registered pool, but is not
error RegisteredPoolOnlyException();

// ---------------- //
// ADDRESS PROVIDER //
// ---------------- //

/// @notice Reverts if address key isn't found in address provider
error AddressNotFoundException();

// ----------------- //
// POOL, PQK, GAUGES //
// ----------------- //

/// @notice Thrown by pool-adjacent contracts when a credit manager being connected has a wrong pool address
error IncompatibleCreditManagerException();

/// @notice Thrown when attempting to set an incompatible successor staking contract
error IncompatibleSuccessorException();

/// @notice Thrown when attempting to vote in a non-approved contract
error VotingContractNotAllowedException();

/// @notice Thrown when attempting to unvote more votes than there are
error InsufficientVotesException();

/// @notice Thrown when attempting to borrow more than the second point on a two-point curve
error BorrowingMoreThanU2ForbiddenException();

/// @notice Thrown when a credit manager attempts to borrow more than its limit in the current block, or in general
error CreditManagerCantBorrowException();

/// @notice Thrown when attempting to connect a quota keeper to an incompatible pool
error IncompatiblePoolQuotaKeeperException();

/// @notice Thrown when attempting to connect a gauge to an incompatible pool quota keeper
error IncompatibleGaugeException();

/// @notice Thrown when the quota is outside of min/max bounds
error QuotaIsOutOfBoundsException();

// -------------- //
// CREDIT MANAGER //
// -------------- //

/// @notice Thrown on failing a full collateral check after multicall
error NotEnoughCollateralException();

/// @notice Thrown if an attempt to approve a collateral token to adapter's target contract fails
error AllowanceFailedException();

/// @notice Thrown on attempting to perform an action for a credit account that does not exist
error CreditAccountDoesNotExistException();

/// @notice Thrown on configurator attempting to add more than 255 collateral tokens
error TooManyTokensException();

/// @notice Thrown if more than the maximum number of tokens were enabled on a credit account
error TooManyEnabledTokensException();

/// @notice Thrown when attempting to execute a protocol interaction without active credit account set
error ActiveCreditAccountNotSetException();

/// @notice Thrown when trying to update credit account's debt more than once in the same block
error DebtUpdatedTwiceInOneBlockException();

/// @notice Thrown when trying to repay all debt while having active quotas
error DebtToZeroWithActiveQuotasException();

/// @notice Thrown when a zero-debt account attempts to update quota
error UpdateQuotaOnZeroDebtAccountException();

/// @notice Thrown when attempting to close an account with non-zero debt
error CloseAccountWithNonZeroDebtException();

/// @notice Thrown when value of funds remaining on the account after liquidation is insufficient
error InsufficientRemainingFundsException();

/// @notice Thrown when Credit Facade tries to write over a non-zero active Credit Account
error ActiveCreditAccountOverridenException();

// ------------------- //
// CREDIT CONFIGURATOR //
// ------------------- //

/// @notice Thrown on attempting to use a non-ERC20 contract or an EOA as a token
error IncorrectTokenContractException();

/// @notice Thrown if the newly set LT if zero or greater than the underlying's LT
error IncorrectLiquidationThresholdException();

/// @notice Thrown if borrowing limits are incorrect: minLimit > maxLimit or maxLimit > blockLimit
error IncorrectLimitsException();

/// @notice Thrown if the new expiration date is less than the current expiration date or current timestamp
error IncorrectExpirationDateException();

/// @notice Thrown if a contract returns a wrong credit manager or reverts when trying to retrieve it
error IncompatibleContractException();

/// @notice Thrown if attempting to forbid an adapter that is not registered in the credit manager
error AdapterIsNotRegisteredException();

/// @notice Thrown if new credit configurator's set of allowed adapters differs from the current one
error IncorrectAdaptersSetException();

/// @notice Thrown if attempting to schedule a token's LT ramping that is too short in duration
error RampDurationTooShortException();

/// @notice Thrown if attempting to set liquidation fees such that the sum of premium and fee changes
error InconsistentLiquidationFeesException();

/// @notice Thrown if attempting to set expired liquidation fees such that the sum of premium and fee changes
error InconsistentExpiredLiquidationFeesException();

// ------------- //
// CREDIT FACADE //
// ------------- //

/// @notice Thrown when attempting to perform an action that is forbidden in whitelisted mode
error ForbiddenInWhitelistedModeException();

/// @notice Thrown if credit facade is not expirable, and attempted aciton requires expirability
error NotAllowedWhenNotExpirableException();

/// @notice Thrown if a selector that doesn't match any allowed function is passed to the credit facade in a multicall
error UnknownMethodException(bytes4 selector);

/// @notice Thrown if a liquidator tries to liquidate an account with a health factor above 1
error CreditAccountNotLiquidatableException();

/// @notice Thrown if a liquidator tries to liquidate an account with loss but violates the loss policy
error CreditAccountNotLiquidatableWithLossException();

/// @notice Thrown if too much new debt was taken within a single block
error BorrowedBlockLimitException();

/// @notice Thrown if the new debt principal for a credit account falls outside of borrowing limits
error BorrowAmountOutOfLimitsException();

/// @notice Thrown if a user attempts to open an account via an expired credit facade
error NotAllowedAfterExpirationException();

/// @notice Thrown if expected balances are attempted to be set twice without performing a slippage check
error ExpectedBalancesAlreadySetException();

/// @notice Thrown if attempting to perform a slippage check when excepted balances are not set
error ExpectedBalancesNotSetException();

/// @notice Thrown if balance of at least one token is less than expected during a slippage check
error BalanceLessThanExpectedException(address token);

/// @notice Thrown when trying to perform an action that is forbidden when credit account has enabled forbidden tokens
error ForbiddenTokensException(uint256 forbiddenTokensMask);

/// @notice Thrown when forbidden token quota is increased during the multicall
error ForbiddenTokenQuotaIncreasedException(address token);

/// @notice Thrown when enabled forbidden token balance is increased during the multicall
error ForbiddenTokenBalanceIncreasedException(address token);

/// @notice Thrown when the remaining token balance is increased during the liquidation
error RemainingTokenBalanceIncreasedException(address token);

/// @notice Thrown if `botMulticall` is called by an address that is not approved by account owner or is forbidden
error NotApprovedBotException(address bot);

/// @notice Thrown when attempting to perform a multicall action with no permission for it
error NoPermissionException(uint256 permission);

/// @notice Thrown when attempting to give a bot unexpected permissions
error UnexpectedPermissionsException(uint256 permissions);

/// @notice Thrown when a custom HF parameter lower than 10000 is passed into the full collateral check
error CustomHealthFactorTooLowException();

/// @notice Thrown when submitted collateral hint is not a valid token mask
error InvalidCollateralHintException(uint256 mask);

/// @notice Thrown when trying to seize underlying token during partial liquidation
error UnderlyingIsNotLiquidatableException();

/// @notice Thrown when amount of collateral seized during partial liquidation is less than required
error SeizedLessThanRequiredException(uint256 seizedAmount);

// ------ //
// ACCESS //
// ------ //

/// @notice Thrown on attempting to call an access restricted function not as credit account owner
error CallerNotCreditAccountOwnerException();

/// @notice Thrown on attempting to call an access restricted function not as configurator
error CallerNotConfiguratorException();

/// @notice Thrown on attempting to call an access-restructed function not as account factory
error CallerNotAccountFactoryException();

/// @notice Thrown on attempting to call an access restricted function not as credit manager
error CallerNotCreditManagerException();

/// @notice Thrown on attempting to call an access restricted function not as credit facade
error CallerNotCreditFacadeException();

/// @notice Thrown on attempting to pause a contract without pausable admin rights
error CallerNotPausableAdminException();

/// @notice Thrown on attempting to unpause a contract without unpausable admin rights
error CallerNotUnpausableAdminException();

/// @notice Thrown on attempting to call an access restricted function not as gauge
error CallerNotGaugeException();

/// @notice Thrown on attempting to call an access restricted function not as quota keeper
error CallerNotPoolQuotaKeeperException();

/// @notice Thrown on attempting to call an access restricted function not as voter
error CallerNotVoterException();

/// @notice Thrown on attempting to call an access restricted function not as allowed adapter
error CallerNotAdapterException();

/// @notice Thrown on attempting to call an access restricted function not as migrator
error CallerNotMigratorException();

/// @notice Thrown when an address that is not the designated executor attempts to execute a transaction
error CallerNotExecutorException();

/// @notice Thrown on attempting to call an access restricted function not as veto admin
error CallerNotVetoAdminException();

// -------- //
// BOT LIST //
// -------- //

/// @notice Thrown when attempting to set non-zero permissions for a forbidden bot
error InvalidBotException();

/// @notice Thrown when attempting to set permissions for a bot that don't meet its requirements
error IncorrectBotPermissionsException();

/// @notice Thrown when attempting to set non-zero permissions for too many bots
error TooManyActiveBotsException();

// --------------- //
// ACCOUNT FACTORY //
// --------------- //

/// @notice Thrown when trying to deploy second master credit account for a credit manager
error MasterCreditAccountAlreadyDeployedException();

/// @notice Thrown when trying to rescue funds from a credit account that is currently in use
error CreditAccountIsInUseException();

// ------------ //
// PRICE ORACLE //
// ------------ //

/// @notice Thrown on attempting to set a token price feed to an address that is not a correct price feed
error IncorrectPriceFeedException();

/// @notice Thrown on attempting to interact with a price feed for a token not added to the price oracle
error PriceFeedDoesNotExistException();

/// @notice Thrown when trying to apply an on-demand price update to a non-updatable price feed
error PriceFeedIsNotUpdatableException();

/// @notice Thrown when price feed returns incorrect price for a token
error IncorrectPriceException();

/// @notice Thrown when token's price feed becomes stale
error StalePriceException();

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

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

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

Settings
{
  "remappings": [
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "forge-std/=lib/forge-std/src/",
    "@1inch/=lib/@1inch/",
    "@openzeppelin/=lib/@openzeppelin/",
    "@gearbox-protocol/=lib/@gearbox-protocol/",
    "@redstone-finance/=node_modules/@redstone-finance/",
    "@solady/=lib/@solady/src/",
    "erc4626-tests/=lib/@openzeppelin/lib/erc4626-tests/",
    "openzeppelin/=lib/@openzeppelin/contracts/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "none",
    "appendCBOR": true
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "shanghai",
  "viaIR": false
}

Contract Security Audit

Contract ABI

API
[{"inputs":[],"name":"contractType","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creditAccount","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"getCurrentWithdrawals","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"withdrawalPhantomToken","type":"address"},{"internalType":"uint256","name":"withdrawalTokenSpent","type":"uint256"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"isDelayed","type":"bool"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct WithdrawalOutput[]","name":"outputs","type":"tuple[]"},{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct MultiCall[]","name":"claimCalls","type":"tuple[]"}],"internalType":"struct ClaimableWithdrawal[]","name":"","type":"tuple[]"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"withdrawalPhantomToken","type":"address"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"isDelayed","type":"bool"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct WithdrawalOutput[]","name":"expectedOutputs","type":"tuple[]"},{"internalType":"uint256","name":"claimableAt","type":"uint256"}],"internalType":"struct PendingWithdrawal[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"token","type":"address"}],"name":"getWithdrawableAssets","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"withdrawalPhantomToken","type":"address"},{"internalType":"address","name":"underlying","type":"address"},{"internalType":"uint256","name":"withdrawalLength","type":"uint256"}],"internalType":"struct WithdrawableAsset[]","name":"","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"creditAccount","type":"address"},{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"withdrawalToken","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"getWithdrawalRequestResult","outputs":[{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"components":[{"internalType":"address","name":"token","type":"address"},{"internalType":"bool","name":"isDelayed","type":"bool"},{"internalType":"uint256","name":"amount","type":"uint256"}],"internalType":"struct WithdrawalOutput[]","name":"outputs","type":"tuple[]"},{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct MultiCall[]","name":"requestCalls","type":"tuple[]"},{"internalType":"uint256","name":"claimableAt","type":"uint256"}],"internalType":"struct RequestableWithdrawal","name":"requestableWithdrawal","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"version","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]

0x608060405234801561000f575f80fd5b506134098061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610064575f3560e01c80638422e25b1161004d5780638422e25b146100a9578063cb2ef6f7146100c9578063d1729e5c146100f0575f80fd5b80634809ce3b1461006857806354fd4d5014610092575b5f80fd5b61007b610076366004612821565b610110565b6040516100899291906129e0565b60405180910390f35b61009b61013681565b604051908152602001610089565b6100bc6100b7366004612aa6565b610305565b6040516100899190612af4565b61009b7f474c4f42414c3a3a4d454c4c4f575f57445f534300000000000000000000000081565b6101036100fe366004612821565b610c48565b6040516100899190612b60565b6060805f836001600160a01b0316638c3ecc456040518163ffffffff1660e01b8152600401602060405180830381865afa158015610150573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101749190612be1565b6040805160018082528183019092529192505f9190816020015b6040805160a0810182525f8082526020808301829052928201526060808201819052608082015282525f1990920191018161018e5790505090506101d3868684610dc8565b815f815181106101e5576101e5612c10565b6020026020010181905250805f8151811061020257610202612c10565b602002602001015160600151515f14806102555750805f8151811061022957610229612c10565b6020026020010151606001515f8151811061024657610246612c10565b6020026020010151604001515f145b156102ab57604080515f80825260208201909252906102a7565b6040805160a0810182525f8082526020808301829052928201526060808201819052608082015282525f1990920191018161026f5790505b5090505b5f6102b687846113ea565b90505f5b81518110156102f857868282815181106102d6576102d6612c10565b6020908102919091018101516001600160a01b039092169101526001016102ba565b5090969095509350505050565b61033d6040518060a001604052805f6001600160a01b031681526020015f815260200160608152602001606081526020015f81525090565b6001600160a01b038416808252602082018390526040517f07a2d13a000000000000000000000000000000000000000000000000000000008152600481018490525f91906307a2d13a90602401602060405180830381865afa1580156103a5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103c99190612c24565b90505f856001600160a01b0316631dcae1646040518163ffffffff1660e01b8152600401602060405180830381865afa158015610408573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061042c9190612be1565b6040517ffc59ca2b0000000000000000000000000000000000000000000000000000000081526001600160a01b038881166004830152602482018590529192505f9183169063fc59ca2b906044015f60405180830381865afa158015610494573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526104bb9190810190612cfe565b9050825f5b825181101561063b575f896001600160a01b0316639bd0911b8584815181106104eb576104eb612c10565b60200260200101515f01516040518263ffffffff1660e01b815260040161051491815260200190565b606060405180830381865afa15801561052f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105539190612dbb565b90505f8151600281111561056957610569612e10565b036105c55783828151811061058057610580612c10565b60200260200101516040015184838151811061059e5761059e612c10565b6020026020010151606001516105b49190612e38565b6105be9084612e4b565b9250610632565b6001815160028111156105da576105da612e10565b03610632578382815181106105f1576105f1612c10565b60200260200101516040015184838151811061060f5761060f612c10565b6020026020010151606001516106259190612e38565b61062f9084612e4b565b92505b506001016104c0565b508381101561078c576040805160028082526060820190925290816020015b604080516060810182525f80825260208083018290529282015282525f1990920191018161065a5790505085604001819052506040518060600160405280896001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106d4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106f89190612be1565b6001600160a01b031681526020015f151581526020018281525085604001515f8151811061072857610728612c10565b60200260200101819052506040518060600160405280886001600160a01b0316815260200160011515815260200182866107629190612e4b565b815250856040015160018151811061077c5761077c612c10565b602002602001018190525061087b565b60408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f199092019101816107a15790505085604001819052506040518060600160405280896001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561081b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061083f9190612be1565b6001600160a01b031681526020015f151581526020018581525085604001515f8151811061086f5761086f612c10565b60200260200101819052505b6040805160028082526060820190925290816020015b604080518082019091525f8152606060208201528152602001906001900390816108915790505085606001819052505f896001600160a01b031663c12c21c06040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108fd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109219190612be1565b60405163fdd5764560e01b81526001600160a01b038b811660048301529192505f9183169063fdd5764590602401602060405180830381865afa15801561096a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061098e9190612be1565b6040805180820182526001600160a01b03831681529051602481018b90525f60448201819052606482015291925090602082019060840160408051601f198184030181529190526020810180516001600160e01b03167fba087652000000000000000000000000000000000000000000000000000000001790529052606088015180515f90610a1f57610a1f612c10565b60200260200101819052505f896001600160a01b031663d379be236040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a67573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a8b9190612be1565b60405163fdd5764560e01b81526001600160a01b0380831660048301529192505f9185169063fdd5764590602401602060405180830381865afa158015610ad4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610af89190612be1565b6040517fa55df0010000000000000000000000000000000000000000000000000000000081526001600160a01b038e811660048301529192505f9182919084169063a55df001906024015f60405180830381865afa158015610b5c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610b839190810190612ec5565b915091506040518060400160405280846001600160a01b031681526020018f8484604051602401610bb69392919061300c565b60408051601f198184030181529190526020810180516001600160e01b03167f51757e5b00000000000000000000000000000000000000000000000000000000179052905260608c015180516001908110610c1357610c13612c10565b6020026020010181905250610c278e611609565b610c319042612e38565b60808c015250505050505050505050949350505050565b60605f826001600160a01b0316638c3ecc456040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c87573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cab9190612be1565b90505f816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0e9190612be1565b6040805160018082528183019092529192505f9190816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610d285790505090506040518060800160405280846001600160a01b03168152602001866001600160a01b03168152602001836001600160a01b03168152602001610d9d85611609565b815250815f81518110610db257610db2612c10565b6020908102919091010152925050505b92915050565b6040805160a0810182525f8082526020820181905291810191909152606080820181905260808201525f826001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e2e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e529190612be1565b6001600160a01b03848116845285166020840152604080516001808252818301909252919250816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181610e7d5790505082606001819052506040518060600160405280826001600160a01b031681526020015f151581526020015f81525082606001515f81518110610eec57610eec612c10565b60200260200101819052505f836001600160a01b031663b42b544f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f34573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f589190612c24565b90505f5b818110156110ae57604051639bd0911b60e01b8152600481018290525f906001600160a01b03871690639bd0911b90602401606060405180830381865afa158015610fa9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fcd9190612dbb565b60408101519091506001600160a01b0316610fe857506110a6565b60408082015190517fe7beaf9d0000000000000000000000000000000000000000000000000000000081526001600160a01b038a811660048301525f92169063e7beaf9d90602401602060405180830381865afa15801561104b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061106f9190612c24565b90508086606001515f8151811061108857611088612c10565b60200260200101516040018181516110a09190612e38565b90525050505b600101610f5c565b5082606001515f815181106110c5576110c5612c10565b6020026020010151604001515f036110de5750506113e3565b82606001515f815181106110f4576110f4612c10565b6020908102919091010151604090810151848201528051600180825281830190925290816020015b604080518082019091525f81526060602082015281526020019060019003908161111c5790505083608001819052505f80866001600160a01b031663d379be236040518163ffffffff1660e01b8152600401602060405180830381865afa158015611189573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111ad9190612be1565b90505f886001600160a01b031663c12c21c06040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112109190612be1565b60405163fdd5764560e01b81526001600160a01b0384811660048301529192509082169063fdd5764590602401602060405180830381865afa158015611258573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127c9190612be1565b6040517f92b8a2580000000000000000000000000000000000000000000000000000000081526001600160a01b0389811660048301528b811660248301529194505f9350839250908416906392b8a258906044015f60405180830381865afa1580156112ea573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526113119190810190612ec5565b915091506040518060400160405280846001600160a01b031681526020016382ef9d3260e01b8985858e8c606001515f8151811061135157611351612c10565b60200260200101516040015160405160240161137195949392919061303f565b60408051601f198184030181529190526020810180516001600160e01b03167fffffffff00000000000000000000000000000000000000000000000000000000909316929092179091529052608087015180515f906113d2576113d2612c10565b602002602001018190525050505050505b9392505050565b60605f826001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611429573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061144d9190612be1565b90505f836001600160a01b031663b42b544f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561148c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b09190612c24565b90505f5b8181101561160057604051639bd0911b60e01b8152600481018290525f906001600160a01b03871690639bd0911b90602401606060405180830381865afa158015611501573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115259190612dbb565b60408101519091506001600160a01b031661154057506115f8565b60408082015190517f63c6b4eb0000000000000000000000000000000000000000000000000000000081526001600160a01b0389811660048301525f9216906363c6b4eb90602401602060405180830381865afa1580156115a3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115c79190612c24565b905080156115f5576115f26115eb8989855f0151866020015187604001518b6118f8565b8790612592565b95505b50505b6001016114b4565b50505092915050565b5f805f90505f836001600160a01b031663b42b544f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561164b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061166f9190612c24565b90505f5b818110156118ef57604051639bd0911b60e01b8152600481018290525f906001600160a01b03871690639bd0911b90602401606060405180830381865afa1580156116c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116e49190612dbb565b90505f815160028111156116fa576116fa612e10565b036117ed575f4282602001516001600160a01b0316634ff0876a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611741573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117659190612c24565b83602001516001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117a5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117c99190612c24565b6117d39190612e38565b6117dd9190612e4b565b9050848111156117eb578094505b505b60018151600281111561180257611802612e10565b036118e6575f81604001516001600160a01b031663df5cf7236040518163ffffffff1660e01b8152600401602060405180830381865afa158015611848573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061186c9190612be1565b6001600160a01b031663c448feb86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118a7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118cb9190612c24565b6118d690600c613089565b9050848111156118e4578094505b505b50600101611673565b50909392505050565b60605f85600281111561190d5761190d612e10565b03611ffa576040517f5d78650e0000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301525f918291829190871690635d78650e90602401608060405180830381865afa158015611976573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a91906130a0565b935050925092505f866001600160a01b031663b97dd9e26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119de573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a029190612c24565b905080821015611a155750505050612588565b808203611c045760408051600180825281830190925290816020015b611a6b60405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b815260200190600190039081611a3157905050945089855f81518110611a9357611a93612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611ac157905050855f81518110611afe57611afe612c10565b6020026020010151604001819052505f611b1a898986856126d2565b90506040518060600160405280886001600160a01b031681526020015f1515815260200182815250865f81518110611b5457611b54612c10565b6020026020010151604001515f81518110611b7157611b71612c10565b6020026020010181905250886001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bb8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bdc9190612c24565b865f81518110611bee57611bee612c10565b6020026020010151606001818152505050611ff5565b611c0f816001612e38565b8203611ff5576040805160028082526060820190925290816020015b611c6560405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b815260200190600190039081611c2b57905050945089855f81518110611c8d57611c8d612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611cbb57905050855f81518110611cf857611cf8612c10565b6020908102919091010151604001525f611d1e898986611d19866001612e38565b6126d2565b90506040518060600160405280886001600160a01b031681526020015f1515815260200182815250865f81518110611d5857611d58612c10565b6020026020010151604001515f81518110611d7557611d75612c10565b6020026020010181905250886001600160a01b0316634ff0876a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611dbc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611de09190612c24565b896001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e1c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e409190612c24565b611e4a9190612e38565b865f81518110611e5c57611e5c612c10565b6020908102919091010151606001528415611ff3578a86600181518110611e8557611e85612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611eb35790505086600181518110611ef157611ef1612c10565b602002602001015160400181905250611f0c898987856126d2565b90506040518060600160405280886001600160a01b031681526020015f151581526020018281525086600181518110611f4757611f47612c10565b6020026020010151604001515f81518110611f6457611f64612c10565b6020026020010181905250886001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611fab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fcf9190612c24565b86600181518110611fe257611fe2612c10565b602002602001015160600181815250505b505b505050505b600185600281111561200e5761200e612e10565b03612588576040517f0a5067490000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301525f1960248301525f6044830181905260648301819052608483018190529190851690630a5067499060a4015f60405180830381865afa15801561208e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526120b591908101906130d3565b509150505f846001600160a01b0316632ee744a56040518163ffffffff1660e01b8152600401602060405180830381865afa1580156120f6573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061211a9190612c24565b9050815167ffffffffffffffff81111561213657612136612bfc565b6040519080825280602002602001820160405280156121a157816020015b61218e60405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b8152602001906001900390816121545790505b5092505f5b8251811015612584575f805f886001600160a01b03166338ceee988786815181106121d3576121d3612c10565b60200260200101518f6040518363ffffffff1660e01b815260040161220b9291909182526001600160a01b0316602082015260400190565b5f60405180830381865afa158015612225573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261224c91908101906131c2565b945094505050925084836080015163ffffffff1611801561226c57505f81115b15612576578b87858151811061228457612284612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f199092019101816122b2579050508785815181106122ef576122ef612c10565b6020026020010151604001819052505f896001600160a01b031663652676968584866040518463ffffffff1660e01b815260040161232f939291906132fe565b602060405180830381865afa15801561234a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061236e9190612c24565b90505f8a6001600160a01b0316634612edfa6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156123ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123d19190612be1565b6001600160a01b0316638f70a6de8c6001600160a01b031663a8c62e766040518163ffffffff1660e01b8152600401602060405180830381865afa15801561241b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061243f9190612be1565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e084901b1681526001600160a01b03909116600482015260248101859052604401602060405180830381865afa1580156124a0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124c49190612c24565b905060405180606001604052808b6001600160a01b031681526020015f15158152602001828152508987815181106124fe576124fe612c10565b6020026020010151604001515f8151811061251b5761251b612c10565b602002602001018190525086856080015163ffffffff1661253c9190612e4b565b61254790600c613089565b6125519042612e38565b89878151811061256357612563612c10565b6020026020010151606001818152505050505b5050508060010190506121a6565b5050505b9695505050505050565b60605f825184516125a39190612e38565b67ffffffffffffffff8111156125bb576125bb612bfc565b60405190808252806020026020018201604052801561262657816020015b61261360405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b8152602001906001900390816125d95790505b5090505f5b84518110156126735784818151811061264657612646612c10565b602002602001015182828151811061266057612660612c10565b602090810291909101015260010161262b565b505f5b83518110156126ca5783818151811061269157612691612c10565b6020026020010151828287516126a79190612e38565b815181106126b7576126b7612c10565b6020908102919091010152600101612676565b509392505050565b6040517f859e7d32000000000000000000000000000000000000000000000000000000008152600481018290525f9081906001600160a01b0386169063859e7d3290602401606060405180830381865afa158015612732573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612756919061339c565b6040517ff5e7ee0f000000000000000000000000000000000000000000000000000000008152600481018590526001600160a01b0387811660248301529192505f9188169063f5e7ee0f90604401602060405180830381865afa1580156127bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127e39190612c24565b60208301519091506127f58287613089565b6127ff91906133dd565b979650505050505050565b6001600160a01b038116811461281e575f80fd5b50565b5f8060408385031215612832575f80fd5b823561283d8161280a565b9150602083013561284d8161280a565b809150509250929050565b5f815180845260208085019450602084015f5b838110156128a857815180516001600160a01b0316885283810151151584890152604090810151908801526060909601959082019060010161286b565b509495945050505050565b5f82825180855260208086019550808260051b8401018186015f5b8481101561295157601f1986840381018a52825180516001600160a01b03168552850151604086860181905281519086018190525f905b80821015612923578282018801518783016060015290870190612905565b5f8782016060908101919091529c88019c601f909101909316909501909101935050908301906001016128ce565b5090979650505050505050565b5f82825180855260208086019550808260051b8401018186015f5b8481101561295157601f19868403018952815160806001600160a01b03808351168652808784015116878701525060408083015182828801526129be83880182612858565b6060948501519790940196909652505098840198925090830190600101612979565b5f6040808301604084528086518083526060925060608601915060608160051b8701016020808a015f5b84811015612a8657605f198a8503018652815160a06001600160a01b038083511687528086840151168688015250898201518a87015288820151818a880152612a5582880182612858565b91505060808083015192508682038188015250612a7281836128b3565b978501979550505090820190600101612a0a565b505087820390880152612a99818961295e565b9998505050505050505050565b5f805f8060808587031215612ab9575f80fd5b8435612ac48161280a565b93506020850135612ad48161280a565b92506040850135612ae48161280a565b9396929550929360600135925050565b602081526001600160a01b038251166020820152602082015160408201525f604083015160a06060840152612b2c60c0840182612858565b90506060840151601f19848303016080850152612b4982826128b3565b915050608084015160a08401528091505092915050565b602080825282518282018190525f919060409081850190868401855b82811015612bc457815180516001600160a01b039081168652878201518116888701528682015116868601526060908101519085015260809093019290850190600101612b7c565b5091979650505050505050565b8051612bdc8161280a565b919050565b5f60208284031215612bf1575f80fd5b81516113e38161280a565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215612c34575f80fd5b5051919050565b6040516080810167ffffffffffffffff81118282101715612c5e57612c5e612bfc565b60405290565b6040516060810167ffffffffffffffff81118282101715612c5e57612c5e612bfc565b60405160e0810167ffffffffffffffff81118282101715612c5e57612c5e612bfc565b604051601f8201601f1916810167ffffffffffffffff81118282101715612cd357612cd3612bfc565b604052919050565b5f67ffffffffffffffff821115612cf457612cf4612bfc565b5060051b60200190565b5f6020808385031215612d0f575f80fd5b825167ffffffffffffffff811115612d25575f80fd5b8301601f81018513612d35575f80fd5b8051612d48612d4382612cdb565b612caa565b81815260079190911b82018301908381019087831115612d66575f80fd5b928401925b828410156127ff5760808489031215612d82575f80fd5b612d8a612c3b565b8451815285850151868201526040808601519082015260608086015190820152825260809093019290840190612d6b565b5f60608284031215612dcb575f80fd5b612dd3612c64565b825160038110612de1575f80fd5b81526020830151612df18161280a565b60208201526040830151612e048161280a565b60408201529392505050565b634e487b7160e01b5f52602160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610dc257610dc2612e24565b81810381811115610dc257610dc2612e24565b5f82601f830112612e6d575f80fd5b81516020612e7d612d4383612cdb565b8083825260208201915060208460051b870101935086841115612e9e575f80fd5b602086015b84811015612eba5780518352918301918301612ea3565b509695505050505050565b5f8060408385031215612ed6575f80fd5b825167ffffffffffffffff80821115612eed575f80fd5b612ef986838701612e5e565b9350602091508185015181811115612f0f575f80fd5b8501601f81018713612f1f575f80fd5b8051612f2d612d4382612cdb565b81815260059190911b82018401908481019089831115612f4b575f80fd5b8584015b83811015612f8157805186811115612f65575f80fd5b612f738c8983890101612e5e565b845250918601918601612f4f565b508096505050505050509250929050565b5f815180845260208085019450602084015f5b838110156128a857815187529582019590820190600101612fa5565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561295157601f19868403018952612ffa838351612f92565b98840198925090830190600101612fde565b6001600160a01b0384168152606060208201525f61302d6060830185612f92565b82810360408401526125888185612fc1565b5f6001600160a01b03808816835260a0602084015261306160a0840188612f92565b83810360408501526130738188612fc1565b9590911660608401525050608001529392505050565b8082028115828204841417610dc257610dc2612e24565b5f805f80608085870312156130b3575f80fd5b505082516020840151604085015160609095015191969095509092509050565b5f805f606084860312156130e5575f80fd5b83519250602084015167ffffffffffffffff80821115613103575f80fd5b61310f87838801612e5e565b93506040860151915080821115613124575f80fd5b5061313186828701612e5e565b9150509250925092565b805163ffffffff81168114612bdc575f80fd5b5f82601f83011261315d575f80fd5b8151602061316d612d4383612cdb565b8083825260208201915060208460051b87010193508684111561318e575f80fd5b602086015b84811015612eba5780516131a68161280a565b8352918301918301613193565b80518015158114612bdc575f80fd5b5f805f805f60a086880312156131d6575f80fd5b855167ffffffffffffffff808211156131ed575f80fd5b9087019060e0828a031215613200575f80fd5b613208612c87565b61321183612bd1565b815261321f60208401612bd1565b602082015261323060408401612bd1565b60408201526060830151606082015261324b6080840161313b565b608082015260a083015182811115613261575f80fd5b61326d8b82860161314e565b60a08301525060c083015182811115613284575f80fd5b6132908b828601612e5e565b60c08301525096506132a7915050602087016131b3565b6040870151606088015160809098015196999198509695945092505050565b5f815180845260208085019450602084015f5b838110156128a85781516001600160a01b0316875295820195908201906001016132d9565b606081525f6001600160a01b038086511660608401528060208701511660808401528060408701511660a084015250606085015160c0830152608085015161334e60e084018263ffffffff169052565b5060a085015160e061010084015261336a6101408401826132c6565b905060c0860151605f19848303016101208501526133888282612f92565b602085019690965250505060400152919050565b5f606082840312156133ac575f80fd5b6133b4612c64565b6133bd836131b3565b815260208301516020820152604083015160408201528091505092915050565b5f826133f757634e487b7160e01b5f52601260045260245ffd5b50049056fea164736f6c6343000817000a

Deployed Bytecode

0x608060405234801561000f575f80fd5b5060043610610064575f3560e01c80638422e25b1161004d5780638422e25b146100a9578063cb2ef6f7146100c9578063d1729e5c146100f0575f80fd5b80634809ce3b1461006857806354fd4d5014610092575b5f80fd5b61007b610076366004612821565b610110565b6040516100899291906129e0565b60405180910390f35b61009b61013681565b604051908152602001610089565b6100bc6100b7366004612aa6565b610305565b6040516100899190612af4565b61009b7f474c4f42414c3a3a4d454c4c4f575f57445f534300000000000000000000000081565b6101036100fe366004612821565b610c48565b6040516100899190612b60565b6060805f836001600160a01b0316638c3ecc456040518163ffffffff1660e01b8152600401602060405180830381865afa158015610150573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906101749190612be1565b6040805160018082528183019092529192505f9190816020015b6040805160a0810182525f8082526020808301829052928201526060808201819052608082015282525f1990920191018161018e5790505090506101d3868684610dc8565b815f815181106101e5576101e5612c10565b6020026020010181905250805f8151811061020257610202612c10565b602002602001015160600151515f14806102555750805f8151811061022957610229612c10565b6020026020010151606001515f8151811061024657610246612c10565b6020026020010151604001515f145b156102ab57604080515f80825260208201909252906102a7565b6040805160a0810182525f8082526020808301829052928201526060808201819052608082015282525f1990920191018161026f5790505b5090505b5f6102b687846113ea565b90505f5b81518110156102f857868282815181106102d6576102d6612c10565b6020908102919091018101516001600160a01b039092169101526001016102ba565b5090969095509350505050565b61033d6040518060a001604052805f6001600160a01b031681526020015f815260200160608152602001606081526020015f81525090565b6001600160a01b038416808252602082018390526040517f07a2d13a000000000000000000000000000000000000000000000000000000008152600481018490525f91906307a2d13a90602401602060405180830381865afa1580156103a5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906103c99190612c24565b90505f856001600160a01b0316631dcae1646040518163ffffffff1660e01b8152600401602060405180830381865afa158015610408573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061042c9190612be1565b6040517ffc59ca2b0000000000000000000000000000000000000000000000000000000081526001600160a01b038881166004830152602482018590529192505f9183169063fc59ca2b906044015f60405180830381865afa158015610494573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526104bb9190810190612cfe565b9050825f5b825181101561063b575f896001600160a01b0316639bd0911b8584815181106104eb576104eb612c10565b60200260200101515f01516040518263ffffffff1660e01b815260040161051491815260200190565b606060405180830381865afa15801561052f573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906105539190612dbb565b90505f8151600281111561056957610569612e10565b036105c55783828151811061058057610580612c10565b60200260200101516040015184838151811061059e5761059e612c10565b6020026020010151606001516105b49190612e38565b6105be9084612e4b565b9250610632565b6001815160028111156105da576105da612e10565b03610632578382815181106105f1576105f1612c10565b60200260200101516040015184838151811061060f5761060f612c10565b6020026020010151606001516106259190612e38565b61062f9084612e4b565b92505b506001016104c0565b508381101561078c576040805160028082526060820190925290816020015b604080516060810182525f80825260208083018290529282015282525f1990920191018161065a5790505085604001819052506040518060600160405280896001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106d4573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906106f89190612be1565b6001600160a01b031681526020015f151581526020018281525085604001515f8151811061072857610728612c10565b60200260200101819052506040518060600160405280886001600160a01b0316815260200160011515815260200182866107629190612e4b565b815250856040015160018151811061077c5761077c612c10565b602002602001018190525061087b565b60408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f199092019101816107a15790505085604001819052506040518060600160405280896001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561081b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061083f9190612be1565b6001600160a01b031681526020015f151581526020018581525085604001515f8151811061086f5761086f612c10565b60200260200101819052505b6040805160028082526060820190925290816020015b604080518082019091525f8152606060208201528152602001906001900390816108915790505085606001819052505f896001600160a01b031663c12c21c06040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108fd573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109219190612be1565b60405163fdd5764560e01b81526001600160a01b038b811660048301529192505f9183169063fdd5764590602401602060405180830381865afa15801561096a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061098e9190612be1565b6040805180820182526001600160a01b03831681529051602481018b90525f60448201819052606482015291925090602082019060840160408051601f198184030181529190526020810180516001600160e01b03167fba087652000000000000000000000000000000000000000000000000000000001790529052606088015180515f90610a1f57610a1f612c10565b60200260200101819052505f896001600160a01b031663d379be236040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a67573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610a8b9190612be1565b60405163fdd5764560e01b81526001600160a01b0380831660048301529192505f9185169063fdd5764590602401602060405180830381865afa158015610ad4573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610af89190612be1565b6040517fa55df0010000000000000000000000000000000000000000000000000000000081526001600160a01b038e811660048301529192505f9182919084169063a55df001906024015f60405180830381865afa158015610b5c573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052610b839190810190612ec5565b915091506040518060400160405280846001600160a01b031681526020018f8484604051602401610bb69392919061300c565b60408051601f198184030181529190526020810180516001600160e01b03167f51757e5b00000000000000000000000000000000000000000000000000000000179052905260608c015180516001908110610c1357610c13612c10565b6020026020010181905250610c278e611609565b610c319042612e38565b60808c015250505050505050505050949350505050565b60605f826001600160a01b0316638c3ecc456040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c87573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610cab9190612be1565b90505f816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610cea573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d0e9190612be1565b6040805160018082528183019092529192505f9190816020015b604080516080810182525f8082526020808301829052928201819052606082015282525f19909201910181610d285790505090506040518060800160405280846001600160a01b03168152602001866001600160a01b03168152602001836001600160a01b03168152602001610d9d85611609565b815250815f81518110610db257610db2612c10565b6020908102919091010152925050505b92915050565b6040805160a0810182525f8082526020820181905291810191909152606080820181905260808201525f826001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e2e573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e529190612be1565b6001600160a01b03848116845285166020840152604080516001808252818301909252919250816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181610e7d5790505082606001819052506040518060600160405280826001600160a01b031681526020015f151581526020015f81525082606001515f81518110610eec57610eec612c10565b60200260200101819052505f836001600160a01b031663b42b544f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f34573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f589190612c24565b90505f5b818110156110ae57604051639bd0911b60e01b8152600481018290525f906001600160a01b03871690639bd0911b90602401606060405180830381865afa158015610fa9573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610fcd9190612dbb565b60408101519091506001600160a01b0316610fe857506110a6565b60408082015190517fe7beaf9d0000000000000000000000000000000000000000000000000000000081526001600160a01b038a811660048301525f92169063e7beaf9d90602401602060405180830381865afa15801561104b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061106f9190612c24565b90508086606001515f8151811061108857611088612c10565b60200260200101516040018181516110a09190612e38565b90525050505b600101610f5c565b5082606001515f815181106110c5576110c5612c10565b6020026020010151604001515f036110de5750506113e3565b82606001515f815181106110f4576110f4612c10565b6020908102919091010151604090810151848201528051600180825281830190925290816020015b604080518082019091525f81526060602082015281526020019060019003908161111c5790505083608001819052505f80866001600160a01b031663d379be236040518163ffffffff1660e01b8152600401602060405180830381865afa158015611189573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111ad9190612be1565b90505f886001600160a01b031663c12c21c06040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111ec573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112109190612be1565b60405163fdd5764560e01b81526001600160a01b0384811660048301529192509082169063fdd5764590602401602060405180830381865afa158015611258573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127c9190612be1565b6040517f92b8a2580000000000000000000000000000000000000000000000000000000081526001600160a01b0389811660048301528b811660248301529194505f9350839250908416906392b8a258906044015f60405180830381865afa1580156112ea573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526113119190810190612ec5565b915091506040518060400160405280846001600160a01b031681526020016382ef9d3260e01b8985858e8c606001515f8151811061135157611351612c10565b60200260200101516040015160405160240161137195949392919061303f565b60408051601f198184030181529190526020810180516001600160e01b03167fffffffff00000000000000000000000000000000000000000000000000000000909316929092179091529052608087015180515f906113d2576113d2612c10565b602002602001018190525050505050505b9392505050565b60605f826001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611429573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061144d9190612be1565b90505f836001600160a01b031663b42b544f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561148c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906114b09190612c24565b90505f5b8181101561160057604051639bd0911b60e01b8152600481018290525f906001600160a01b03871690639bd0911b90602401606060405180830381865afa158015611501573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115259190612dbb565b60408101519091506001600160a01b031661154057506115f8565b60408082015190517f63c6b4eb0000000000000000000000000000000000000000000000000000000081526001600160a01b0389811660048301525f9216906363c6b4eb90602401602060405180830381865afa1580156115a3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906115c79190612c24565b905080156115f5576115f26115eb8989855f0151866020015187604001518b6118f8565b8790612592565b95505b50505b6001016114b4565b50505092915050565b5f805f90505f836001600160a01b031663b42b544f6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561164b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061166f9190612c24565b90505f5b818110156118ef57604051639bd0911b60e01b8152600481018290525f906001600160a01b03871690639bd0911b90602401606060405180830381865afa1580156116c0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906116e49190612dbb565b90505f815160028111156116fa576116fa612e10565b036117ed575f4282602001516001600160a01b0316634ff0876a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611741573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117659190612c24565b83602001516001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156117a5573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906117c99190612c24565b6117d39190612e38565b6117dd9190612e4b565b9050848111156117eb578094505b505b60018151600281111561180257611802612e10565b036118e6575f81604001516001600160a01b031663df5cf7236040518163ffffffff1660e01b8152600401602060405180830381865afa158015611848573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061186c9190612be1565b6001600160a01b031663c448feb86040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118a7573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906118cb9190612c24565b6118d690600c613089565b9050848111156118e4578094505b505b50600101611673565b50909392505050565b60605f85600281111561190d5761190d612e10565b03611ffa576040517f5d78650e0000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301525f918291829190871690635d78650e90602401608060405180830381865afa158015611976573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061199a91906130a0565b935050925092505f866001600160a01b031663b97dd9e26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119de573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611a029190612c24565b905080821015611a155750505050612588565b808203611c045760408051600180825281830190925290816020015b611a6b60405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b815260200190600190039081611a3157905050945089855f81518110611a9357611a93612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611ac157905050855f81518110611afe57611afe612c10565b6020026020010151604001819052505f611b1a898986856126d2565b90506040518060600160405280886001600160a01b031681526020015f1515815260200182815250865f81518110611b5457611b54612c10565b6020026020010151604001515f81518110611b7157611b71612c10565b6020026020010181905250886001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611bb8573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611bdc9190612c24565b865f81518110611bee57611bee612c10565b6020026020010151606001818152505050611ff5565b611c0f816001612e38565b8203611ff5576040805160028082526060820190925290816020015b611c6560405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b815260200190600190039081611c2b57905050945089855f81518110611c8d57611c8d612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611cbb57905050855f81518110611cf857611cf8612c10565b6020908102919091010151604001525f611d1e898986611d19866001612e38565b6126d2565b90506040518060600160405280886001600160a01b031681526020015f1515815260200182815250865f81518110611d5857611d58612c10565b6020026020010151604001515f81518110611d7557611d75612c10565b6020026020010181905250886001600160a01b0316634ff0876a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611dbc573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611de09190612c24565b896001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e1c573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611e409190612c24565b611e4a9190612e38565b865f81518110611e5c57611e5c612c10565b6020908102919091010151606001528415611ff3578a86600181518110611e8557611e85612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f19909201910181611eb35790505086600181518110611ef157611ef1612c10565b602002602001015160400181905250611f0c898987856126d2565b90506040518060600160405280886001600160a01b031681526020015f151581526020018281525086600181518110611f4757611f47612c10565b6020026020010151604001515f81518110611f6457611f64612c10565b6020026020010181905250886001600160a01b03166373790ab36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611fab573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611fcf9190612c24565b86600181518110611fe257611fe2612c10565b602002602001015160600181815250505b505b505050505b600185600281111561200e5761200e612e10565b03612588576040517f0a5067490000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301525f1960248301525f6044830181905260648301819052608483018190529190851690630a5067499060a4015f60405180830381865afa15801561208e573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f191682016040526120b591908101906130d3565b509150505f846001600160a01b0316632ee744a56040518163ffffffff1660e01b8152600401602060405180830381865afa1580156120f6573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061211a9190612c24565b9050815167ffffffffffffffff81111561213657612136612bfc565b6040519080825280602002602001820160405280156121a157816020015b61218e60405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b8152602001906001900390816121545790505b5092505f5b8251811015612584575f805f886001600160a01b03166338ceee988786815181106121d3576121d3612c10565b60200260200101518f6040518363ffffffff1660e01b815260040161220b9291909182526001600160a01b0316602082015260400190565b5f60405180830381865afa158015612225573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f1916820160405261224c91908101906131c2565b945094505050925084836080015163ffffffff1611801561226c57505f81115b15612576578b87858151811061228457612284612c10565b60209081029190910101516001600160a01b0391909116905260408051600180825281830190925290816020015b604080516060810182525f80825260208083018290529282015282525f199092019101816122b2579050508785815181106122ef576122ef612c10565b6020026020010151604001819052505f896001600160a01b031663652676968584866040518463ffffffff1660e01b815260040161232f939291906132fe565b602060405180830381865afa15801561234a573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061236e9190612c24565b90505f8a6001600160a01b0316634612edfa6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156123ad573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906123d19190612be1565b6001600160a01b0316638f70a6de8c6001600160a01b031663a8c62e766040518163ffffffff1660e01b8152600401602060405180830381865afa15801561241b573d5f803e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061243f9190612be1565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e084901b1681526001600160a01b03909116600482015260248101859052604401602060405180830381865afa1580156124a0573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906124c49190612c24565b905060405180606001604052808b6001600160a01b031681526020015f15158152602001828152508987815181106124fe576124fe612c10565b6020026020010151604001515f8151811061251b5761251b612c10565b602002602001018190525086856080015163ffffffff1661253c9190612e4b565b61254790600c613089565b6125519042612e38565b89878151811061256357612563612c10565b6020026020010151606001818152505050505b5050508060010190506121a6565b5050505b9695505050505050565b60605f825184516125a39190612e38565b67ffffffffffffffff8111156125bb576125bb612bfc565b60405190808252806020026020018201604052801561262657816020015b61261360405180608001604052805f6001600160a01b031681526020015f6001600160a01b03168152602001606081526020015f81525090565b8152602001906001900390816125d95790505b5090505f5b84518110156126735784818151811061264657612646612c10565b602002602001015182828151811061266057612660612c10565b602090810291909101015260010161262b565b505f5b83518110156126ca5783818151811061269157612691612c10565b6020026020010151828287516126a79190612e38565b815181106126b7576126b7612c10565b6020908102919091010152600101612676565b509392505050565b6040517f859e7d32000000000000000000000000000000000000000000000000000000008152600481018290525f9081906001600160a01b0386169063859e7d3290602401606060405180830381865afa158015612732573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612756919061339c565b6040517ff5e7ee0f000000000000000000000000000000000000000000000000000000008152600481018590526001600160a01b0387811660248301529192505f9188169063f5e7ee0f90604401602060405180830381865afa1580156127bf573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906127e39190612c24565b60208301519091506127f58287613089565b6127ff91906133dd565b979650505050505050565b6001600160a01b038116811461281e575f80fd5b50565b5f8060408385031215612832575f80fd5b823561283d8161280a565b9150602083013561284d8161280a565b809150509250929050565b5f815180845260208085019450602084015f5b838110156128a857815180516001600160a01b0316885283810151151584890152604090810151908801526060909601959082019060010161286b565b509495945050505050565b5f82825180855260208086019550808260051b8401018186015f5b8481101561295157601f1986840381018a52825180516001600160a01b03168552850151604086860181905281519086018190525f905b80821015612923578282018801518783016060015290870190612905565b5f8782016060908101919091529c88019c601f909101909316909501909101935050908301906001016128ce565b5090979650505050505050565b5f82825180855260208086019550808260051b8401018186015f5b8481101561295157601f19868403018952815160806001600160a01b03808351168652808784015116878701525060408083015182828801526129be83880182612858565b6060948501519790940196909652505098840198925090830190600101612979565b5f6040808301604084528086518083526060925060608601915060608160051b8701016020808a015f5b84811015612a8657605f198a8503018652815160a06001600160a01b038083511687528086840151168688015250898201518a87015288820151818a880152612a5582880182612858565b91505060808083015192508682038188015250612a7281836128b3565b978501979550505090820190600101612a0a565b505087820390880152612a99818961295e565b9998505050505050505050565b5f805f8060808587031215612ab9575f80fd5b8435612ac48161280a565b93506020850135612ad48161280a565b92506040850135612ae48161280a565b9396929550929360600135925050565b602081526001600160a01b038251166020820152602082015160408201525f604083015160a06060840152612b2c60c0840182612858565b90506060840151601f19848303016080850152612b4982826128b3565b915050608084015160a08401528091505092915050565b602080825282518282018190525f919060409081850190868401855b82811015612bc457815180516001600160a01b039081168652878201518116888701528682015116868601526060908101519085015260809093019290850190600101612b7c565b5091979650505050505050565b8051612bdc8161280a565b919050565b5f60208284031215612bf1575f80fd5b81516113e38161280a565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f52603260045260245ffd5b5f60208284031215612c34575f80fd5b5051919050565b6040516080810167ffffffffffffffff81118282101715612c5e57612c5e612bfc565b60405290565b6040516060810167ffffffffffffffff81118282101715612c5e57612c5e612bfc565b60405160e0810167ffffffffffffffff81118282101715612c5e57612c5e612bfc565b604051601f8201601f1916810167ffffffffffffffff81118282101715612cd357612cd3612bfc565b604052919050565b5f67ffffffffffffffff821115612cf457612cf4612bfc565b5060051b60200190565b5f6020808385031215612d0f575f80fd5b825167ffffffffffffffff811115612d25575f80fd5b8301601f81018513612d35575f80fd5b8051612d48612d4382612cdb565b612caa565b81815260079190911b82018301908381019087831115612d66575f80fd5b928401925b828410156127ff5760808489031215612d82575f80fd5b612d8a612c3b565b8451815285850151868201526040808601519082015260608086015190820152825260809093019290840190612d6b565b5f60608284031215612dcb575f80fd5b612dd3612c64565b825160038110612de1575f80fd5b81526020830151612df18161280a565b60208201526040830151612e048161280a565b60408201529392505050565b634e487b7160e01b5f52602160045260245ffd5b634e487b7160e01b5f52601160045260245ffd5b80820180821115610dc257610dc2612e24565b81810381811115610dc257610dc2612e24565b5f82601f830112612e6d575f80fd5b81516020612e7d612d4383612cdb565b8083825260208201915060208460051b870101935086841115612e9e575f80fd5b602086015b84811015612eba5780518352918301918301612ea3565b509695505050505050565b5f8060408385031215612ed6575f80fd5b825167ffffffffffffffff80821115612eed575f80fd5b612ef986838701612e5e565b9350602091508185015181811115612f0f575f80fd5b8501601f81018713612f1f575f80fd5b8051612f2d612d4382612cdb565b81815260059190911b82018401908481019089831115612f4b575f80fd5b8584015b83811015612f8157805186811115612f65575f80fd5b612f738c8983890101612e5e565b845250918601918601612f4f565b508096505050505050509250929050565b5f815180845260208085019450602084015f5b838110156128a857815187529582019590820190600101612fa5565b5f8282518085526020808601955060208260051b840101602086015f5b8481101561295157601f19868403018952612ffa838351612f92565b98840198925090830190600101612fde565b6001600160a01b0384168152606060208201525f61302d6060830185612f92565b82810360408401526125888185612fc1565b5f6001600160a01b03808816835260a0602084015261306160a0840188612f92565b83810360408501526130738188612fc1565b9590911660608401525050608001529392505050565b8082028115828204841417610dc257610dc2612e24565b5f805f80608085870312156130b3575f80fd5b505082516020840151604085015160609095015191969095509092509050565b5f805f606084860312156130e5575f80fd5b83519250602084015167ffffffffffffffff80821115613103575f80fd5b61310f87838801612e5e565b93506040860151915080821115613124575f80fd5b5061313186828701612e5e565b9150509250925092565b805163ffffffff81168114612bdc575f80fd5b5f82601f83011261315d575f80fd5b8151602061316d612d4383612cdb565b8083825260208201915060208460051b87010193508684111561318e575f80fd5b602086015b84811015612eba5780516131a68161280a565b8352918301918301613193565b80518015158114612bdc575f80fd5b5f805f805f60a086880312156131d6575f80fd5b855167ffffffffffffffff808211156131ed575f80fd5b9087019060e0828a031215613200575f80fd5b613208612c87565b61321183612bd1565b815261321f60208401612bd1565b602082015261323060408401612bd1565b60408201526060830151606082015261324b6080840161313b565b608082015260a083015182811115613261575f80fd5b61326d8b82860161314e565b60a08301525060c083015182811115613284575f80fd5b6132908b828601612e5e565b60c08301525096506132a7915050602087016131b3565b6040870151606088015160809098015196999198509695945092505050565b5f815180845260208085019450602084015f5b838110156128a85781516001600160a01b0316875295820195908201906001016132d9565b606081525f6001600160a01b038086511660608401528060208701511660808401528060408701511660a084015250606085015160c0830152608085015161334e60e084018263ffffffff169052565b5060a085015160e061010084015261336a6101408401826132c6565b905060c0860151605f19848303016101208501526133888282612f92565b602085019690965250505060400152919050565b5f606082840312156133ac575f80fd5b6133b4612c64565b6133bd836131b3565b815260208301516020820152604083015160408201528091505092915050565b5f826133f757634e487b7160e01b5f52601260045260245ffd5b50049056fea164736f6c6343000817000a

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export  ]

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