S Price: $0.737136 (-8.72%)

Contract

0x9590CC6De8a4C294992FFa0550Dee8916651aC4f

Overview

S Balance

Sonic LogoSonic LogoSonic Logo0 S

S Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

1 Internal Transaction found.

Latest 1 internal transaction

Parent Transaction Hash Block From To
97811482025-02-24 10:14:3517 hrs ago1740392075  Contract Creation0 S
Loading...
Loading

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

Contract Name:
BalancerV2VaultAdapter

Compiler Version
v0.8.17+commit.8df45f5f

Optimization Enabled:
Yes with 1000 runs

Other Settings:
london EvmVersion
File 1 of 17 : BalancerV2VaultAdapter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.17;

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

import {RAY} from "@gearbox-protocol/core-v2/contracts/libraries/Constants.sol";
import {BitMask} from "@gearbox-protocol/core-v3/contracts/libraries/BitMask.sol";

import {AbstractAdapter} from "../AbstractAdapter.sol";
import {AdapterType} from "@gearbox-protocol/sdk-gov/contracts/AdapterType.sol";

import {IAsset} from "../../integrations/balancer/IAsset.sol";
import {
    IBalancerV2Vault,
    SwapKind,
    SingleSwap,
    FundManagement,
    BatchSwapStep,
    JoinPoolRequest,
    ExitPoolRequest
} from "../../integrations/balancer/IBalancerV2Vault.sol";
import {
    IBalancerV2VaultAdapter, SingleSwapDiff, PoolStatus
} from "../../interfaces/balancer/IBalancerV2VaultAdapter.sol";

/// @title Balancer V2 Vault adapter
/// @notice Implements logic allowing CAs to swap through and LP in Balancer vaults
contract BalancerV2VaultAdapter is AbstractAdapter, IBalancerV2VaultAdapter {
    using BitMask for uint256;

    AdapterType public constant override _gearboxAdapterType = AdapterType.BALANCER_VAULT;
    uint16 public constant override _gearboxAdapterVersion = 3_00;

    /// @notice Mapping from poolId to status of the pool: whether it is not supported, fully supported or swap-only
    mapping(bytes32 => PoolStatus) public override poolStatus;

    /// @notice Constructor
    /// @param _creditManager Credit manager address
    /// @param _vault Balancer vault address
    constructor(address _creditManager, address _vault)
        AbstractAdapter(_creditManager, _vault) // U:[BAL2-1]
    {}

    // ----- //
    // SWAPS //
    // ----- //

    /// @notice Swaps a token for another token within a single pool
    /// @param singleSwap Struct containing swap parameters
    ///        * `poolId` - ID of the pool to perform a swap in
    ///        * `kind` - type of swap (GIVEN IN / GIVEN OUT)
    ///        * `assetIn` - asset to send
    ///        * `assetOut` - asset to receive
    ///        * `amount` - amount of input asset to send (for GIVEN IN) or output asset to receive (for GIVEN OUT)
    ///        * `userData` - generic blob used to pass extra data
    /// @param limit The minimal amount of `assetOut` to receive or maximal amount of `assetIn` to spend (depending on `kind`)
    /// @param deadline The latest timestamp at which the swap would be executed
    /// @dev `fundManagement` param from the original interface is ignored, as the adapter does not use internal balances and
    ///       only has one sender/recipient
    /// @dev The function reverts if the poolId status is not ALLOWED or SWAP_ONLY
    function swap(SingleSwap memory singleSwap, FundManagement memory, uint256 limit, uint256 deadline)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        if (poolStatus[singleSwap.poolId] == PoolStatus.NOT_ALLOWED) {
            revert PoolNotSupportedException(); // U:[BAL2-3]
        }

        address creditAccount = _creditAccount(); // U:[BAL2-3]

        address tokenIn = address(singleSwap.assetIn);
        address tokenOut = address(singleSwap.assetOut);

        FundManagement memory fundManagement = _getDefaultFundManagement(creditAccount); // U:[BAL2-3]

        // calling `_executeSwap` because we need to check if output token is registered as collateral token in the CM
        (tokensToEnable, tokensToDisable,) = _executeSwapSafeApprove(
            tokenIn,
            tokenOut,
            abi.encodeCall(IBalancerV2Vault.swap, (singleSwap, fundManagement, limit, deadline)),
            false
        ); // U:[BAL2-3]
    }

    /// @notice Swaps the entire balance of a token for another token within a single pool, except the specified amount
    /// @param singleSwapDiff Struct containing swap parameters
    ///        * `poolId` - ID of the pool to perform a swap in
    ///        * `leftoverAmount` - amount of assetIn to leave after operation
    ///        * `assetIn` - asset to send
    ///        * `assetOut` - asset to receive
    ///        * `userData` - additional generic blob used to pass extra data
    /// @param limitRateRAY The minimal resulting exchange rate of assetOut to assetIn, scaled by 1e27
    /// @param deadline The latest timestamp at which the swap would be executed
    /// @dev The function reverts if the poolId status is not ALLOWED or SWAP_ONLY
    function swapDiff(SingleSwapDiff memory singleSwapDiff, uint256 limitRateRAY, uint256 deadline)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        address creditAccount = _creditAccount(); // U:[BAL2-4]

        if (poolStatus[singleSwapDiff.poolId] == PoolStatus.NOT_ALLOWED) {
            revert PoolNotSupportedException(); // U:[BAL2-4]
        }

        uint256 amount = IERC20(address(singleSwapDiff.assetIn)).balanceOf(creditAccount); // U:[BAL2-4]
        if (amount <= singleSwapDiff.leftoverAmount) return (0, 0);

        unchecked {
            amount -= singleSwapDiff.leftoverAmount; // U:[BAL2-4]
        }

        FundManagement memory fundManagement = _getDefaultFundManagement(creditAccount); // U:[BAL2-4]

        // calling `_executeSwap` because we need to check if output token is registered as collateral token in the CM
        (tokensToEnable, tokensToDisable,) = _executeSwapSafeApprove(
            address(singleSwapDiff.assetIn),
            address(singleSwapDiff.assetOut),
            abi.encodeCall(
                IBalancerV2Vault.swap,
                (
                    SingleSwap({
                        poolId: singleSwapDiff.poolId,
                        kind: SwapKind.GIVEN_IN,
                        assetIn: singleSwapDiff.assetIn,
                        assetOut: singleSwapDiff.assetOut,
                        amount: amount,
                        userData: singleSwapDiff.userData
                    }),
                    fundManagement,
                    (amount * limitRateRAY) / RAY,
                    deadline
                )
            ),
            singleSwapDiff.leftoverAmount <= 1
        ); // U:[BAL2-4]
    }

    /// @notice Performs a multi-hop swap through several Balancer pools
    /// @param kind Type of swap (GIVEN IN or GIVEN OUT)
    /// @param swaps Array of structs containing data for each individual swap:
    ///        * `poolId` - ID of the pool to perform a swap in
    ///        * `assetInIndex` - Index of the input asset in the pool (in an alphanumerically sorted array of asset addresses)
    ///        * `assetOutIndex` - Index of the output asset in the pool (in an alphanumerically sorted array of asset addresses)
    ///        * `amount` - amount of asset to send / receive. 0 signals to either spend the entire amount received from the last step,
    ///           or to receive the exact amount needed for the next step
    ///        * `userData` - generic blob used to pass extra data
    /// @param assets Array of all assets participating in the swap
    /// @param limits Array of minimal received (negative) / maximal spent (positive) amounts, in the same order as the assets array
    /// @param deadline The latest timestamp at which the swap would be executed
    /// @dev `fundManagement` param from the original interface is ignored, as the adapter does not use internal balances and
    ///       only has one sender/recipient
    /// @dev The function reverts if any of the poolId statuses is not ALLOWED or SWAP_ONLY
    function batchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        IAsset[] memory assets,
        FundManagement memory,
        int256[] memory limits,
        uint256 deadline
    )
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        unchecked {
            for (uint256 i; i < swaps.length; ++i) {
                if (poolStatus[swaps[i].poolId] == PoolStatus.NOT_ALLOWED) {
                    revert PoolNotSupportedException(); // U:[BAL2-5]
                }
            }
        }

        address creditAccount = _creditAccount(); // U:[BAL2-5]

        FundManagement memory fundManagement = _getDefaultFundManagement(creditAccount); // U:[BAL2-5]

        _approveAssets(assets, limits, type(uint256).max); // U:[BAL2-5]

        int256[] memory assetDeltas = abi.decode(
            _execute(
                abi.encodeCall(IBalancerV2Vault.batchSwap, (kind, swaps, assets, fundManagement, limits, deadline))
            ),
            (int256[])
        ); // U:[BAL2-5]

        _approveAssets(assets, limits, 1); // U:[BAL2-5]

        (tokensToEnable, tokensToDisable) = (_getTokensToEnable(assets, assetDeltas), 0); // U:[BAL2-5]
    }

    // --------- //
    // JOIN POOL //
    // --------- //

    /// @notice Deposits liquidity into a Balancer pool in exchange for BPT
    /// @param poolId ID of the pool to deposit into
    /// @param request A struct containing data for executing a deposit:
    ///        * `assets` - Array of assets in the pool
    ///        * `maxAmountsIn` - Array of maximal amounts to be spent for each asset
    ///        * `userData` - a blob encoding the type of deposit and additional parameters
    ///          (see https://dev.balancer.fi/resources/joins-and-exits/pool-joins#userdata for more info)
    ///        * `fromInternalBalance` - whether to use internal balances for assets
    ///          (ignored as the adapter does not use internal balances)
    /// @dev `sender` and `recipient` are ignored, since they are always set to the CA address
    /// @dev The function reverts if poolId status is not ALLOWED
    function joinPool(bytes32 poolId, address, address, JoinPoolRequest memory request)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        if (poolStatus[poolId] != PoolStatus.ALLOWED) {
            revert PoolNotSupportedException(); // U:[BAL2-6]
        }

        address creditAccount = _creditAccount(); // U:[BAL2-6]

        (address bpt,) = IBalancerV2Vault(targetContract).getPool(poolId);

        request.fromInternalBalance = false; // U:[BAL2-6]

        _approveAssets(request.assets, request.maxAmountsIn, type(uint256).max); // U:[BAL2-6]
        _execute(abi.encodeCall(IBalancerV2Vault.joinPool, (poolId, creditAccount, creditAccount, request))); // U:[BAL2-6]
        _approveAssets(request.assets, request.maxAmountsIn, 1); // U:[BAL2-6]
        (tokensToEnable, tokensToDisable) = (_getMaskOrRevert(bpt), 0); // U:[BAL2-6]
    }

    /// @notice Deposits single asset as liquidity into a Balancer pool
    /// @param poolId ID of the pool to deposit into
    /// @param assetIn Asset to deposit
    /// @param amountIn Amount of asset to deposit
    /// @param minAmountOut The minimal amount of BPT to receive
    /// @dev The function reverts if poolId status is not ALLOWED
    function joinPoolSingleAsset(bytes32 poolId, IAsset assetIn, uint256 amountIn, uint256 minAmountOut)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        if (poolStatus[poolId] != PoolStatus.ALLOWED) {
            revert PoolNotSupportedException(); // U:[BAL2-7]
        }

        address creditAccount = _creditAccount(); // U:[BAL2-7]

        (address bpt,) = IBalancerV2Vault(targetContract).getPool(poolId);

        // calling `_executeSwap` because we need to check if BPT is registered as collateral token in the CM
        (tokensToEnable, tokensToDisable,) = _executeSwapSafeApprove(
            address(assetIn),
            bpt,
            abi.encodeCall(
                IBalancerV2Vault.joinPool,
                (
                    poolId,
                    creditAccount,
                    creditAccount,
                    _getJoinSingleAssetRequest(poolId, assetIn, amountIn, minAmountOut, bpt)
                )
            ),
            false
        ); // U:[BAL2-7]
    }

    /// @notice Deposits the entire balance of given asset, except a specified amount, as liquidity into a Balancer pool
    /// @param poolId ID of the pool to deposit into
    /// @param assetIn Asset to deposit
    /// @param leftoverAmount Amount of underlying to keep on the account
    /// @param minRateRAY The minimal exchange rate of assetIn to BPT, scaled by 1e27
    /// @dev The function reverts if poolId status is not ALLOWED
    function joinPoolSingleAssetDiff(bytes32 poolId, IAsset assetIn, uint256 leftoverAmount, uint256 minRateRAY)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        address creditAccount = _creditAccount(); // U:[BAL2-8]

        if (poolStatus[poolId] != PoolStatus.ALLOWED) {
            revert PoolNotSupportedException(); // U:[BAL2-8]
        }

        uint256 amount = IERC20(address(assetIn)).balanceOf(creditAccount); // U:[BAL2-8]
        if (amount <= leftoverAmount) return (0, 0);

        unchecked {
            amount -= leftoverAmount; // U:[BAL2-8]
        }

        (address bpt,) = IBalancerV2Vault(targetContract).getPool(poolId);

        uint256 amountOutMin = (amount * minRateRAY) / RAY; // U:[BAL2-8]
        JoinPoolRequest memory request = _getJoinSingleAssetRequest(poolId, assetIn, amount, amountOutMin, bpt); // U:[BAL2-8]

        // calling `_executeSwap` because we need to check if BPT is registered as collateral token in the CM
        (tokensToEnable, tokensToDisable,) = _executeSwapSafeApprove(
            address(assetIn),
            bpt,
            abi.encodeCall(IBalancerV2Vault.joinPool, (poolId, creditAccount, creditAccount, request)),
            leftoverAmount <= 1
        ); // U:[BAL2-8]
    }

    /// @dev Internal function that builds a `JoinPoolRequest` struct for one-sided deposits
    function _getJoinSingleAssetRequest(
        bytes32 poolId,
        IAsset assetIn,
        uint256 amountIn,
        uint256 minAmountOut,
        address bpt
    ) internal view returns (JoinPoolRequest memory request) {
        (IERC20[] memory tokens,,) = IBalancerV2Vault(targetContract).getPoolTokens(poolId);

        uint256 len = tokens.length;

        request.assets = new IAsset[](tokens.length);
        request.maxAmountsIn = new uint256[](tokens.length);
        uint256 bptIndex = tokens.length;

        unchecked {
            for (uint256 i; i < len; ++i) {
                request.assets[i] = IAsset(address(tokens[i]));

                if (request.assets[i] == assetIn) {
                    request.maxAmountsIn[i] = amountIn; // U:[BAL2-7,8]
                }

                if (address(request.assets[i]) == bpt) {
                    bptIndex = i;
                }
            }
        }

        request.userData = abi.encode(uint256(1), _removeIndex(request.maxAmountsIn, bptIndex), minAmountOut); // U:[BAL2-7,8]
    }

    // --------- //
    // EXIT POOL //
    // --------- //

    /// @notice Withdraws liquidity from a Balancer pool, burning BPT and receiving assets
    /// @param poolId ID of the pool to withdraw from
    /// @param request A struct containing data for executing a withdrawal:
    ///        * `assets` - Array of all assets in the pool
    ///        * `minAmountsOut` - The minimal amounts to receive for each asset
    ///        * `userData` - a blob encoding the type of deposit and additional parameters
    ///          (see https://dev.balancer.fi/resources/joins-and-exits/pool-exits#userdata for more info)
    ///        * `toInternalBalance` - whether to use internal balances for assets
    ///          (ignored as the adapter does not use internal balances)
    /// @dev `sender` and `recipient` are ignored, since they are always set to the CA address
    function exitPool(bytes32 poolId, address, address payable, ExitPoolRequest memory request)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        address creditAccount = _creditAccount(); // U:[BAL2-9]

        (address bpt,) = IBalancerV2Vault(targetContract).getPool(poolId);

        request.toInternalBalance = false; // U:[BAL2-9]

        _execute(abi.encodeCall(IBalancerV2Vault.exitPool, (poolId, creditAccount, payable(creditAccount), request))); // U:[BAL2-9]

        _getMaskOrRevert(bpt); // U:[BAL2-9]
        (tokensToEnable, tokensToDisable) =
            (_getTokensToEnable(request.assets, _getBalancesFilter(creditAccount, request.assets)), 0); // U:[BAL2-9]
    }

    /// @notice Withdraws liquidity from a Balancer pool, burning BPT and receiving a single asset
    /// @param poolId ID of the pool to withdraw from
    /// @param assetOut Asset to withdraw
    /// @param amountIn Amount of BPT to burn
    /// @param minAmountOut Minimal amount of asset to receive
    function exitPoolSingleAsset(bytes32 poolId, IAsset assetOut, uint256 amountIn, uint256 minAmountOut)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        address creditAccount = _creditAccount(); // U:[BAL2-10]

        (address bpt,) = IBalancerV2Vault(targetContract).getPool(poolId);

        // calling `_executeSwap` because we need to check if asset is registered as collateral token in the CM
        (tokensToEnable, tokensToDisable,) = _executeSwapNoApprove(
            bpt,
            address(assetOut),
            abi.encodeCall(
                IBalancerV2Vault.exitPool,
                (
                    poolId,
                    creditAccount,
                    payable(creditAccount),
                    _getExitSingleAssetRequest(poolId, assetOut, amountIn, minAmountOut, bpt)
                )
            ),
            false
        ); // U:[BAL2-10]
    }

    /// @notice Withdraws all liquidity from a Balancer pool except the specified amount, burning BPT and receiving a single asset
    /// @param poolId ID of the pool to withdraw from
    /// @param assetOut Asset to withdraw
    /// @param leftoverAmount Amount of pool token to keep on the account
    /// @param minRateRAY Minimal exchange rate of BPT to assetOut, scaled by 1e27
    function exitPoolSingleAssetDiff(bytes32 poolId, IAsset assetOut, uint256 leftoverAmount, uint256 minRateRAY)
        external
        override
        creditFacadeOnly // U:[BAL2-2]
        returns (uint256 tokensToEnable, uint256 tokensToDisable)
    {
        address creditAccount = _creditAccount(); // U:[BAL2-11]

        (address bpt,) = IBalancerV2Vault(targetContract).getPool(poolId);

        uint256 amount = IERC20(bpt).balanceOf(creditAccount); // U:[BAL2-11]
        if (amount <= leftoverAmount) return (0, 0);

        unchecked {
            amount -= leftoverAmount; // U:[BAL2-11]
        }

        uint256 amountOutMin = (amount * minRateRAY) / RAY; // U:[BAL2-11]
        ExitPoolRequest memory request = _getExitSingleAssetRequest(poolId, assetOut, amount, amountOutMin, bpt); // U:[BAL2-11]

        // calling `_executeSwap` because we need to check if asset is registered as collateral token in the CM
        (tokensToEnable, tokensToDisable,) = _executeSwapNoApprove(
            bpt,
            address(assetOut),
            abi.encodeCall(IBalancerV2Vault.exitPool, (poolId, creditAccount, payable(creditAccount), request)),
            leftoverAmount <= 1
        ); // U:[BAL2-11]
    }

    /// @dev Internal function that builds an `ExitPoolRequest` struct for one-sided withdrawals
    function _getExitSingleAssetRequest(
        bytes32 poolId,
        IAsset assetOut,
        uint256 amountIn,
        uint256 minAmountOut,
        address bpt
    ) internal view returns (ExitPoolRequest memory request) {
        (IERC20[] memory tokens,,) = IBalancerV2Vault(targetContract).getPoolTokens(poolId);

        uint256 len = tokens.length;

        request.assets = new IAsset[](tokens.length);
        request.minAmountsOut = new uint256[](tokens.length);
        uint256 tokenIndex = tokens.length;
        uint256 bptIndex = tokens.length;

        unchecked {
            for (uint256 i; i < len; ++i) {
                request.assets[i] = IAsset(address(tokens[i]));

                if (request.assets[i] == assetOut) {
                    request.minAmountsOut[i] = minAmountOut; // U:[BAL2-10,11]
                    tokenIndex = i;
                }

                if (address(request.assets[i]) == bpt) {
                    bptIndex = i;
                }
            }
        }

        tokenIndex = tokenIndex > bptIndex ? tokenIndex - 1 : tokenIndex; // U:[BAL2-10,11]

        request.userData = abi.encode(uint256(0), amountIn, tokenIndex);
    }

    // ------- //
    // HELPERS //
    // ------- //

    /// @dev Internal function that changes approval for a batch of assets in the vault
    function _approveAssets(IAsset[] memory assets, int256[] memory filter, uint256 amount) internal {
        uint256 len = assets.length;

        unchecked {
            for (uint256 i; i < len; ++i) {
                if (filter[i] > 1) _approveToken(address(assets[i]), amount);
            }
        }
    }

    /// @dev Internal function that changes approval for a batch of assets in the vault (overloading)
    function _approveAssets(IAsset[] memory assets, uint256[] memory filter, uint256 amount) internal {
        uint256 len = assets.length;

        unchecked {
            for (uint256 i = 0; i < len; ++i) {
                if (filter[i] > 1) _approveToken(address(assets[i]), amount);
            }
        }
    }

    /// @dev Returns mask of all tokens that should be enabled, based on balances / balance changes
    function _getTokensToEnable(IAsset[] memory assets, int256[] memory filter)
        internal
        view
        returns (uint256 tokensToEnable)
    {
        uint256 len = assets.length;

        unchecked {
            for (uint256 i; i < len; ++i) {
                if (filter[i] < -1) tokensToEnable = tokensToEnable.enable(_getMaskOrRevert(address(assets[i])));
            }
        }
    }

    /// @dev Internal function that creates a filter based on CA token balances
    function _getBalancesFilter(address creditAccount, IAsset[] memory assets)
        internal
        view
        returns (int256[] memory filter)
    {
        uint256 len = assets.length;

        filter = new int256[](len);

        for (uint256 i = 0; i < len;) {
            filter[i] = -int256(IERC20(address(assets[i])).balanceOf(creditAccount));
            unchecked {
                ++i;
            }
        }
    }

    /// @dev Returns a standard `FundManagement` struct used by the adapter
    function _getDefaultFundManagement(address creditAccount) internal pure returns (FundManagement memory) {
        return FundManagement({
            sender: creditAccount,
            fromInternalBalance: false,
            recipient: payable(creditAccount),
            toInternalBalance: false
        });
    }

    /// @dev Returns copy of `array` without an element at `index`
    function _removeIndex(uint256[] memory array, uint256 index) internal pure returns (uint256[] memory res) {
        uint256 len = array.length;

        if (index >= len) {
            return array;
        }

        len = len - 1;

        res = new uint256[](len);

        for (uint256 i = 0; i < len;) {
            if (i < index) {
                res[i] = array[i];
            } else {
                res[i] = array[i + 1];
            }

            unchecked {
                ++i;
            }
        }
    }

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

    /// @notice Sets the pool status
    function setPoolStatus(bytes32 poolId, PoolStatus newStatus)
        external
        override
        configuratorOnly // U:[BAL2-12]
    {
        if (poolStatus[poolId] != newStatus) {
            poolStatus[poolId] = newStatus; // U:[BAL2-12]
            emit SetPoolStatus(poolId, newStatus); // U:[BAL2-12]
        }
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

File 3 of 17 : Constants.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;

// Denominations

uint256 constant WAD = 1e18;
uint256 constant RAY = 1e27;
uint16 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals

// 25% of type(uint256).max
uint256 constant ALLOWANCE_THRESHOLD = type(uint96).max >> 3;

// FEE = 50%
uint16 constant DEFAULT_FEE_INTEREST = 50_00; // 50%

// LIQUIDATION_FEE 1.5%
uint16 constant DEFAULT_FEE_LIQUIDATION = 1_50; // 1.5%

// LIQUIDATION PREMIUM 4%
uint16 constant DEFAULT_LIQUIDATION_PREMIUM = 4_00; // 4%

// LIQUIDATION_FEE_EXPIRED 2%
uint16 constant DEFAULT_FEE_LIQUIDATION_EXPIRED = 1_00; // 2%

// LIQUIDATION PREMIUM EXPIRED 2%
uint16 constant DEFAULT_LIQUIDATION_PREMIUM_EXPIRED = 2_00; // 2%

// DEFAULT PROPORTION OF MAX BORROWED PER BLOCK TO MAX BORROWED PER ACCOUNT
uint16 constant DEFAULT_LIMIT_PER_BLOCK_MULTIPLIER = 2;

// Seconds in a year
uint256 constant SECONDS_PER_YEAR = 365 days;
uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = (SECONDS_PER_YEAR * 3) / 2;

// OPERATIONS

// Leverage decimals - 100 is equal to 2x leverage (100% * collateral amount + 100% * borrowed amount)
uint8 constant LEVERAGE_DECIMALS = 100;

// Maximum withdraw fee for pool in PERCENTAGE_FACTOR format
uint8 constant MAX_WITHDRAW_FEE = 100;

uint256 constant EXACT_INPUT = 1;
uint256 constant EXACT_OUTPUT = 2;

address constant UNIVERSAL_CONTRACT = 0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC;

File 4 of 17 : BitMask.sol
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.17;

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

uint256 constant UNDERLYING_TOKEN_MASK = 1;

/// @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 an index of an item based on its mask (using a binary search)
    /// @dev The input should always have only 1 bit set, otherwise the result may be unpredictable
    function calcIndex(uint256 mask) internal pure returns (uint8 index) {
        if (mask == 0) revert IncorrectParameterException(); // U:[BM-1]
        uint16 lb = 0; // U:[BM-2]
        uint16 ub = 256; // U:[BM-2]
        uint16 mid = 128; // U:[BM-2]

        unchecked {
            while (true) {
                uint256 newMask = 1 << mid;
                if (newMask & mask != 0) return uint8(mid); // U:[BM-2]

                if (newMask > mask) ub = mid; // U:[BM-2]

                else lb = mid; // U:[BM-2]
                mid = (lb + ub) >> 1; // U:[BM-2]
            }
        }
    }

    /// @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 Enables bits from the second mask in the first mask, skipping specified bits
    /// @param enabledTokenMask The initial mask
    /// @param bitsToEnable Mask with bits to enable
    /// @param invertedSkipMask An inversion of mask of immutable bits
    function enable(uint256 enabledTokenMask, uint256 bitsToEnable, uint256 invertedSkipMask)
        internal
        pure
        returns (uint256)
    {
        return enabledTokenMask | (bitsToEnable & invertedSkipMask); // U:[BM-6]
    }

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

    /// @dev Computes a new mask with sets of new enabled and disabled bits, skipping some bits
    /// @dev bitsToEnable and bitsToDisable are applied sequentially to original mask. Skipmask is applied in both cases.
    /// @param enabledTokensMask The initial mask
    /// @param bitsToEnable Mask with bits to enable
    /// @param bitsToDisable Mask with bits to disable
    /// @param invertedSkipMask An inversion of mask of immutable bits
    function enableDisable(
        uint256 enabledTokensMask,
        uint256 bitsToEnable,
        uint256 bitsToDisable,
        uint256 invertedSkipMask
    ) internal pure returns (uint256) {
        return (enabledTokensMask | (bitsToEnable & invertedSkipMask)) & (~(bitsToDisable & invertedSkipMask)); // U:[BM-7]
    }
}

File 5 of 17 : AbstractAdapter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.17;

import {IAdapter} from "@gearbox-protocol/core-v2/contracts/interfaces/IAdapter.sol";
import {ICreditManagerV3} from "@gearbox-protocol/core-v3/contracts/interfaces/ICreditManagerV3.sol";
import {CallerNotCreditFacadeException} from "@gearbox-protocol/core-v3/contracts/interfaces/IExceptions.sol";
import {ACLTrait} from "@gearbox-protocol/core-v3/contracts/traits/ACLTrait.sol";

/// @title Abstract adapter
/// @dev Inheriting adapters MUST use provided internal functions to perform all operations with credit accounts
abstract contract AbstractAdapter is IAdapter, ACLTrait {
    /// @notice Credit manager the adapter is connected to
    address public immutable override creditManager;

    /// @notice Address provider contract
    address public immutable override addressProvider;

    /// @notice Address of the contract the adapter is interacting with
    address public immutable override targetContract;

    /// @notice Constructor
    /// @param _creditManager Credit manager to connect the adapter to
    /// @param _targetContract Address of the adapted contract
    constructor(address _creditManager, address _targetContract)
        ACLTrait(ICreditManagerV3(_creditManager).addressProvider())
        nonZeroAddress(_targetContract)
    {
        creditManager = _creditManager;
        addressProvider = ICreditManagerV3(_creditManager).addressProvider();
        targetContract = _targetContract;
    }

    /// @dev Ensures that caller of the function is credit facade connected to the credit manager
    /// @dev Inheriting adapters MUST use this modifier in all external functions that operate on credit accounts
    modifier creditFacadeOnly() {
        _revertIfCallerNotCreditFacade();
        _;
    }

    /// @dev Ensures that caller is credit facade connected to the credit manager
    function _revertIfCallerNotCreditFacade() internal view {
        if (msg.sender != ICreditManagerV3(creditManager).creditFacade()) {
            revert CallerNotCreditFacadeException();
        }
    }

    /// @dev Ensures that active credit account is set and returns its address
    function _creditAccount() internal view returns (address) {
        return ICreditManagerV3(creditManager).getActiveCreditAccountOrRevert();
    }

    /// @dev Ensures that token is registered as collateral in the credit manager and returns its mask
    function _getMaskOrRevert(address token) internal view returns (uint256 tokenMask) {
        tokenMask = ICreditManagerV3(creditManager).getTokenMaskOrRevert(token);
    }

    /// @dev Approves target contract to spend given token from the active credit account
    ///      Reverts if active credit account is not set or token is not registered as collateral
    /// @param token Token to approve
    /// @param amount Amount to approve
    function _approveToken(address token, uint256 amount) internal {
        ICreditManagerV3(creditManager).approveCreditAccount(token, amount);
    }

    /// @dev Executes an external call from the active credit account to the target contract
    ///      Reverts if active credit account is not set
    /// @param callData Data to call the target contract with
    /// @return result Call result
    function _execute(bytes memory callData) internal returns (bytes memory result) {
        return ICreditManagerV3(creditManager).execute(callData);
    }

    /// @dev Executes a swap operation without input token approval
    ///      Reverts if active credit account is not set or any of passed tokens is not registered as collateral
    /// @param tokenIn Input token that credit account spends in the call
    /// @param tokenOut Output token that credit account receives after the call
    /// @param callData Data to call the target contract with
    /// @param disableTokenIn Whether `tokenIn` should be disabled after the call
    ///        (for operations that spend the entire account's balance of the input token)
    /// @return tokensToEnable Bit mask of tokens that should be enabled after the call
    /// @return tokensToDisable Bit mask of tokens that should be disabled after the call
    /// @return result Call result
    function _executeSwapNoApprove(address tokenIn, address tokenOut, bytes memory callData, bool disableTokenIn)
        internal
        returns (uint256 tokensToEnable, uint256 tokensToDisable, bytes memory result)
    {
        tokensToEnable = _getMaskOrRevert(tokenOut);
        uint256 tokenInMask = _getMaskOrRevert(tokenIn);
        if (disableTokenIn) tokensToDisable = tokenInMask;
        result = _execute(callData);
    }

    /// @dev Executes a swap operation with maximum input token approval, and revokes approval after the call
    ///      Reverts if active credit account is not set or any of passed tokens is not registered as collateral
    /// @param tokenIn Input token that credit account spends in the call
    /// @param tokenOut Output token that credit account receives after the call
    /// @param callData Data to call the target contract with
    /// @param disableTokenIn Whether `tokenIn` should be disabled after the call
    ///        (for operations that spend the entire account's balance of the input token)
    /// @return tokensToEnable Bit mask of tokens that should be enabled after the call
    /// @return tokensToDisable Bit mask of tokens that should be disabled after the call
    /// @return result Call result
    /// @custom:expects Credit manager reverts when trying to approve non-collateral token
    function _executeSwapSafeApprove(address tokenIn, address tokenOut, bytes memory callData, bool disableTokenIn)
        internal
        returns (uint256 tokensToEnable, uint256 tokensToDisable, bytes memory result)
    {
        tokensToEnable = _getMaskOrRevert(tokenOut);
        if (disableTokenIn) tokensToDisable = _getMaskOrRevert(tokenIn);
        _approveToken(tokenIn, type(uint256).max);
        result = _execute(callData);
        _approveToken(tokenIn, 1);
    }
}

File 6 of 17 : AdapterType.sol
// SPDX-License-Identifier: UNLICENSED
// Gearbox. Generalized leverage protocol that allows to take leverage and then use it across other DeFi protocols and platforms in a composable way.
// (c) Gearbox Foundation, 2023
pragma solidity ^0.8.17;

enum AdapterType {
    ABSTRACT,
    UNISWAP_V2_ROUTER,
    UNISWAP_V3_ROUTER,
    CURVE_V1_EXCHANGE_ONLY,
    YEARN_V2,
    CURVE_V1_2ASSETS,
    CURVE_V1_3ASSETS,
    CURVE_V1_4ASSETS,
    CURVE_V1_STECRV_POOL,
    CURVE_V1_WRAPPER,
    CONVEX_V1_BASE_REWARD_POOL,
    CONVEX_V1_BOOSTER,
    CONVEX_V1_CLAIM_ZAP,
    LIDO_V1,
    UNIVERSAL,
    LIDO_WSTETH_V1,
    BALANCER_VAULT,
    AAVE_V2_LENDING_POOL,
    AAVE_V2_WRAPPED_ATOKEN,
    COMPOUND_V2_CERC20,
    COMPOUND_V2_CETHER,
    ERC4626_VAULT,
    VELODROME_V2_ROUTER,
    CURVE_STABLE_NG,
    CAMELOT_V3_ROUTER,
    CONVEX_L2_BOOSTER,
    CONVEX_L2_REWARD_POOL,
    AAVE_V3_LENDING_POOL,
    ZIRCUIT_POOL,
    SYMBIOTIC_DEFAULT_COLLATERAL,
    MELLOW_LRT_VAULT,
    PENDLE_ROUTER,
    MELLOW_ERC4626_VAULT,
    DAI_USDS_EXCHANGE,
    STAKING_REWARDS,
    EQUALIZER_ROUTER,
    BALANCER_V3_ROUTER
}

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

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

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

pragma solidity >=0.7.0 <0.9.0;

/**
 * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero
 * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like
 * types.
 *
 * This concept is unrelated to a Pool's Asset Managers.
 */
interface IAsset {
// solhint-disable-previous-line no-empty-blocks
}

File 8 of 17 : IBalancerV2Vault.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IAsset} from "./IAsset.sol";

enum SwapKind {
    GIVEN_IN,
    GIVEN_OUT
}

enum PoolSpecialization {
    GENERAL,
    MINIMAL_SWAP_INFO,
    TWO_TOKEN
}

enum JoinKind {
    INIT,
    EXACT_TOKENS_IN_FOR_BPT_OUT,
    TOKEN_IN_FOR_EXACT_BPT_OUT,
    ALL_TOKENS_IN_FOR_EXACT_BPT_OUT
}

enum ExitKind {
    EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,
    EXACT_BPT_IN_FOR_TOKENS_OUT,
    BPT_IN_FOR_EXACT_TOKENS_OUT
}

struct SingleSwap {
    bytes32 poolId;
    SwapKind kind;
    IAsset assetIn;
    IAsset assetOut;
    uint256 amount;
    bytes userData;
}

struct BatchSwapStep {
    bytes32 poolId;
    uint256 assetInIndex;
    uint256 assetOutIndex;
    uint256 amount;
    bytes userData;
}

struct FundManagement {
    address sender;
    bool fromInternalBalance;
    address payable recipient;
    bool toInternalBalance;
}

struct JoinPoolRequest {
    IAsset[] assets;
    uint256[] maxAmountsIn;
    bytes userData;
    bool fromInternalBalance;
}

struct ExitPoolRequest {
    IAsset[] assets;
    uint256[] minAmountsOut;
    bytes userData;
    bool toInternalBalance;
}

interface IBalancerV2VaultGetters {
    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);

    function getPoolTokenInfo(bytes32 poolId, IERC20 token)
        external
        view
        returns (uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager);

    function getPoolTokens(bytes32 poolId)
        external
        view
        returns (IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock);
}

interface IBalancerV2Vault is IBalancerV2VaultGetters {
    function batchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        IAsset[] memory assets,
        FundManagement memory funds,
        int256[] memory limits,
        uint256 deadline
    ) external returns (int256[] memory assetDeltas);

    function queryBatchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        IAsset[] memory assets,
        FundManagement memory funds
    ) external returns (int256[] memory assetDeltas);

    function swap(SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline)
        external
        returns (uint256 amountCalculated);

    function joinPool(bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request) external;

    function exitPool(bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request)
        external;
}

File 9 of 17 : IBalancerV2VaultAdapter.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.17;

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

import {
    IAsset,
    SingleSwap,
    FundManagement,
    SwapKind,
    BatchSwapStep,
    JoinPoolRequest,
    ExitPoolRequest
} from "../../integrations/balancer/IBalancerV2Vault.sol";

enum PoolStatus {
    NOT_ALLOWED,
    ALLOWED,
    SWAP_ONLY
}

struct SingleSwapDiff {
    bytes32 poolId;
    uint256 leftoverAmount;
    IAsset assetIn;
    IAsset assetOut;
    bytes userData;
}

interface IBalancerV2VaultAdapterEvents {
    /// @notice Emitted when new status is set for a pool with given ID
    event SetPoolStatus(bytes32 indexed poolId, PoolStatus newStatus);
}

interface IBalancerV2VaultAdapterExceptions {
    /// @notice Thrown when attempting to swap or change liqudity in the pool that is not supported for that action
    error PoolNotSupportedException();
}

/// @title Balancer V2 Vault adapter interface
interface IBalancerV2VaultAdapter is IAdapter, IBalancerV2VaultAdapterEvents, IBalancerV2VaultAdapterExceptions {
    // ----- //
    // SWAPS //
    // ----- //

    function swap(SingleSwap memory singleSwap, FundManagement memory, uint256 limit, uint256 deadline)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    function swapDiff(SingleSwapDiff memory singleSwapDiff, uint256 limitRateRAY, uint256 deadline)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    function batchSwap(
        SwapKind kind,
        BatchSwapStep[] memory swaps,
        IAsset[] memory assets,
        FundManagement memory,
        int256[] memory limits,
        uint256 deadline
    ) external returns (uint256 tokensToEnable, uint256 tokensToDisable);

    // --------- //
    // JOIN POOL //
    // --------- //

    function joinPool(bytes32 poolId, address, address, JoinPoolRequest memory request)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    function joinPoolSingleAsset(bytes32 poolId, IAsset assetIn, uint256 amountIn, uint256 minAmountOut)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    function joinPoolSingleAssetDiff(bytes32 poolId, IAsset assetIn, uint256 leftoverAmount, uint256 minRateRAY)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    // --------- //
    // EXIT POOL //
    // --------- //

    function exitPool(bytes32 poolId, address, address payable, ExitPoolRequest memory request)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    function exitPoolSingleAsset(bytes32 poolId, IAsset assetOut, uint256 amountIn, uint256 minAmountOut)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

    function exitPoolSingleAssetDiff(bytes32 poolId, IAsset assetOut, uint256 leftoverAmount, uint256 minRateRAY)
        external
        returns (uint256 tokensToEnable, uint256 tokensToDisable);

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

    function poolStatus(bytes32 poolId) external view returns (PoolStatus);

    function setPoolStatus(bytes32 poolId, PoolStatus newStatus) external;
}

File 10 of 17 : IExceptions.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
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 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();

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

/// @notice Thrown when trying to close an account with enabled tokens
error CloseAccountWithEnabledTokensException();

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

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

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

/// @notice Thrown when new forbidden tokens are enabled during the multicall
error ForbiddenTokenEnabledException();

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

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

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

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

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

// ------ //
// 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 call an access restricted function not as controller or configurator
error CallerNotControllerException();

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

// ------------------- //
// CONTROLLER TIMELOCK //
// ------------------- //

/// @notice Thrown when the new parameter values do not satisfy required conditions
error ParameterChecksFailedException();

/// @notice Thrown when attempting to execute a non-queued transaction
error TxNotQueuedException();

/// @notice Thrown when attempting to execute a transaction that is either immature or stale
error TxExecutedOutsideTimeWindowException();

/// @notice Thrown when execution of a transaction fails
error TxExecutionRevertedException();

/// @notice Thrown when the value of a parameter on execution is different from the value on queue
error ParameterChangedAfterQueuedTxException();

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

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

// --------------- //
// 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 price feed returns incorrect price for a token
error IncorrectPriceException();

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

File 11 of 17 : IAdapter.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.0;

import { AdapterType } from "@gearbox-protocol/sdk-gov/contracts/AdapterType.sol";

/// @title Adapter interface
interface IAdapter {
    function _gearboxAdapterType() external view returns (AdapterType);

    function _gearboxAdapterVersion() external view returns (uint16);

    function creditManager() external view returns (address);

    function addressProvider() external view returns (address);

    function targetContract() external view returns (address);
}

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

import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";

uint8 constant BOT_PERMISSIONS_SET_FLAG = 1;

uint8 constant DEFAULT_MAX_ENABLED_TOKENS = 4;
address constant INACTIVE_CREDIT_ACCOUNT_ADDRESS = address(1);

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

struct RevocationPair {
    address spender;
    address token;
}

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 addressProvider() 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 tokensToEnable, uint256 tokensToDisable);

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

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

    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;

    function revokeAdapterAllowances(address creditAccount, RevocationPair[] calldata revocations) 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 enabledTokensMaskAfter);

    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 setQuotedMask(uint256 quotedTokensMask) external;

    function setMaxEnabledTokens(uint8 maxEnabledTokens) external;

    function setContractAllowance(address adapter, address targetContract) external;

    function setCreditFacade(address creditFacade) external;

    function setPriceOracle(address priceOracle) external;

    function setCreditConfigurator(address creditConfigurator) external;
}

File 13 of 17 : ACLTrait.sol
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.17;

import {IACL} from "@gearbox-protocol/core-v2/contracts/interfaces/IACL.sol";

import {AP_ACL, IAddressProviderV3, NO_VERSION_CONTROL} from "../interfaces/IAddressProviderV3.sol";
import {CallerNotConfiguratorException} from "../interfaces/IExceptions.sol";

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

/// @title ACL trait
/// @notice Utility class for ACL (access-control list) consumers
abstract contract ACLTrait is SanityCheckTrait {
    /// @notice ACL contract address
    address public immutable acl;

    /// @notice Constructor
    /// @param addressProvider Address provider contract address
    constructor(address addressProvider) nonZeroAddress(addressProvider) {
        acl = IAddressProviderV3(addressProvider).getAddressOrRevert(AP_ACL, NO_VERSION_CONTROL);
    }

    /// @dev Ensures that function caller has configurator role
    modifier configuratorOnly() {
        _ensureCallerIsConfigurator();
        _;
    }

    /// @dev Reverts if the caller is not the configurator
    /// @dev Used to cut contract size on modifiers
    function _ensureCallerIsConfigurator() internal view {
        if (!_isConfigurator({account: msg.sender})) {
            revert CallerNotConfiguratorException();
        }
    }

    /// @dev Checks whether given account has configurator role
    function _isConfigurator(address account) internal view returns (bool) {
        return IACL(acl).isConfigurator(account);
    }
}

File 14 of 17 : IVersion.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;

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

File 15 of 17 : IACL.sol
// SPDX-License-Identifier: MIT
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2022
pragma solidity ^0.8.10;
import { IVersion } from "./IVersion.sol";

interface IACLExceptions {
    /// @dev Thrown when attempting to delete an address from a set that is not a pausable admin
    error AddressNotPausableAdminException(address addr);

    /// @dev Thrown when attempting to delete an address from a set that is not a unpausable admin
    error AddressNotUnpausableAdminException(address addr);
}

interface IACLEvents {
    /// @dev Emits when a new admin is added that can pause contracts
    event PausableAdminAdded(address indexed newAdmin);

    /// @dev Emits when a Pausable admin is removed
    event PausableAdminRemoved(address indexed admin);

    /// @dev Emits when a new admin is added that can unpause contracts
    event UnpausableAdminAdded(address indexed newAdmin);

    /// @dev Emits when an Unpausable admin is removed
    event UnpausableAdminRemoved(address indexed admin);
}

/// @title ACL interface
interface IACL is IACLEvents, IACLExceptions, IVersion {
    /// @dev Returns true if the address is a pausable admin and false if not
    /// @param addr Address to check
    function isPausableAdmin(address addr) external view returns (bool);

    /// @dev Returns true if the address is unpausable admin and false if not
    /// @param addr Address to check
    function isUnpausableAdmin(address addr) external view returns (bool);

    /// @dev Returns true if an address has configurator rights
    /// @param account Address to check
    function isConfigurator(address account) external view returns (bool);

    /// @dev Returns address of configurator
    function owner() external view returns (address);
}

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

import {IVersion} from "@gearbox-protocol/core-v2/contracts/interfaces/IVersion.sol";

uint256 constant NO_VERSION_CONTROL = 0;

bytes32 constant AP_CONTRACTS_REGISTER = "CONTRACTS_REGISTER";
bytes32 constant AP_ACL = "ACL";
bytes32 constant AP_PRICE_ORACLE = "PRICE_ORACLE";
bytes32 constant AP_ACCOUNT_FACTORY = "ACCOUNT_FACTORY";
bytes32 constant AP_DATA_COMPRESSOR = "DATA_COMPRESSOR";
bytes32 constant AP_TREASURY = "TREASURY";
bytes32 constant AP_GEAR_TOKEN = "GEAR_TOKEN";
bytes32 constant AP_WETH_TOKEN = "WETH_TOKEN";
bytes32 constant AP_WETH_GATEWAY = "WETH_GATEWAY";
bytes32 constant AP_ROUTER = "ROUTER";
bytes32 constant AP_BOT_LIST = "BOT_LIST";
bytes32 constant AP_GEAR_STAKING = "GEAR_STAKING";
bytes32 constant AP_ZAPPER_REGISTER = "ZAPPER_REGISTER";

interface IAddressProviderV3Events {
    /// @notice Emitted when an address is set for a contract key
    event SetAddress(bytes32 indexed key, address indexed value, uint256 indexed version);
}

/// @title Address provider V3 interface
interface IAddressProviderV3 is IAddressProviderV3Events, IVersion {
    function addresses(bytes32 key, uint256 _version) external view returns (address);

    function getAddressOrRevert(bytes32 key, uint256 _version) external view returns (address result);

    function setAddress(bytes32 key, address value, bool saveVersion) external;
}

File 17 of 17 : SanityCheckTrait.sol
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Foundation, 2023.
pragma solidity ^0.8.17;

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

/// @title Sanity check trait
abstract contract SanityCheckTrait {
    /// @dev Ensures that passed address is non-zero
    modifier nonZeroAddress(address addr) {
        _revertIfZeroAddress(addr);
        _;
    }

    /// @dev Reverts if address is zero
    function _revertIfZeroAddress(address addr) private pure {
        if (addr == address(0)) revert ZeroAddressException();
    }
}

Settings
{
  "remappings": [
    "@1inch/=node_modules/@1inch/",
    "@arbitrum/=node_modules/@arbitrum/",
    "@chainlink/=node_modules/@chainlink/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@gearbox-protocol/=node_modules/@gearbox-protocol/",
    "@openzeppelin/=node_modules/@openzeppelin/",
    "@redstone-finance/=node_modules/@redstone-finance/",
    "ds-test/=lib/forge-std/lib/ds-test/src/",
    "eth-gas-reporter/=node_modules/eth-gas-reporter/",
    "forge-std/=lib/forge-std/src/"
  ],
  "optimizer": {
    "enabled": true,
    "runs": 1000
  },
  "metadata": {
    "useLiteralContent": false,
    "bytecodeHash": "ipfs"
  },
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "evmVersion": "london",
  "viaIR": false,
  "libraries": {}
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"_creditManager","type":"address"},{"internalType":"address","name":"_vault","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"CallerNotConfiguratorException","type":"error"},{"inputs":[],"name":"CallerNotCreditFacadeException","type":"error"},{"inputs":[],"name":"PoolNotSupportedException","type":"error"},{"inputs":[],"name":"ZeroAddressException","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"poolId","type":"bytes32"},{"indexed":false,"internalType":"enum PoolStatus","name":"newStatus","type":"uint8"}],"name":"SetPoolStatus","type":"event"},{"inputs":[],"name":"_gearboxAdapterType","outputs":[{"internalType":"enum AdapterType","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_gearboxAdapterVersion","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"acl","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"addressProvider","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"enum SwapKind","name":"kind","type":"uint8"},{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"assetInIndex","type":"uint256"},{"internalType":"uint256","name":"assetOutIndex","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"internalType":"struct BatchSwapStep[]","name":"swaps","type":"tuple[]"},{"internalType":"contract IAsset[]","name":"assets","type":"address[]"},{"components":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"},{"internalType":"address payable","name":"recipient","type":"address"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct FundManagement","name":"","type":"tuple"},{"internalType":"int256[]","name":"limits","type":"int256[]"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"batchSwap","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"creditManager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"","type":"address"},{"internalType":"address payable","name":"","type":"address"},{"components":[{"internalType":"contract IAsset[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"minAmountsOut","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct ExitPoolRequest","name":"request","type":"tuple"}],"name":"exitPool","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"contract IAsset","name":"assetOut","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"name":"exitPoolSingleAsset","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"contract IAsset","name":"assetOut","type":"address"},{"internalType":"uint256","name":"leftoverAmount","type":"uint256"},{"internalType":"uint256","name":"minRateRAY","type":"uint256"}],"name":"exitPoolSingleAssetDiff","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"components":[{"internalType":"contract IAsset[]","name":"assets","type":"address[]"},{"internalType":"uint256[]","name":"maxAmountsIn","type":"uint256[]"},{"internalType":"bytes","name":"userData","type":"bytes"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"}],"internalType":"struct JoinPoolRequest","name":"request","type":"tuple"}],"name":"joinPool","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"contract IAsset","name":"assetIn","type":"address"},{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"minAmountOut","type":"uint256"}],"name":"joinPoolSingleAsset","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"contract IAsset","name":"assetIn","type":"address"},{"internalType":"uint256","name":"leftoverAmount","type":"uint256"},{"internalType":"uint256","name":"minRateRAY","type":"uint256"}],"name":"joinPoolSingleAssetDiff","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"poolStatus","outputs":[{"internalType":"enum PoolStatus","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"enum PoolStatus","name":"newStatus","type":"uint8"}],"name":"setPoolStatus","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"enum SwapKind","name":"kind","type":"uint8"},{"internalType":"contract IAsset","name":"assetIn","type":"address"},{"internalType":"contract IAsset","name":"assetOut","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"userData","type":"bytes"}],"internalType":"struct SingleSwap","name":"singleSwap","type":"tuple"},{"components":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"bool","name":"fromInternalBalance","type":"bool"},{"internalType":"address payable","name":"recipient","type":"address"},{"internalType":"bool","name":"toInternalBalance","type":"bool"}],"internalType":"struct FundManagement","name":"","type":"tuple"},{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swap","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"bytes32","name":"poolId","type":"bytes32"},{"internalType":"uint256","name":"leftoverAmount","type":"uint256"},{"internalType":"contract IAsset","name":"assetIn","type":"address"},{"internalType":"contract IAsset","name":"assetOut","type":"address"},{"internalType":"bytes","name":"userData","type":"bytes"}],"internalType":"struct SingleSwapDiff","name":"singleSwapDiff","type":"tuple"},{"internalType":"uint256","name":"limitRateRAY","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapDiff","outputs":[{"internalType":"uint256","name":"tokensToEnable","type":"uint256"},{"internalType":"uint256","name":"tokensToDisable","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"targetContract","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

Deployed Bytecode

0x608060405234801561001057600080fd5b506004361061011b5760003560e01c80638f4c6ec5116100b2578063bd90df7011610081578063ce30bbdb11610066578063ce30bbdb146102c4578063d1b5797e146102d9578063de287359146102ec57600080fd5b8063bd90df7014610276578063c12c21c01461029d57600080fd5b80638f4c6ec514610228578063945bcec91461023d578063b95cac2814610250578063bc5a07df1461026357600080fd5b806352bbbe29116100ee57806352bbbe29146101d357806372a802ce146101e657806378aa73a4146101f95780638bdb39131461021557600080fd5b8063066ada90146101205780631a970270146101595780631cc04018146101815780632954018c14610194575b600080fd5b61014361012e366004611e5a565b60006020819052908152604090205460ff1681565b6040516101509190611e89565b60405180910390f35b61016c610167366004611ebb565b610313565b60408051928352602083019190915201610150565b61016c61018f366004611ebb565b6104dd565b6101bb7f0000000000000000000000004b27b296273b72d7c7bfee1ace93dc081467c41b81565b6040516001600160a01b039091168152602001610150565b61016c6101e13660046120c1565b6106d5565b61016c6101f4366004611ebb565b6107f4565b61020261012c81565b60405161ffff9091168152602001610150565b61016c61022336600461231e565b610946565b61023b610236366004612397565b610a6d565b005b61016c61024b366004612422565b610b1c565b61016c61025e36600461231e565b610cb8565b61016c610271366004611ebb565b610e23565b6101bb7f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c881565b6101bb7f00000000000000000000000029b9131bd16859ddac4d43167aca40720dd75f7b81565b6102cc601081565b60405161015091906125ce565b61016c6102e73660046125e2565b610f22565b6101bb7f000000000000000000000000ad131da4bddb40ebb5ceeaea87067553d431389581565b60008061031e61115a565b6000610328611228565b60405163f6c0092760e01b8152600481018990529091506000906001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8169063f6c00927906024016040805180830381865afa158015610392573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103b6919061269a565b506040516370a0823160e01b81526001600160a01b0384811660048301529192506000918316906370a0823190602401602060405180830381865afa158015610403573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061042791906126c9565b905086811161043f57600080945094505050506104d4565b86900360006b033b2e3c9fd0803ce800000061045b88846126f8565b610465919061270f565b905060006104768b8b8585886112b1565b90506104c8848b8d8889866040516024016104949493929190612853565b60408051601f198184030181529190526020810180516001600160e01b0316638bdb391360e01b17905260018d1115611546565b50909750955050505050505b94509492505050565b6000806104e861115a565b60006104f2611228565b9050600160008881526020819052604090205460ff16600281111561051957610519611e73565b146105375760405163d3ef306f60e01b815260040160405180910390fd5b6040516370a0823160e01b81526001600160a01b038281166004830152600091908816906370a0823190602401602060405180830381865afa158015610581573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105a591906126c9565b90508581116105bc576000809350935050506104d4565b60405163f6c0092760e01b81526004810189905290869003906000907f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03169063f6c00927906024016040805180830381865afa158015610628573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061064c919061269a565b50905060006b033b2e3c9fd0803ce800000061066888856126f8565b610672919061270f565b905060006106838b8b868587611583565b90506104c88a848d8889866040516024016106a19493929190612853565b60408051601f198184030181529190526020810180516001600160e01b031663172b958560e31b17905260018d1115611800565b6000806106e061115a565b855160009081526020819052604081205460ff16600281111561070557610705611e73565b036107235760405163d3ef306f60e01b815260040160405180910390fd5b600061072d611228565b604088015160608901519192509060006107938460408051608081018252600080825260208201819052918101829052606081019190915250604080516080810182526001600160a01b0390921680835260006020840181905291830152606082015290565b90506107e283838c848c8c6040516024016107b194939291906128a3565b60408051601f198184030181529190526020810180516001600160e01b03166352bbbe2960e01b1790526000611800565b50909b909a5098505050505050505050565b6000806107ff61115a565b600160008781526020819052604090205460ff16600281111561082457610824611e73565b146108425760405163d3ef306f60e01b815260040160405180910390fd5b600061084c611228565b60405163f6c0092760e01b8152600481018990529091506000906001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8169063f6c00927906024016040805180830381865afa1580156108b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108da919061269a565b50905061093687828a85866108f28e8e8e8e8b611583565b6040516024016109059493929190612853565b60408051601f198184030181529190526020810180516001600160e01b031663172b958560e31b1790526000611800565b5090999098509650505050505050565b60008061095161115a565b600061095b611228565b60405163f6c0092760e01b8152600481018990529091506000906001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8169063f6c00927906024016040805180830381865afa1580156109c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109e9919061269a565b5060006060870152604051909150610a3e90610a0f908a90859081908a90602401612853565b60408051601f198184030181529190526020810180516001600160e01b0316638bdb391360e01b17905261184e565b50610a4881611903565b508451610a5e90610a5984826119ab565b611abe565b98600098509650505050505050565b610a75611b25565b806002811115610a8757610a87611e73565b60008381526020819052604090205460ff166002811115610aaa57610aaa611e73565b14610b18576000828152602081905260409020805482919060ff19166001836002811115610ada57610ada611e73565b0217905550817fcb31053d9df846999fdad8189e022e9af1c2069b37a00077a5e0ac41ea25bbea82604051610b0f9190611e89565b60405180910390a25b5050565b600080610b2761115a565b60005b8751811015610b9f57600080808a8481518110610b4957610b49612960565b6020908102919091018101515182528101919091526040016000205460ff166002811115610b7957610b79611e73565b03610b975760405163d3ef306f60e01b815260040160405180910390fd5b600101610b2a565b506000610baa611228565b90506000610c048260408051608081018252600080825260208201819052918101829052606081019190915250604080516080810182526001600160a01b0390921680835260006020840181905291830152606082015290565b9050610c138887600019611b64565b6000610c7b8b8b8b858b8b604051602401610c33969594939291906129af565b60408051601f198184030181529190526020810180516001600160e01b03167f945bcec90000000000000000000000000000000000000000000000000000000017905261184e565b806020019051810190610c8e9190612aca565b9050610c9c89886001611b64565b610ca68982611abe565b9b60009b509950505050505050505050565b600080610cc361115a565b600160008781526020819052604090205460ff166002811115610ce857610ce8611e73565b14610d065760405163d3ef306f60e01b815260040160405180910390fd5b6000610d10611228565b60405163f6c0092760e01b8152600481018990529091506000906001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8169063f6c00927906024016040805180830381865afa158015610d7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d9e919061269a565b506000606087015285516020870151919250610dbc91600019611bc5565b610e0588838488604051602401610dd69493929190612853565b60408051601f198184030181529190526020810180516001600160e01b031663172b958560e31b17905261184e565b50610e1a856000015186602001516001611bc5565b610a5e81611903565b600080610e2e61115a565b6000610e38611228565b60405163f6c0092760e01b8152600481018990529091506000906001600160a01b037f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c8169063f6c00927906024016040805180830381865afa158015610ea2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ec6919061269a565b50905061093681888a8586610ede8e8e8e8e8b6112b1565b604051602401610ef19493929190612853565b60408051601f198184030181529190526020810180516001600160e01b0316638bdb391360e01b1790526000611546565b600080610f2d61115a565b6000610f37611228565b90506000865160009081526020819052604090205460ff166002811115610f6057610f60611e73565b03610f7e5760405163d3ef306f60e01b815260040160405180910390fd5b60408087015190516370a0823160e01b81526001600160a01b03838116600483015260009216906370a0823190602401602060405180830381865afa158015610fcb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fef91906126c9565b90508660200151811161100a57600080935093505050611152565b6020870151900360006110698360408051608081018252600080825260208201819052918101829052606081019190915250604080516080810182526001600160a01b0390921680835260006020840181905291830152606082015290565b9050611148886040015189606001516040518060c001604052808c600001518152602001600060018111156110a0576110a0611e73565b81526020018c604001516001600160a01b031681526020018c606001516001600160a01b031681526020018681526020018c60800151815250846b033b2e3c9fd0803ce80000008c886110f391906126f8565b6110fd919061270f565b8b60405160240161111194939291906128a3565b60408051601f19818403018152919052602080820180516001600160e01b03166352bbbe2960e01b1790528c015160011015611800565b5090955093505050505b935093915050565b7f00000000000000000000000029b9131bd16859ddac4d43167aca40720dd75f7b6001600160a01b0316632f7a18816040518163ffffffff1660e01b8152600401602060405180830381865afa1580156111b8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111dc9190612b5b565b6001600160a01b0316336001600160a01b031614611226576040517f0c1d6a3f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b565b60007f00000000000000000000000029b9131bd16859ddac4d43167aca40720dd75f7b6001600160a01b03166334878f546040518163ffffffff1660e01b8152600401602060405180830381865afa158015611288573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112ac9190612b5b565b905090565b6112de60405180608001604052806060815260200160608152602001606081526020016000151581525090565b604051631f29a8cd60e31b8152600481018790526000907f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03169063f94d466890602401600060405180830381865afa158015611346573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261136e9190810190612bda565b505080519091508067ffffffffffffffff81111561138e5761138e611ef8565b6040519080825280602002602001820160405280156113b7578160200160208202803683370190505b508352815167ffffffffffffffff8111156113d4576113d4611ef8565b6040519080825280602002602001820160405280156113fd578160200160208202803683370190505b50602084015281518060005b838110156114ee5784818151811061142357611423612960565b60200260200101518660000151828151811061144157611441612960565b6001600160a01b03928316602091820292909201015286518051918c16918390811061146f5761146f612960565b60200260200101516001600160a01b0316036114ac57878660200151828151811061149c5761149c612960565b6020026020010181815250508092505b866001600160a01b0316866000015182815181106114cc576114cc612960565b60200260200101516001600160a01b0316036114e6578091505b600101611409565b508082116114fc5781611507565b611507600183612ca8565b60408051600060208201529081018a90526060810182905290925060800160408051601f19818403018152918152860152509298975050505050505050565b600080606061155486611903565b9250600061156188611903565b9050841561156d578092505b6115768661184e565b9150509450945094915050565b6115b060405180608001604052806060815260200160608152602001606081526020016000151581525090565b604051631f29a8cd60e31b8152600481018790526000907f000000000000000000000000ba12222222228d8ba445958a75a0704d566bf2c86001600160a01b03169063f94d466890602401600060405180830381865afa158015611618573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526116409190810190612bda565b505080519091508067ffffffffffffffff81111561166057611660611ef8565b604051908082528060200260200182016040528015611689578160200160208202803683370190505b508352815167ffffffffffffffff8111156116a6576116a6611ef8565b6040519080825280602002602001820160405280156116cf578160200160208202803683370190505b506020840152815160005b828110156117bc578381815181106116f4576116f4612960565b60200260200101518560000151828151811061171257611712612960565b6001600160a01b03928316602091820292909201015285518051918b16918390811061174057611740612960565b60200260200101516001600160a01b03160361177a57878560200151828151811061176d5761176d612960565b6020026020010181815250505b856001600160a01b03168560000151828151811061179a5761179a612960565b60200260200101516001600160a01b0316036117b4578091505b6001016116da565b5060016117cd856020015183611c11565b876040516020016117e093929190612cbb565b60408051601f198184030181529181528501525091979650505050505050565b600080606061180e86611903565b925083156118225761181f87611903565b91505b61182e87600019611d13565b6118378561184e565b9050611844876001611d13565b9450945094915050565b6040517f09c5eabe0000000000000000000000000000000000000000000000000000000081526060906001600160a01b037f00000000000000000000000029b9131bd16859ddac4d43167aca40720dd75f7b16906309c5eabe906118b6908590600401612ce4565b6000604051808303816000875af11580156118d5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526118fd9190810190612cf7565b92915050565b6040517fd5c2f4860000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301526000917f00000000000000000000000029b9131bd16859ddac4d43167aca40720dd75f7b9091169063d5c2f48690602401602060405180830381865afa158015611987573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118fd91906126c9565b80516060908067ffffffffffffffff8111156119c9576119c9611ef8565b6040519080825280602002602001820160405280156119f2578160200160208202803683370190505b50915060005b81811015611ab657838181518110611a1257611a12612960565b60209081029190910101516040516370a0823160e01b81526001600160a01b038781166004830152909116906370a0823190602401602060405180830381865afa158015611a64573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a8891906126c9565b611a9190612d6e565b838281518110611aa357611aa3612960565b60209081029190910101526001016119f8565b505092915050565b8151600090815b81811015611ab657600019848281518110611ae257611ae2612960565b60200260200101511215611b1d57611b1a611b15868381518110611b0857611b08612960565b6020026020010151611903565b841790565b92505b600101611ac5565b611b2e33611db2565b611226576040517f61081c1500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b825160005b81811015611bbe576001848281518110611b8557611b85612960565b60200260200101511315611bb657611bb6858281518110611ba857611ba8612960565b602002602001015184611d13565b600101611b69565b5050505050565b825160005b81811015611bbe576001848281518110611be657611be6612960565b60200260200101511115611c0957611c09858281518110611ba857611ba8612960565b600101611bca565b8151606090808310611c2657839150506118fd565b611c31600182612ca8565b90508067ffffffffffffffff811115611c4c57611c4c611ef8565b604051908082528060200260200182016040528015611c75578160200160208202803683370190505b50915060005b81811015611ab65783811015611cc857848181518110611c9d57611c9d612960565b6020026020010151838281518110611cb757611cb7612960565b602002602001018181525050611d0b565b84611cd4826001612da6565b81518110611ce457611ce4612960565b6020026020010151838281518110611cfe57611cfe612960565b6020026020010181815250505b600101611c7b565b6040517ffa30b30f0000000000000000000000000000000000000000000000000000000081526001600160a01b038381166004830152602482018390527f00000000000000000000000029b9131bd16859ddac4d43167aca40720dd75f7b169063fa30b30f90604401600060405180830381600087803b158015611d9657600080fd5b505af1158015611daa573d6000803e3d6000fd5b505050505050565b6040517f5f259aba0000000000000000000000000000000000000000000000000000000081526001600160a01b0382811660048301526000917f000000000000000000000000ad131da4bddb40ebb5ceeaea87067553d431389590911690635f259aba90602401602060405180830381865afa158015611e36573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118fd9190612db9565b600060208284031215611e6c57600080fd5b5035919050565b634e487b7160e01b600052602160045260246000fd5b6020810160038310611e9d57611e9d611e73565b91905290565b6001600160a01b0381168114611eb857600080fd5b50565b60008060008060808587031215611ed157600080fd5b843593506020850135611ee381611ea3565b93969395505050506040820135916060013590565b634e487b7160e01b600052604160045260246000fd5b6040516080810167ffffffffffffffff81118282101715611f3157611f31611ef8565b60405290565b60405160c0810167ffffffffffffffff81118282101715611f3157611f31611ef8565b60405160a0810167ffffffffffffffff81118282101715611f3157611f31611ef8565b604051601f8201601f1916810167ffffffffffffffff81118282101715611fa657611fa6611ef8565b604052919050565b803560028110611fbd57600080fd5b919050565b600067ffffffffffffffff821115611fdc57611fdc611ef8565b50601f01601f191660200190565b600082601f830112611ffb57600080fd5b813561200e61200982611fc2565b611f7d565b81815284602083860101111561202357600080fd5b816020850160208301376000918101602001919091529392505050565b8015158114611eb857600080fd5b8035611fbd81612040565b60006080828403121561206b57600080fd5b612073611f0e565b9050813561208081611ea3565b8152602082013561209081612040565b602082015260408201356120a381611ea3565b604082015260608201356120b681612040565b606082015292915050565b60008060008060e085870312156120d757600080fd5b843567ffffffffffffffff808211156120ef57600080fd5b9086019060c0828903121561210357600080fd5b61210b611f37565b8235815261211b60208401611fae565b6020820152604083013561212e81611ea3565b6040820152606083013561214181611ea3565b60608201526080838101359082015260a08301358281111561216257600080fd5b61216e8a828601611fea565b60a0830152508096505050506121878660208701612059565b939693955050505060a08201359160c0013590565b600067ffffffffffffffff8211156121b6576121b6611ef8565b5060051b60200190565b600082601f8301126121d157600080fd5b813560206121e16120098361219c565b82815260059290921b8401810191818101908684111561220057600080fd5b8286015b8481101561222457803561221781611ea3565b8352918301918301612204565b509695505050505050565b60006080828403121561224157600080fd5b612249611f0e565b9050813567ffffffffffffffff8082111561226357600080fd5b61226f858386016121c0565b835260209150818401358181111561228657600080fd5b8401601f8101861361229757600080fd5b80356122a56120098261219c565b81815260059190911b820184019084810190888311156122c457600080fd5b928501925b828410156122e2578335825292850192908501906122c9565b80868801525050505060408401359150808211156122ff57600080fd5b5061230c84828501611fea565b6040830152506120b66060830161204e565b6000806000806080858703121561233457600080fd5b84359350602085013561234681611ea3565b9250604085013561235681611ea3565b9150606085013567ffffffffffffffff81111561237257600080fd5b61237e8782880161222f565b91505092959194509250565b60038110611eb857600080fd5b600080604083850312156123aa57600080fd5b8235915060208301356123bc8161238a565b809150509250929050565b600082601f8301126123d857600080fd5b813560206123e86120098361219c565b82815260059290921b8401810191818101908684111561240757600080fd5b8286015b84811015612224578035835291830191830161240b565b600080600080600080610120878903121561243c57600080fd5b61244587611fae565b955067ffffffffffffffff6020880135111561246057600080fd5b6020870135870188601f82011261247657600080fd5b612483612009823561219c565b81358082526020808301929160051b8401018b10156124a157600080fd5b602083015b6020843560051b8501018110156125525767ffffffffffffffff813511156124cd57600080fd5b8035840160a0818e03601f190112156124e557600080fd5b6124ed611f5a565b6020820135815260408201356020820152606082013560408201526080820135606082015267ffffffffffffffff60a0830135111561252b57600080fd5b61253e8e602060a0850135850101611fea565b6080820152845250602092830192016124a6565b509650505067ffffffffffffffff6040880135111561257057600080fd5b61258088604089013589016121c0565b935061258f8860608901612059565b925067ffffffffffffffff60e088013511156125aa57600080fd5b6125ba8860e089013589016123c7565b915061010087013590509295509295509295565b6020810160258310611e9d57611e9d611e73565b6000806000606084860312156125f757600080fd5b833567ffffffffffffffff8082111561260f57600080fd5b9085019060a0828803121561262357600080fd5b61262b611f5a565b8235815260208301356020820152604083013561264781611ea3565b6040820152606083013561265a81611ea3565b606082015260808301358281111561267157600080fd5b61267d89828601611fea565b608083015250976020870135975060409096013595945050505050565b600080604083850312156126ad57600080fd5b82516126b881611ea3565b60208401519092506123bc8161238a565b6000602082840312156126db57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176118fd576118fd6126e2565b60008261272c57634e487b7160e01b600052601260045260246000fd5b500490565b600081518084526020808501945080840160005b8381101561276157815187529582019590820190600101612745565b509495945050505050565b60005b8381101561278757818101518382015260200161276f565b50506000910152565b600081518084526127a881602086016020860161276c565b601f01601f19169290920160200192915050565b8051608080845281519084018190526000916020919082019060a0860190845b818110156128015783516001600160a01b0316835292840192918401916001016127dc565b50508285015191508581038387015261281a8183612731565b92505050604083015184820360408601526128358282612790565b915050606083015161284b606086018215159052565b509392505050565b84815260006001600160a01b0380861660208401528085166040840152506080606083015261288560808301846127bc565b9695505050505050565b6002811061289f5761289f611e73565b9052565b60e08152845160e0820152600060208601516128c361010084018261288f565b5060408601516001600160a01b03908116610120840152606087015116610140830152608086015161016083015260a086015160c061018084015261290c6101a0840182612790565b91505061294e60208301866001600160a01b03808251168352602082015115156020840152806040830151166040840152506060810151151560608301525050565b60a082019390935260c0015292915050565b634e487b7160e01b600052603260045260246000fd5b600081518084526020808501945080840160005b838110156127615781516001600160a01b03168752958201959082019060010161298a565b60006101208083016129c1848b61288f565b60208481019290925288519081905261014080850192600583901b8601909101918a820160005b82811015612a4b5787850361013f190186528151805186528481015185870152604080820151908701526060808201519087015260809081015160a091870182905290612a3781880183612790565b9786019796505050908301906001016129e8565b505050508381036040850152612a618189612976565b915050612aa360608401876001600160a01b03808251168352602082015115156020840152806040830151166040840152506060810151151560608301525050565b82810360e0840152612ab58186612731565b91505082610100830152979650505050505050565b60006020808385031215612add57600080fd5b825167ffffffffffffffff811115612af457600080fd5b8301601f81018513612b0557600080fd5b8051612b136120098261219c565b81815260059190911b82018301908381019087831115612b3257600080fd5b928401925b82841015612b5057835182529284019290840190612b37565b979650505050505050565b600060208284031215612b6d57600080fd5b8151612b7881611ea3565b9392505050565b600082601f830112612b9057600080fd5b81516020612ba06120098361219c565b82815260059290921b84018101918181019086841115612bbf57600080fd5b8286015b848110156122245780518352918301918301612bc3565b600080600060608486031215612bef57600080fd5b835167ffffffffffffffff80821115612c0757600080fd5b818601915086601f830112612c1b57600080fd5b81516020612c2b6120098361219c565b82815260059290921b8401810191818101908a841115612c4a57600080fd5b948201945b83861015612c71578551612c6281611ea3565b82529482019490820190612c4f565b91890151919750909350505080821115612c8a57600080fd5b50612c9786828701612b7f565b925050604084015190509250925092565b818103818111156118fd576118fd6126e2565b838152606060208201526000612cd46060830185612731565b9050826040830152949350505050565b602081526000612b786020830184612790565b600060208284031215612d0957600080fd5b815167ffffffffffffffff811115612d2057600080fd5b8201601f81018413612d3157600080fd5b8051612d3f61200982611fc2565b818152856020838501011115612d5457600080fd5b612d6582602083016020860161276c565b95945050505050565b60007f80000000000000000000000000000000000000000000000000000000000000008203612d9f57612d9f6126e2565b5060000390565b808201808211156118fd576118fd6126e2565b600060208284031215612dcb57600080fd5b8151612b788161204056fea26469706673582212207bf56e21d1d18ab0da33b0554c791c204bc61144335bfa11220ac891b969257664736f6c63430008110033

Block Transaction Gas Used Reward
view all blocks produced

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

Validator Index Block Amount
View All Withdrawals

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

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