Skip to content
Verified contractPartialUNLICENSED

PositionManagerOwnable2StepWithShortcut

Address0x985c9dec764a50ff79d0bb764dce0537e25a865b
Balance

0 ETH

 

Transactions

20

 

Compiler

solc 0.8.21

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.21+commit.d9974bed
Language
solidity
Optimization
Yes, 200 runs
EVM version
paris
Via IR
yes
License
UNLICENSED
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,554,422
Creation transaction
0x2bae0585b3…72d55a565c
Libraries
contracts/PositionManagerOwnable2StepWithShortcut.sol:CurveMethods0xf7db…408f3d

contracts/PositionManagerOwnable2StepWithShortcut.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

import './PositionManager.sol';
import '@itb/quant-common/contracts/solidity8/utils/Ownable2StepWithShortcut.sol';

contract PositionManagerOwnable2StepWithShortcut is PositionManager, Ownable2StepWithShortcut {
    constructor(address[] memory _executors, IMinter _minter, address payable _wnative, address _crv_address, PoolsConfigParam memory _pools_config, address _merkle_distributor) PositionManager(_executors, _minter, _wnative, _crv_address, _pools_config, _merkle_distributor) {}
}

@itb/quant-common/contracts/solidity8/ITBContract.sol

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

import './utils/Withdrawable.sol';
import './utils/IWETH.sol';


/// @title ITBContract contract that implements common owner only functions accross all strategies
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract ITBContract is Withdrawable {
    using SafeERC20 for IERC20;
    event ApproveToken(address indexed token, address guy, uint256 wad);
    address payable immutable public WNATIVE;

    uint constant ONE = 1e18;

    /// @param _executors Executor addresses
    constructor(address[] memory _executors, address payable _wnative) Executable(_executors) {
        WNATIVE = _wnative;
    }

    function _percentageAmount(uint _amount, uint _percentage) internal pure returns (uint) {
        return _amount * _percentage / ONE;
    }

    /// @notice Set allowance for a given token, amount and spender
    /// @param _token Token to spend
    /// @param _guy Spender
    /// @param _wad Max amount to spend
    function _approveToken(address _token, address _guy, uint256 _wad) internal {
        if (_wad != 0)
            IERC20(_token).forceApprove(_guy, _wad);
        else
            IERC20(_token).approve(_guy, _wad);
        emit ApproveToken(_token, _guy, _wad);
    }

    /// @notice For a given token, amount and spender, check if contract can spend amount and, if necessary, set the allowance to amount
    /// @param _token Token to spend
    /// @param _guy Spender
    /// @param _amount Amount to spend
    function _checkAllowanceAndApprove(address _token, address _guy, uint256 _amount) internal {
        _checkAllowanceAndApprove(_token, _guy, _amount, _amount);
    }

    /// @notice For a given token, amount and spender, check if contract can spend amount and, if necessary, set the allowance to approval amount
    /// @param _token Token to spend
    /// @param _guy Spender
    /// @param _amount Amount to spend
    /// @param _approval_amount Amount to approve
    function _checkAllowanceAndApprove(address _token, address _guy, uint256 _amount, uint256 _approval_amount) internal {
        if (IERC20(_token).allowance(address(this), _guy) < _amount)
            _approveToken(_token, _guy, _approval_amount);
    }

    /// @notice Only owner. Set allowance for a given token, amount and spender
    /// @param _token Token to spend
    /// @param _guy Spender
    /// @param _wad Max amount to spend
    function approveToken(address _token, address _guy, uint256 _wad) external onlyOwner {
        _approveToken(_token, _guy, _wad);
    }

    /// @notice Only owner. Revoke allowance for a given token and spender
    /// @param _token Token to spend
    /// @param _guy Spender
    function revokeToken(address _token, address _guy) external onlyOwner {
        _approveToken(_token, _guy, 0);
    }

    /// @notice Only owner. Execute an arbitrary call
    /// @param _to Target address
    /// @param _value Value (i. e. msg.value)
    /// @param _data Invocation data
    function execute(address _to, uint256 _value, bytes calldata _data) external payable onlyOwner {
        (bool success, bytes memory returnData) = _to.call{ value: _value }(_data);
        require(success, string(returnData));
    }

    /// @notice Only owner. Execute multiple arbitrary calls in order
    /// @param _tos Target address for each call
    /// @param _values Value for each call (i. e. msg.value)
    /// @param _datas Invocation data for each call
    function batchExecute(address[] calldata _tos, uint256[] calldata _values, bytes[] calldata _datas) external payable onlyOwner {
        require(_tos.length == _values.length && _tos.length == _datas.length, "Arguments length mismatch");
        for (uint256 i = 0; i < _tos.length; i++) {
            (bool success, bytes memory returnData) = _tos[i].call{ value: _values[i] }(_datas[i]);
            require(success, string(returnData));
        }
    }

    function wrapNative(uint256 _amount) public onlyExecutor {
        IWETH(WNATIVE).deposit{ value: _amount }();
    }

    function unwrapNative(uint256 _amount) public onlyExecutor {
        IWETH(WNATIVE).withdraw(_amount);
    }
}

@itb/quant-common/contracts/solidity8/utils/Executable.sol

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

import "@openzeppelin/contracts/access/Ownable2Step.sol";

/// @title Base contract that implements executor related functions
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract Executable is Ownable2Step {
    mapping(address => bool) public executors;

    event ExecutorUpdated(address indexed executor, bool enabled);

    /// @param _executors Initial whitelisted executor addresses
    constructor(address[] memory _executors) Ownable(msg.sender) {
        for (uint256 i = 0; i < _executors.length; i++) {
            addExecutor(_executors[i]);
        }
    }

    /// @notice Revert if call is not being made from the owner or an executor
    modifier onlyExecutor() {
        require(owner() == msg.sender || executors[msg.sender], "Executable: caller is not the executor");
        _;
    }

    /// @notice Only owner. Add an executor
    /// @param _executor New executor address
    function addExecutor(address _executor) public onlyOwner {
        emit ExecutorUpdated(_executor, true);
        executors[_executor] = true;
    }

    /// @notice Only owner. Remove an executor
    /// @param _executor Executor address to remove
    function removeExecutor(address _executor) external onlyOwner {
        emit ExecutorUpdated(_executor, false);
        executors[_executor] = false;
    }
}

@itb/quant-common/contracts/solidity8/utils/IWETH.sol

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

interface IWETH {
    function name() external view returns (string memory);
    function symbol() external view returns (string memory);
    function decimals() external view returns (uint8);

    event Approval(address indexed src, address indexed guy, uint256 wad);
    event Transfer(address indexed src, address indexed dst, uint256 wad);
    event Deposit(address indexed dst, uint256 wad);
    event Withdrawal(address indexed src, uint256 wad);

    function balanceOf(address) external view returns (uint256);
    function allowance(address, address) external view returns (uint256);

    fallback() external payable;
    receive() external payable;
    function deposit() external payable;
    function withdraw(uint256 wad) external;
    function totalSupply() external view returns (uint256);
    function approve(address guy, uint256 wad) external returns (bool);
    function transfer(address dst, uint256 wad) external returns (bool);
    function transferFrom(address src, address dst, uint256 wad) external returns (bool);
}

@itb/quant-common/contracts/solidity8/utils/Ownable2StepWithShortcut.sol

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

import "@openzeppelin/contracts/access/Ownable2Step.sol";

abstract contract Ownable2StepWithShortcut is Ownable2Step {
    function transferOwnership1Step(address newOwner) public onlyOwner {
        require(newOwner != address(0), "ITBOwnable: zero address");
        _transferOwnership(newOwner);
    }
}

@itb/quant-common/contracts/solidity8/utils/Withdrawable.sol

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

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import './Executable.sol';

/**
    Ensures that any contract that inherits from this contract is able to
    withdraw funds that are accidentally received or stuck.
 */

/// @title Base contract that implements withdrawal related functions
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract Withdrawable is Executable {
    using SafeERC20 for IERC20;
    address constant ETHER = address(0);

    event LogWithdraw(
        address indexed _to,
        address indexed _asset_address,
        uint256 amount
    );

    receive() external payable {}

    /// @notice ERC20 or ETH balance of this contract given a token address
    /// @param _asset_address Token address or address(0) for ETH
    /// @return Balance    
    function _erc20OrNativeBalance(address _asset_address) internal view returns (uint256) {
        return _asset_address == ETHER ? _nativeBalance() : _erc20Balance(_asset_address);
    }
    
    function _erc20Balance(address _asset_address) internal view returns (uint256) {
        return IERC20(_asset_address).balanceOf(address(this));
    }

    function _nativeBalance() internal view returns (uint256) {
        return address(this).balance;
    }
    
    /// @notice ERC20 balance of given account
    /// @param _asset_address Token address 
    /// @param _account Account address 
    /// @return Balance  
    function balanceOf(address _asset_address, address _account) public view returns (uint256) {
        return IERC20(_asset_address).balanceOf(_account);
    }

    /// @notice Send the given amount of the given token or ETH to the given receiver
    /// @param _asset_address Token address or address(0) for ETH
    /// @param _amount Amount to send
    /// @param _to Receiver address
    function _withdraw_to(address _asset_address, uint256 _amount, address payable _to) internal {
        require(_to != address(0), 'Invalid address');
        uint256 balance = _erc20OrNativeBalance(_asset_address);
        require(balance >= _amount, 'Insufficient funds');
        if (_asset_address == ETHER) {
            (bool success, ) = _to.call{value: _amount}(''); /* carry gas over so it works with contracts with custom fallback, we dont care about reentrancy on onlyOwner */
            require(success, 'Native transfer failed.');
        } else
            IERC20(_asset_address).safeTransfer(_to, _amount);
        emit LogWithdraw(_to, _asset_address, _amount);
    }

    /// @notice Only owner. Send the given amount of the given token or ETH to the caller
    /// @param _asset_address Token address or address(0) for ETH
    /// @param _amount Amount to send
    function withdraw(address _asset_address, uint256 _amount) external onlyOwner {
        _withdraw_to(_asset_address, _amount, payable(msg.sender));
    }

    /// @notice Only owner. Send the given amount of the given token or ETH to the given receiver
    /// @param _asset_address Token address or address(0) for ETH
    /// @param _amount Amount to send
    /// @param _to Receiver address
    function withdrawTo(address _asset_address, uint256 _amount, address payable _to) external onlyOwner {
        _withdraw_to(_asset_address, _amount, _to);
    }

    /// @notice Only owner. Send its entire balance of the given token or ETH to the caller
    /// @param _asset_address Token address or address(0) for ETH
    function withdrawAll(address _asset_address) external onlyOwner {
        uint256 balance = _erc20OrNativeBalance(_asset_address);
        _withdraw_to(_asset_address, balance, payable(msg.sender));
    }

    /// @notice Only owner. Send its entire balance of the given token or ETH to the given receiver
    /// @param _asset_address Token address or address(0) for ETH
    /// @param _to Receiver address
    function withdrawAllTo(address _asset_address, address payable _to) external onlyOwner {
        uint256 balance = _erc20OrNativeBalance(_asset_address);
        _withdraw_to(_asset_address, balance, _to);
    }
}

@openzeppelin/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

@openzeppelin/contracts/interfaces/IERC1363.sol

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

pragma solidity >=0.6.2;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/interfaces/IERC165.sol

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

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

@openzeppelin/contracts/token/ERC20/IERC20.sol

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@openzeppelin/contracts/utils/Context.sol

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

pragma solidity ^0.8.20;

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

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

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

@openzeppelin/contracts/utils/introspection/IERC165.sol

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

pragma solidity >=0.4.16;

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

contracts/Base.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

import '@itb/quant-common/contracts/solidity8/ITBContract.sol';
import './curve/ILiquidityGaugeV2.sol';
import './curve/IMinter.sol';

/// @title Base contract that implements common owner only functions accross all strategies
/// @author IntoTheBlock Corp
/// @dev Abstract
abstract contract Base is ITBContract {
    event UpdateMinter(IMinter old_minter, IMinter new_minter);

    address constant public ETH_COIN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    
    IMinter public minter;

    /// @param _executors Array of executor addresses.
    /// @param _minter CRV minter.
    /// @param _wnative Address of wrap native token.
    constructor(address[] memory _executors, IMinter _minter, address payable _wnative) ITBContract(_executors, _wnative) {
        updateMinter(_minter);
    }

    /// @notice Only owner. Update minter of CRV.
    /// @param _minter Minter address.
    function updateMinter(IMinter _minter) public onlyOwner {
        emit UpdateMinter(minter, _minter);
        minter = _minter;
    }
}

contracts/IPositionManager.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

import './convex/IConvexRewards.sol';

struct MetaPool {
    bool is_meta_pool;
    address base_pool;
    address base_pool_coin;
}

enum GaugeVersion { V1, V2, V3, REWARD, VSidechain, V4, V6, NULLGAUGE }
    
struct PositionConfig {
    address pool;
    address gauge;
    GaugeVersion gauge_version;
    address coin;
    MetaPool meta_pool;
    bool useWrap;
}

interface IPositionManager {
  function cvx_booster() external view returns (address);

  function pool_cvx_id() external view returns (uint);

  function currentBalance(address _token) external view returns (uint);

  function CRV_ADDRESS() external view returns (address);

  function CVX_ADDRESS() external view returns (address);

  function ETH_COIN() external view returns (address);

  function WNATIVE() external view returns (address);

  function lpts(address _pool) external view returns (address);
  function getCoins(address _pool) external view returns (address[] memory);
  function use_uint_indexes(address _pool) external view returns (bool);

  function coinIndex(address _pool, address _coin) external view returns (uint);

  function position_config() external view returns (PositionConfig memory);

  function getUnderlyingCoin(address _coin) external view returns (address);

  function getUnderlyingAmountsFromLPT(uint _lpt_amount) external view returns (address[] memory, uint256[] memory);

  function stakedLPTBalance() external view returns (uint);

  function totalLPTBalance() external view returns (uint);

  function rewardsAddress() external view returns (address);

  function rewardsContract() external view returns (IConvexRewards);

  function getRewardLength() external view returns (uint);
}

contracts/PositionManager.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

import './Base.sol';
import './libraries/CurveMethods.sol';
import './curve/ICurvePool.sol';
import './curve/IGaugeReward.sol';
import './curve/ICurvePoolDynamic.sol';
import './interfaces/merkl/IMerkleDistributor.sol';

struct MerkleClaimData {
    address[] users;
    address[] tokens;
    uint[] values;
    bytes32[][] proof;
}

/// @title PositionManager that targets Curve pools
/// @author IntoTheBlock Corp
/// @notice Assembles a staking position in Curve.
contract PositionManager is Base {
    event AddLiquidity(address indexed pool, uint[] coin_amounts, uint lpt_amount);
    event RemoveLiquidity(address indexed pool, uint[] coin_amounts, uint lpt_amount);
    event Stake(address indexed gauge, uint lpt_amount);
    event Unstake(address indexed gauge, uint lpt_amount);
    event UpdatePool(address indexed pool, address new_lpt, address[] new_coins, bool new_use_uint_index, bool new_use_underlying, bool new_is_dynamic);
    event UpdatePoolZap(address indexed pool, address old_zap, address new_zap);
    event WhitelistedPoolUpdated(address indexed pool, bool whitelisted);
    event UpdatePositionConfig(PositionConfig old_position_config, PositionConfig new_position_config);
    event ClaimRewards(address[] rewards_addresses, uint[] claimed_amounts);
    event UpdateMerkleDistributor(address merkle_distributor);
    event ClaimMerkleRewards(address[] tokens, uint[] values);

    address public immutable CRV_ADDRESS;
    IMerkleDistributor public merkle_distributor;

    mapping(address => address) public lpts;
    mapping(address => address[]) public coins;
    mapping(address => bool) public use_uint_indexes;
    mapping(address => bool) public use_underlyings;
    mapping(address => address) public zaps;
    mapping(address => bool) public is_dynamic;

    mapping(address => bool) public whitelisted_pools;

    PositionConfig public position_config;

    struct PoolsConfigParam {    // Index matching struct used to build initial mappings
        address[] pools;         // Array of pool addresses
        address[] lpts;          // Array of LPT addresses
        address[][] coins;       // Array of coin addresses arrays
        bool[] use_uint_indexes; // Array of boolean with true meaning use uint Curve pool ABI
        bool[] use_underlyings;  // Array of boolean with true meaning interact with pool using underlying tokens
        address[] zaps;          // Array of zap addresses. address(0) for no zap
        bool[] is_dynamic;       // Array of boolean with true meaning add/remove liquidity uses dynamic length arrays
    }

    /// @param _executors Array of executor addresses.
    /// @param _minter CRV minter.
    /// @param _wnative Address of wrap native token.
    /// @param _crv_address Address of CRV token.
    /// @param _pools_config Pools configuration. See PoolsConfigParam struct.
    /// @param _merkle_distributor Merkl distributor address.
    constructor(
        address[] memory _executors,
        IMinter _minter,
        address payable _wnative,
        address _crv_address,
        PoolsConfigParam memory _pools_config,
        address _merkle_distributor
    ) Base(_executors, _minter, _wnative) {
        CRV_ADDRESS = _crv_address;
        for (uint i = 0; i < _pools_config.pools.length; i++) {
            address p = _pools_config.pools[i];
            _updatePool(p, _pools_config.lpts[i], _pools_config.coins[i], _pools_config.use_uint_indexes[i], _pools_config.use_underlyings[i], _pools_config.is_dynamic[i]);
            _updatePoolZap(p, _pools_config.zaps[i]);
        }
        if (_merkle_distributor != address(0))
            updateMerkleDistributor(_merkle_distributor);
    }

    function VERSION() pure external virtual returns (string memory) {
        return "1.0.0";
    }

    modifier hasConfig() {
        require(position_config.pool != address(0), 'A3'); // position_config is missing
        _;
    }

    /* View functions */

    function _isMultipleCoins() internal view returns (bool) {
        return position_config.coin == address(0);
    }

    function _isMetapool() internal view returns (bool) {
        return position_config.meta_pool.is_meta_pool;
    }

    function _LPTIndex() internal view returns (uint) {
        return coinIndex(position_config.pool, lpts[position_config.meta_pool.base_pool]);
    }

    function getUnderlyingCoin(address _coin) external virtual view returns (address) {
        return _coin;
    }

    function idleLPTBalance() public virtual view returns (uint) {
        return currentBalance(lpts[position_config.pool]);
    }

    function stakedLPTBalance() public virtual view returns (uint) {
        if (position_config.gauge_version == GaugeVersion.NULLGAUGE)
            return 0;
        return currentBalance(position_config.gauge);
    }

    function totalLPTBalance() public virtual view returns (uint) {
        return idleLPTBalance() + stakedLPTBalance();
    }

    function getCoins(address _pool) external view returns (address[] memory) {
        return coins[_pool];
    }

    /// @notice View function to get coin index in the pool coin array.
    /// @param _pool Pool address.
    /// @param _coin Coin to search in the pool coin array.
    /// @return _coin_index Coin index in the pool coin array.
    function coinIndex(address _pool, address _coin) public view returns (uint) {
        for (uint i = 0; i < coins[_pool].length; i++)
            if (coins[_pool][i] == _coin)
                return i;
        revert('A1'); // Missing coin
    }

    /// @notice View function to get balance of the position manager in a given token or ETH.
    /// @param _a Address to get balance of position manager.
    /// @return _balance_of balance of the position manager
    function currentBalance(address _a) public view returns(uint) {
        return CurveMethods.currentBalance(address(this), _a);
    }

    /// @notice Get all rewards tokens in the gauge given by position_config
    /// @return rewards_addresses
    function getRewardsTokens() public virtual view returns (address[] memory rewards_addresses) {
        return CurveMethods.getRewardsTokens(address(this));
    }

    /// @notice View function to get underlyings addresses
    /// @return assets all underlying assets
    function getPositionAssets() external virtual view returns (address[] memory assets) {
        return CurveMethods.getPositionAssets(address(this), _isMultipleCoins(), _isMetapool());
    }

    /// @notice Get underlyings address and amounts
    /// @return assets all underlying assets
    /// @return amounts amounts of all underlying assets
    function getUnderlyings() external view returns (address[] memory assets, uint256[] memory amounts) {
        return CurveMethods.getUnderlyings(address(this));
    }

    /// @notice Get underlyings address and amounts by lpt_amount given
    /// @return assets all underlying assets
    /// @return amounts amounts of all underlying assets
    function getUnderlyingAmountsFromLPT(uint lpt_amount) external virtual view returns (address[] memory assets, uint256[] memory amounts) {
        return CurveMethods.getUnderlyingAmountsFromLPT(address(this), _isMultipleCoins(), _isMetapool(), lpt_amount);
    }
    
    /// @notice Get reward length in the gauge given by position_config
    /// @return reward_length  
    function getRewardLength() external virtual view returns (uint) {
        return CurveMethods.getRewardLength(address(this));
    }

    /* Admin functions */

    /// @notice Updating the pool information in position manager.
    /// @param _pool Pool address.
    /// @param _lpt LPT address.
    /// @param _coins Array of coins.
    /// @param _use_uint_index If the parameter "i" is uint in the function remove_liquidity_one_coin then is true.
    /// @param _use_underlying If True, deposit underlying assets instead of wrapped assets.
    /// @param _is_dynamic If True, use dynamic length arrays.
    function _updatePool(address _pool, address _lpt, address[] memory _coins, bool _use_uint_index, bool _use_underlying, bool _is_dynamic) internal {
        lpts[_pool] = _lpt; /* we could use registry get_lp_tokens or pool#token, pool#lp_token, but curve  has a history of not keeping registry up to date. e. g. atricrypto3 polygon */
        coins[_pool] = _coins;
        use_uint_indexes[_pool] = _use_uint_index;
        use_underlyings[_pool] = _use_underlying;
        is_dynamic[_pool] = _is_dynamic;
    }

    /// @notice Updating the pool zap in position manager. 
    /// @param _pool Pool address.
    /// @param _zap Zap address.
    /// @dev Zaps are used for wrapping and unwrapping underlying assets when depositing into or withdrawing from pools.
    function _updatePoolZap(address _pool, address _zap) internal {
        zaps[_pool] = _zap;
    }

    function updatePositionConfig(PositionConfig memory _position_config) external onlyOwner {
        emit UpdatePositionConfig(position_config, _position_config);
        position_config = _position_config;
    }
    
    /// @notice Only owner. Updating the pool information in position manager.
    /// @param _pool Pool address.
    /// @param _lpt LPT address.
    /// @param _coins Array of coins.
    /// @param _use_uint_index If the parameter "i" is uint in the function remove_liquidity_one_coin then is true.
    /// @param _use_underlying If True, deposit underlying assets instead of wrapped assets.
    /// @param _is_dynamic If True, use dynamic length arrays.
    function updatePool(address _pool, address _lpt, address[] memory _coins, bool _use_uint_index, bool _use_underlying, bool _is_dynamic) external onlyOwner {
        emit UpdatePool(_pool, _lpt, _coins, _use_uint_index, _use_underlying, _is_dynamic);
        _updatePool(_pool, _lpt, _coins, _use_uint_index, _use_underlying, _is_dynamic);
    }

    /// @notice Only owner. Updating the pool zap in position manager. 
    /// @param _pool Pool address.
    /// @param _zap Zap address.
    /// @dev Zaps are used for wrapping and unwrapping underlying assets when depositing into or withdrawing from pools.
    function updatePoolZap(address _pool, address _zap) external onlyOwner {
        emit UpdatePoolZap(_pool, zaps[_pool], _zap);
        _updatePoolZap(_pool, _zap);
        
    }

    /// @notice Only owner. Add pool to the whitelist in position manager.
    /// @param _pool Pool to add to the whitelist.
    function whitelistPool(address _pool) external onlyOwner {
        if (whitelisted_pools[_pool])
            return;
        whitelisted_pools[_pool] = true;
        emit WhitelistedPoolUpdated(_pool, true);
    }

    /// @notice Only owner. Disable pool, delete pool from the whitelist in position manager.
    /// @param _pool Pool to remove from the whitelist.
    function disablePool(address _pool) external onlyOwner {
        if (!whitelisted_pools[_pool])
            return;
        whitelisted_pools[_pool] = false;
        emit WhitelistedPoolUpdated(_pool, false);
    }

    /* Executor functions */

    /// @notice Add liquidity to pool with multiple amounts.
    /// @param _pool Pool address.
    /// @param _amounts Array of coin amounts to be added.
    /// @param _value Amount of ETH.
    /// @param _min_lpts_out Amount min out of LPT.
    /// @return lpt_amount Amount of LPT obtained.
    function _addLiquidity(address _pool, uint[] memory _amounts, uint _value, uint _min_lpts_out) internal virtual returns(uint lpt_amount) {
        uint start_lpt = currentBalance(lpts[_pool]);
        if (is_dynamic[_pool])
            _addLiquidityDynamic(_pool, _amounts, _value, _min_lpts_out);
        else {
            uint coins_count = coins[_pool].length;
            if (coins_count == 2)
                _addLiquidity2(_pool, _amounts, _value, _min_lpts_out);
            else if (coins_count == 3)
                _addLiquidity3(_pool, _amounts, _value, _min_lpts_out);
            else if (coins_count == 4)
                _addLiquidity4(_pool, _amounts, _value, _min_lpts_out);
            else
                revert('Missing implementation');
        }
        
        lpt_amount = currentBalance(lpts[_pool]) - start_lpt;
        emit AddLiquidity(_pool, _amounts, lpt_amount);
    }

    /// @notice Add liquidity to pool with multiple amounts.
    /// @param _pool Pool address.
    /// @param _amounts Array of coin amounts to be added.
    /// @param _value Amount of ETH.
    /// @param _min_lpts_out Amount min out of LPT.
    function _addLiquidityDynamic(address _pool, uint[] memory _amounts, uint _value, uint _min_lpts_out) internal {
        ICurvePoolDynamic deposit = ICurvePoolDynamic(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        /* approval required if not eth only */
        deposit.add_liquidity{ value: _value }(_amounts, _min_lpts_out);
    }

    /// @notice Add liquidity to pool with 2 coins.
    /// @param _pool Pool address.
    /// @param _coin_amounts Array of coin amounts to be added.
    /// @param _value Amount of ETH.
    function _addLiquidity2(address _pool, uint[] memory _coin_amounts, uint _value, uint _min_lpts_out) internal {
        uint[2] memory amounts;
        amounts[0] = _coin_amounts[0];
        amounts[1] = _coin_amounts[1];
        ICurvePool deposit = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        /* approval required if not eth only */
        if (use_underlyings[_pool])
            deposit.add_liquidity{ value: _value }(amounts, _min_lpts_out, true);
        else
            deposit.add_liquidity{ value: _value }(amounts, _min_lpts_out);
    }

    /// @notice Add liquidity to pool with 3 coins.
    /// @param _pool Pool address.
    /// @param _coin_amounts Array of coin amounts to be added.
    /// @param _value Amount of ETH.
    function _addLiquidity3(address _pool, uint[] memory _coin_amounts, uint _value, uint _min_lpts_out) internal {
        uint[3] memory amounts;
        amounts[0] = _coin_amounts[0];
        amounts[1] = _coin_amounts[1];
        amounts[2] = _coin_amounts[2];
        ICurvePool deposit = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        /* approval required if not eth only */
        if (use_underlyings[_pool])
            deposit.add_liquidity{ value: _value }(amounts, _min_lpts_out, true);
        else
            deposit.add_liquidity{ value: _value }(amounts, _min_lpts_out);
    }

    /// @notice Add liquidity to pool with 4 coins.
    /// @param _pool Pool address.
    /// @param _coin_amounts Array of coin amounts to be added.
    /// @param _value Amount of ETH.
    function _addLiquidity4(address _pool, uint[] memory _coin_amounts, uint _value, uint _min_lpts_out) internal {
        uint[4] memory amounts;
        amounts[0] = _coin_amounts[0];
        amounts[1] = _coin_amounts[1];
        amounts[2] = _coin_amounts[2];
        amounts[3] = _coin_amounts[3];
        ICurvePool deposit = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        /* approval required if not eth only */
        if (use_underlyings[_pool])
            deposit.add_liquidity{ value: _value }(amounts, _min_lpts_out, true);
        else
            deposit.add_liquidity{ value: _value }(amounts, _min_lpts_out);
    }

    /// @notice Remove liquidity to pool with 2 coins.
    /// @param _pool Pool address.
    /// @param _lpt_amount Amount of LPT to be removed.
    function _removeLiquidityAllCoinsDynamic(address _pool, uint _lpt_amount, uint[] memory _min_coins_amount) internal {
        ICurvePoolDynamic deposit = ICurvePoolDynamic(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        /* approval required if zap */
        deposit.remove_liquidity(_lpt_amount, _min_coins_amount);
    }

    /// @notice Remove liquidity to pool with 2 coins.
    /// @param _pool Pool address.
    /// @param _lpt_amount Amount of LPT to be removed.
    function _removeLiquidityAllCoins2(address _pool, uint _lpt_amount, uint[] memory _min_coins_amount) internal {
        ICurvePool deposit = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        uint[2] memory min_coins;
        min_coins[0] = _min_coins_amount[0];
        min_coins[1] = _min_coins_amount[1];
        /* approval required if zap */
        if (use_underlyings[_pool])
            deposit.remove_liquidity(_lpt_amount, min_coins, true);
        else
            deposit.remove_liquidity(_lpt_amount, min_coins);
        
    }

    /// @notice Remove liquidity to pool with 3 coins.
    /// @param _pool Pool address.
    /// @param _lpt_amount Amount of LPT to be removed.
    function _removeLiquidityAllCoins3(address _pool, uint _lpt_amount, uint[] memory _min_coins_amount) internal {
        ICurvePool deposit = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        uint[3] memory min_coins;
        min_coins[0] = _min_coins_amount[0];
        min_coins[1] = _min_coins_amount[1];
        min_coins[2] = _min_coins_amount[2];
        /* approval required if zap */
        if (use_underlyings[_pool])
            deposit.remove_liquidity(_lpt_amount, min_coins, true);
        else
            deposit.remove_liquidity(_lpt_amount, min_coins);
    }

    /// @notice Remove liquidity to pool with 4 coins.
    /// @param _pool Pool address.
    /// @param _lpt_amount Amount of LPT to be removed.
    function _removeLiquidityAllCoins4(address _pool, uint _lpt_amount, uint[] memory _min_coins_amount) internal {
        ICurvePool deposit = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        uint[4] memory min_coins;
        min_coins[0] = _min_coins_amount[0];
        min_coins[1] = _min_coins_amount[1];
        min_coins[2] = _min_coins_amount[2];
        min_coins[3] = _min_coins_amount[3];
        /* approval required if zap */
        if (use_underlyings[_pool])
            deposit.remove_liquidity(_lpt_amount, min_coins, true);
        else
            deposit.remove_liquidity(_lpt_amount, min_coins);
    }

    function _assembleMetapool(uint _min_lpts_out, uint _amount_in) internal virtual returns (uint) {
        return addLiquidityAndStakeMeta(position_config.pool, position_config.meta_pool.base_pool_coin, _amount_in, position_config.gauge, _min_lpts_out, position_config.meta_pool.base_pool);
    }

    function _assembleMultipleCoins(uint _min_lpts_out, uint[] memory _amounts_in) internal virtual returns (uint) {
        uint total_amount_in;
        for (uint256 i = 0; i < _amounts_in.length; i++)
            total_amount_in += _amounts_in[i];
        if (total_amount_in == 0) 
            return 0;
        return addLiquidityAllCoinsAndStake(position_config.pool, _amounts_in, position_config.gauge, _min_lpts_out);
    }

    function _assembleOneCoin(uint _min_lpts_out, uint _amount_in) internal virtual returns (uint) {
        if (_amount_in == 0) 
            return 0;
        return addLiquidityAndStake(position_config.pool, position_config.coin, _amount_in, position_config.gauge, _min_lpts_out);
    }

    function _disassembleMetapool(uint _min_coin_out, uint _lpt_amount) internal virtual returns (uint) {
        return unstakeAndRemoveLiquidityMeta(position_config.pool, position_config.coin, _lpt_amount, position_config.gauge, _min_coin_out, position_config.meta_pool.base_pool);
    }

    function _disassembleMultipleCoins(uint[] memory _min_coins_out, uint _lpt_amount) internal virtual returns (uint[] memory) {
        return unstakeAndRemoveLiquidityAllCoins(position_config.pool, _lpt_amount, position_config.gauge, _min_coins_out);
    }

    function _disassembleOneCoin(uint _min_coin_out, uint _lpt_amount) internal virtual returns (uint) {
        return unstakeAndRemoveLiquidity(position_config.pool, position_config.coin, _lpt_amount, position_config.gauge, _min_coin_out);
    }

    function _stakeBeforeDisassemble(uint _lpt_amount) internal virtual {
        stake(position_config.gauge, _lpt_amount);
    }

    function _mint(address _gauge) internal virtual {
        if (_gauge == address(0))
            return;
        minter.mint(_gauge);
    }

    /// @notice Only executor. Add a given amount of coin to pool.
    /// @param _pool Pool address to add liquidity.
    /// @param _coin Address of the coin to add to pool.
    /// @param _coin_amount Amount of coin to add to pool.
    /// @return lpt_amount Amount of LPT obtained.
    function addLiquidity(address _pool, address _coin, uint _coin_amount, uint _min_lpts_out) public onlyExecutor returns(uint) {
        require(whitelisted_pools[_pool], "A2"); // Pool is not whitelisted

        uint value = _coin == ETH_COIN ? _coin_amount : 0;
        uint[] memory amounts = new uint[](coins[_pool].length);
        amounts[coinIndex(_pool, _coin)] = _coin_amount;
        return _addLiquidity(_pool, amounts, value, _min_lpts_out);
    }

    /// @notice Only executor. Add liquidity with multiple coins to pool.
    /// @param _pool Pool address to add liquidity.
    /// @param _coin_amounts Array of coin amounts to be added.
    /// @return lpt_amount Amount of LPT obtained.
    function addLiquidityAllCoins(address _pool, uint[] memory _coin_amounts, uint _min_lpts_out) public onlyExecutor returns(uint) {
        require(whitelisted_pools[_pool], "A2"); //Pool is not whitelisted
        
        uint value;
        for (uint i = 0; i < coins[_pool].length; i++)
            if (coins[_pool][i] == ETH_COIN)
                value = _coin_amounts[i];

        return _addLiquidity(_pool, _coin_amounts, value, _min_lpts_out);
    }

    /// @notice Only executor. Remove a given amount of LPT in a given coin.
    /// @param _pool Pool address to remove liquidity.
    /// @param _coin Address of the coin to get from pool.
    /// @param _lpt_amount Amount of LPT to be removed.
    /// @return coin_amount Amount of coin obtained.
    function removeLiquidity(address _pool, address _coin, uint _lpt_amount, uint _min_coin_out) public onlyExecutor returns(uint) {
        require(whitelisted_pools[_pool], "A2"); // Pool is not whitelisted

        ICurvePool p = ICurvePool(zaps[_pool] == address(0) ? _pool : zaps[_pool]);
        uint ci = coinIndex(_pool, _coin);

        uint start_coin = currentBalance(_coin);
        bool use_underlying = use_underlyings[_pool];
        if (use_uint_indexes[_pool]) {
            if (use_underlying)
                p.remove_liquidity_one_coin(_lpt_amount, ci, _min_coin_out, true);
            else 
                p.remove_liquidity_one_coin(_lpt_amount, ci, _min_coin_out);
        }
        else {
            if (use_underlying)
                p.remove_liquidity_one_coin(_lpt_amount, int128(uint128(ci)), _min_coin_out, true);
            else
                p.remove_liquidity_one_coin(_lpt_amount, int128(uint128(ci)), _min_coin_out);
        }
        uint removed = currentBalance(_coin) - start_coin;
        uint coins_count = coins[_pool].length;
        uint[] memory out_amounts = new uint[](coins_count);
        out_amounts[ci] = removed;
        emit RemoveLiquidity(_pool, out_amounts, _lpt_amount);
        return removed;
    }

    /// @notice Only executor. Remove a given amount of LPT in multiple coins.
    /// @param _pool Pool address to remove liquidity.
    /// @param _lpt_amount Amount of LPT to be removed.
    function removeLiquidityAllCoins(address _pool, uint _lpt_amount, uint[] memory _min_coins_amount) public onlyExecutor returns (uint[] memory) {
        require(whitelisted_pools[_pool], "A2"); // Pool is not whitelisted

        uint coins_count = coins[_pool].length;
        uint[] memory before_coins = new uint[](coins_count);
        for (uint i = 0; i < coins_count; i++)
            before_coins[i] = currentBalance(coins[_pool][i]);
        if (is_dynamic[_pool])
            _removeLiquidityAllCoinsDynamic(_pool, _lpt_amount, _min_coins_amount);
        else {
            if (coins_count == 2)
                _removeLiquidityAllCoins2(_pool, _lpt_amount, _min_coins_amount);
            else if (coins_count == 3)
                _removeLiquidityAllCoins3(_pool, _lpt_amount, _min_coins_amount);
            else if (coins_count == 4)
                _removeLiquidityAllCoins4(_pool, _lpt_amount, _min_coins_amount);
            else
                revert('Missing implementation');
        }
        uint[] memory out_amounts = new uint[](coins_count);
        for (uint i = 0; i < coins_count; i++)
            out_amounts[i] = currentBalance(coins[_pool][i]) - before_coins[i];
        emit RemoveLiquidity(_pool, out_amounts, _lpt_amount);
        return out_amounts;
    }

    /// @notice Only executor. Stake a given amount of LPT in a gauge.
    /// @param _gauge Address of the gauge to stake LPT.
    /// @param _lpt_amount Amount of LPT to add in gauge.
    function stake(address _gauge, uint _lpt_amount) public virtual onlyExecutor {
        if (_gauge == address(0))
            return;
        /* approval required */
        ILiquidityGaugeV2(_gauge).deposit(_lpt_amount);
        emit Stake(_gauge, _lpt_amount);
    }

    /// @notice Only executor. Unstake a given amount of LPT from gauge.
    /// @param _gauge Address of the gauge to unstake LPT.
    /// @param _lpt_amount Amount of LPT to remove from gauge.
    function unstake(address _gauge, uint _lpt_amount) public virtual onlyExecutor {
        if (_gauge == address(0))
            return;
        ILiquidityGaugeV2(_gauge).withdraw(_lpt_amount);
        emit Unstake(_gauge, _lpt_amount);
    }

    /// @notice Only executor. Add liquidity with 1 coin to pool and stake the amount of LPT obtained in a gauge.
    /// @param _pool Pool address to add liquidity.
    /// @param _coin Address of the coin to add to pool.
    /// @param _coin_amount Amount of coin to add to pool.
    /// @param _gauge Address of the gauge to stake LPT.
    /// @return lpt_amount Amount of LPT staked in gauge.
    function addLiquidityAndStake(address _pool, address _coin, uint _coin_amount, address _gauge, uint _min_lpts_out) public virtual onlyExecutor returns(uint) {
        uint out = addLiquidity(_pool, _coin, _coin_amount, _min_lpts_out);
        stake(_gauge, out);
        return out;
    }

    /// @notice Only executor. Add liquidity with multiple coins to pool and stake the amount of LPT obtained in a gauge.
    /// @param _pool Pool address to add liquidity.
    /// @param _coin_amounts Array of coin amounts to be added.
    /// @param _gauge Address of the gauge to stake LPT.
    /// @return lpt_amount Amount of LPT staked in gauge.
    function addLiquidityAllCoinsAndStake(address _pool, uint[] memory _coin_amounts, address _gauge, uint _min_lpts_out) public virtual onlyExecutor returns(uint) {
        uint out = addLiquidityAllCoins(_pool, _coin_amounts, _min_lpts_out);
        stake(_gauge, out);
        return out;
    }

    /// @notice Only executor. Add liquidity to meta pool and stake the amount of LPT obtained in a gauge.
    /// @param _pool Pool address to add liquidity.
    /// @param _coin Address of the coin to add to base pool.
    /// @param _coin_amount Amount of coin to add to base pool.
    /// @param _gauge Address of the gauge to stake LPT.
    /// @param _base_pool Base pool address to add to pool.
    /// @return lpt_amount Amount of LPT staked in gauge.
    function addLiquidityAndStakeMeta(address _pool, address _coin, uint _coin_amount, address _gauge, uint _min_lpts_out, address _base_pool) public virtual onlyExecutor returns(uint) {
        address base_pool_token = lpts[_base_pool];
        uint base_lpt_amount = addLiquidity(_base_pool, _coin, _coin_amount, 0);
        return addLiquidityAndStake(_pool, base_pool_token, base_lpt_amount, _gauge, _min_lpts_out);
    }

    /// @notice Only executor. Unstake a given amount of LPT from gauge and remove the amount of LPT unstaked from the pool.
    /// @param _pool Pool address to remove liquidity.
    /// @param _coin Address of the coin to get from pool.
    /// @param _lpt_amount Amount of LPT to be unstaked.
    /// @param _gauge Address of the gauge to unstake LPT.
    /// @return coin_amount Amount of coin obtained.
    function unstakeAndRemoveLiquidity(address _pool, address _coin, uint _lpt_amount, address _gauge, uint _min_coin_out) public virtual onlyExecutor returns(uint) {
        unstake(_gauge, _lpt_amount);
        return removeLiquidity(_pool, _coin, _lpt_amount, _min_coin_out);
    }

    /// @notice Only executor. Unstake a given amount of LPT from gauge and remove the amount of LPT unstaked from the pool in multiple coins.
    /// @param _pool Pool address to remove liquidity.
    /// @param _lpt_amount Amount of LPT to be unstaked.
    /// @param _gauge Address of the gauge to unstake LPT.
    function unstakeAndRemoveLiquidityAllCoins(address _pool, uint _lpt_amount, address _gauge, uint[] memory _min_coins_amount) public virtual onlyExecutor returns (uint[] memory) {
        unstake(_gauge, _lpt_amount);
        return removeLiquidityAllCoins(_pool, _lpt_amount, _min_coins_amount);
    }

    /// @notice Only executor. Unstake a given amount of LPT from gauge and remove the amount of LPT unstaked from the meta pool.
    /// @param _pool Pool address to remove liquidity to get base pool.
    /// @param _coin Address of the coin to get from base pool.
    /// @param _lpt_amount Amount of LPT (_pool) to be unstaked.
    /// @param _gauge Address of the gauge to unstake LPT.
    /// @param _base_pool Address of the base pool to get from base pool.
    /// @return coin_amount Amount of coin obtained.
    function unstakeAndRemoveLiquidityMeta(address _pool, address _coin, uint _lpt_amount, address _gauge, uint _min_coin_out, address _base_pool) public virtual onlyExecutor returns(uint) {
        address base_pool_token = lpts[_base_pool];
        uint base_lpt_amount = unstakeAndRemoveLiquidity(_pool, base_pool_token, _lpt_amount, _gauge, 0);
        return removeLiquidity(_base_pool, _coin, base_lpt_amount, _min_coin_out);
    }

    /// @notice Only executor. Assemble by configuration
    function assemble(uint _min_lpts_out) external virtual onlyExecutor hasConfig returns (uint) {
        if (position_config.useWrap)
            unwrapNative(currentBalance(WNATIVE));

        if (_isMetapool()) 
            return _assembleMetapool(_min_lpts_out, currentBalance(position_config.meta_pool.base_pool_coin));

        if (_isMultipleCoins()) {
            uint[] memory coins_amounts = new uint[](coins[position_config.pool].length);
            for (uint i = 0; i < coins[position_config.pool].length; i++)
                coins_amounts[i] = currentBalance(coins[position_config.pool][i]);
            return _assembleMultipleCoins(_min_lpts_out, coins_amounts);
        }
    
        return _assembleOneCoin(_min_lpts_out, currentBalance(position_config.coin));
    }

    /// @notice Only executor. Disassemble by configuration
    /// @param _percentage Amount to unstakeAndRemoveLiquidity expressed as a percentage. 1e18 is equivalent to 100%.
    function disassemble(uint _percentage, uint[] memory _min_coins_out) external virtual onlyExecutor hasConfig returns (uint[] memory out_amounts) {
        out_amounts = new uint[](coins[position_config.pool].length);
        uint lpt_amount = _percentageAmount(totalLPTBalance(), _percentage);
        if (lpt_amount == 0)
            return out_amounts;

        uint unstaked_lpt_amount = idleLPTBalance();
        if (unstaked_lpt_amount != 0)
            _stakeBeforeDisassemble(unstaked_lpt_amount);

        if (_isMetapool()) {
            uint lpt_index = _LPTIndex();
            out_amounts[lpt_index] = _disassembleMetapool(_min_coins_out[lpt_index], lpt_amount);
        }
        else if (_isMultipleCoins()) 
            out_amounts = _disassembleMultipleCoins(_min_coins_out, lpt_amount);
        else {
            uint coin_index = coinIndex(position_config.pool, position_config.coin);
            out_amounts[coin_index] = _disassembleOneCoin(_min_coins_out[coin_index], lpt_amount);
        }

        if (position_config.useWrap)
            wrapNative(address(this).balance);
    }

    /// @notice Only executor. Mint CRV token to position manager.
    /// @param _gauge Address of the gauge to mint CRV.
    function mint(address _gauge) external onlyExecutor {
        address[] memory rewards_addresses = new address[](1);
        rewards_addresses[0] = CRV_ADDRESS;
        uint[] memory claimed_amounts = new uint[](1);
        claimed_amounts[0] = currentBalance(rewards_addresses[0]);
        _mint(_gauge);
        claimed_amounts[0] = currentBalance(rewards_addresses[0]) - claimed_amounts[0];
        emit ClaimRewards(rewards_addresses, claimed_amounts);
    }

    /// @notice Claim all rewards tokens in the gauge given by position_config
    /// @return rewards_addresses
    /// @return claimed_amounts
    function claimRewards() external virtual onlyExecutor hasConfig returns (address[] memory rewards_addresses, uint[] memory claimed_amounts) {
        rewards_addresses = getRewardsTokens();
        claimed_amounts = new uint[](rewards_addresses.length);

        if (position_config.gauge_version == GaugeVersion.NULLGAUGE)
            return (rewards_addresses, claimed_amounts);
        
        for (uint i = 0; i < rewards_addresses.length; i++)
            claimed_amounts[i] = currentBalance(rewards_addresses[i]);

        _mint(position_config.gauge);
        if (position_config.gauge_version != GaugeVersion.V1) {
            if (CurveMethods.shouldSkipWrongRewardToken(position_config.gauge)) {}
            else
                ILiquidityGaugeV2(position_config.gauge).claim_rewards();
        }
        
        for (uint i = 0; i < rewards_addresses.length; i++)
            claimed_amounts[i] = currentBalance(rewards_addresses[i]) - claimed_amounts[i];

        emit ClaimRewards(rewards_addresses, claimed_amounts);
    }

    /// @param _merkle_distributor Merkl distributor address
    function updateMerkleDistributor(address _merkle_distributor) public onlyOwner {
        merkle_distributor = IMerkleDistributor(_merkle_distributor);
        emit UpdateMerkleDistributor(_merkle_distributor);
    }

    /// @notice Claims Merkl rewards for the given users and tokens
    /// @param _merkle_claim_data merkle claim data
    /// @return merkle_tokens_out token addresses claimed
    /// @return merkle_amounts_out amounts of each token claimed
    function claimMerkleRewards(MerkleClaimData calldata _merkle_claim_data) external onlyExecutor returns (address[] memory merkle_tokens_out, uint[] memory merkle_amounts_out) {
        require(address(merkle_distributor) != address(0), 'C1');

        merkle_amounts_out = new uint[](_merkle_claim_data.tokens.length);

        uint[] memory balances_before = new uint[](_merkle_claim_data.tokens.length);
        for (uint i = 0; i < _merkle_claim_data.tokens.length; i++)
            balances_before[i] = currentBalance(_merkle_claim_data.tokens[i]);

        merkle_distributor.claim(_merkle_claim_data.users, _merkle_claim_data.tokens, _merkle_claim_data.values, _merkle_claim_data.proof);

        for (uint i = 0; i < _merkle_claim_data.tokens.length; i++)
            merkle_amounts_out[i] = currentBalance(_merkle_claim_data.tokens[i]) - balances_before[i];

        emit ClaimMerkleRewards(_merkle_claim_data.tokens, merkle_amounts_out);
        return (_merkle_claim_data.tokens, merkle_amounts_out);
    }
}

contracts/convex/IConvexRewards.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


//sample convex reward contracts interface
interface IConvexRewards{
    function withdrawAndUnwrap(uint256 _amount, bool _claim) external returns(bool);

    function getReward(address _account, bool _claimExtras) external returns(bool);

    function rewardToken() external view returns (address);

    function extraRewardsLength() external view returns (uint);

    function extraRewards(uint _index) external view returns (address _child_rewards_contract);

    /* Sidechain */

    function withdraw(uint256 _amount, bool _claim) external returns(bool);

    function getReward(address _account) external;

    function rewardLength() external view returns (uint);

    struct RewardType {
        address reward_token;
        uint256 reward_integral;
        uint256 reward_remaining;
    }

    function rewards(uint _index) external view returns (RewardType memory);
}

contracts/curve/ICurvePool.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

interface ICurvePool {
  function calc_token_amount(uint[2] memory _amounts, bool _is_deposit) external view returns(uint);
  function calc_token_amount(uint[3] memory _amounts, bool _is_deposit) external view returns(uint);
  function calc_token_amount(uint[4] memory _amounts, bool _is_deposit) external view returns(uint);
  function balances(uint) external view returns(uint);
  function coins(uint) external view returns(address);

  function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount) payable external;
  function add_liquidity(uint[3] memory _amounts, uint _min_mint_amount) payable external;
  function add_liquidity(uint[4] memory _amounts, uint _min_mint_amount) payable external;
  function add_liquidity(uint[2] memory _amounts, uint _min_mint_amount, bool _use_underlying) payable external;
  function add_liquidity(uint[3] memory _amounts, uint _min_mint_amount, bool _use_underlying) payable external;
  function add_liquidity(uint[4] memory _amounts, uint _min_mint_amount, bool _use_underlying) payable external;

  function remove_liquidity_one_coin(uint _token_amount, int128 i, uint _min_amount) external;
  function remove_liquidity_one_coin(uint _token_amount, uint i, uint _min_amount) external;
  function remove_liquidity_one_coin(uint _token_amount, int128 i, uint _min_amount, bool _use_underlying) external;
  function remove_liquidity_one_coin(uint _token_amount, uint i, uint _min_amount, bool _use_underlying) external;

  function remove_liquidity(uint _amount, uint[2] memory _min_amounts) external;
  function remove_liquidity(uint _amount, uint[3] memory _min_amounts) external;
  function remove_liquidity(uint _amount, uint[4] memory _min_amounts) external;
  function remove_liquidity(uint _amount, uint[2] memory _min_amounts, bool _use_underlying) external;
  function remove_liquidity(uint _amount, uint[3] memory _min_amounts, bool _use_underlying) external;
  function remove_liquidity(uint _amount, uint[4] memory _min_amounts, bool _use_underlying) external;

  function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns(uint);
  function calc_withdraw_one_coin(uint _token_amount, uint i) external view returns(uint);

  function get_dy(int128 i, int128 j, uint dx) external view returns(uint);
  function get_dy(uint i, uint j, uint dx) external view returns(uint);

  function exchange(int128 i, int128 j, uint dx, uint min_dy) external;
  function exchange(uint i, uint j, uint dx, uint min_dy) external;
}

contracts/curve/ICurvePoolDynamic.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

interface ICurvePoolDynamic {
  function calc_token_amount(uint[] memory _amounts, bool _is_deposit) external view returns(uint);
  function balances(uint) external view returns(uint);
  function coins(uint) external view returns(address);

  function add_liquidity(uint[] memory _amounts, uint _min_mint_amount) payable external;

  function remove_liquidity_one_coin(uint _token_amount, int128 i, uint _min_amount) external;

  function remove_liquidity(uint _amount, uint[] memory _min_amounts) external;

  function calc_withdraw_one_coin(uint _token_amount, int128 i) external view returns(uint);

  function get_dy(int128 i, int128 j, uint dx) external view returns(uint);

  function exchange(int128 i, int128 j, uint dx, uint min_dy) external;
}

contracts/curve/IGaugeReward.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

interface IGaugeReward {
  function rewarded_token() external view returns(address);
}

contracts/curve/ILiquidityGaugeV2.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

interface ILiquidityGaugeV2 {
  function deposit(uint) external;

  function withdraw(uint) external;

  function claim_rewards(address) external;
  
  function claim_rewards() external;

  function reward_tokens(uint) external view returns(address);
  
  function reward_count() external view returns(uint);
  
  function crv_token() external view returns(address);
}

contracts/curve/IMinter.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

interface IMinter {
  function toggle_approve_mint(address) external;

  function mint_for(address, address) external;

  function mint(address) external;

  function mint_many(address[] memory) external;
}

contracts/interfaces/merkl/IMerkleDistributor.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

interface IMerkleDistributor {
    function claim(address[] calldata users, address[] calldata tokens, uint256[] calldata amounts, bytes32[][] calldata proofs) external;

    function claimed(address user, address token) external view returns (uint208 amount, uint48 timestamp, bytes32 merkleRoot);
}

contracts/libraries/CurveMethods.sol

/* SPDX-License-Identifier: UNLICENSED */
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import '../curve/ICurvePool.sol';
import '../curve/IGaugeReward.sol';
import '../curve/ILiquidityGaugeV2.sol';
import '../IPositionManager.sol';

library CurveMethods {
    address constant public ETH_COIN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
    
    function _calcWithdrawOneCoin(address _position, address _pool, address _coin, uint _lpt_amount) public view returns (uint) {
        IPositionManager p = IPositionManager(_position);
        if (p.use_uint_indexes(_pool))
              return ICurvePool(_pool).calc_withdraw_one_coin(_lpt_amount, p.coinIndex(_pool, _coin));
        return ICurvePool(_pool).calc_withdraw_one_coin(_lpt_amount, int128(int(p.coinIndex(_pool, _coin))));
    }

    /// @notice View function to get balance of the position manager in a given token or ETH.
    /// @param _a Address to get balance of position manager.
    /// @return _balance_of balance of the position manager
    function currentBalance(address _a, address _token) public view returns(uint) {
        if (_token == ETH_COIN)
            return _a.balance;
        return IERC20(_token).balanceOf(_a);
    }

    /// @notice View function to get underlyings addresses
    /// @return assets all underlying assets
    function getPositionAssets(address _position, bool _isMultipleCoins, bool _isMetapool) public view returns(address[] memory assets) {
        IPositionManager p = IPositionManager(_position);
        PositionConfig memory position_config = p.position_config();
        assets = new address[](_isMultipleCoins ? p.getCoins(position_config.pool).length : 1);

        if (_isMultipleCoins)
            assets = p.getCoins(position_config.pool);
        else
            assets[0] = position_config.coin;

        for (uint256 i = 0; i < assets.length; i++) {
            if (_isMetapool && assets[i] == p.lpts(position_config.meta_pool.base_pool))
                assets[i] = position_config.meta_pool.base_pool_coin;
            else
                assets[i] = p.getUnderlyingCoin(assets[i]);
        }

        for (uint256 i = 0; i < assets.length; i++)
            if (assets[i] == p.ETH_COIN() && position_config.useWrap)
                assets[i] = p.WNATIVE();
    }

    /// @notice Get underlyings address and amounts by lpt_amount given
    /// @return assets all underlying assets
    /// @return amounts amounts of all underlying assets
    function getUnderlyingAmountsFromLPT(address _position, bool _isMultipleCoins, bool _isMetapool, uint lpt_amount) public view returns (address[] memory assets, uint256[] memory amounts) {
        IPositionManager p = IPositionManager(_position);
        PositionConfig memory position_config = p.position_config();
        assets = getPositionAssets(_position, _isMultipleCoins, _isMetapool);
        amounts = new uint[](assets.length);
        if (lpt_amount != 0) {
            if (_isMultipleCoins) {
                uint total_lpt = IERC20(p.lpts(position_config.pool)).totalSupply();

                for (uint i = 0; i < p.getCoins(position_config.pool).length; i++) {
                    uint balance = ICurvePool(position_config.pool).balances(i);
                    amounts[i] = balance *  lpt_amount / total_lpt;
                    if (_isMetapool && p.lpts(position_config.meta_pool.base_pool) == p.getCoins(position_config.pool)[i])
                        amounts[i] = _calcWithdrawOneCoin(_position, position_config.meta_pool.base_pool, position_config.meta_pool.base_pool_coin, amounts[i]);
                }
            }
            else if (_isMetapool) {
                uint base_lpt_amount = _calcWithdrawOneCoin(_position, position_config.pool, p.lpts(position_config.meta_pool.base_pool), lpt_amount);
                amounts[0] = _calcWithdrawOneCoin(_position, position_config.meta_pool.base_pool, position_config.meta_pool.base_pool_coin, base_lpt_amount);
            }
            else 
                amounts[0] = _calcWithdrawOneCoin(_position, position_config.pool, position_config.coin, lpt_amount);
        }
    }

    /// @notice Get all rewards tokens in the gauge given by position_config
    /// @return rewards_addresses
    function getRewardsTokens(address _position) public view returns(address[] memory rewards_addresses) {
        IPositionManager p = IPositionManager(_position);
        PositionConfig memory position_config = p.position_config();

        uint reward_length = p.getRewardLength();
        rewards_addresses = new address[](reward_length);

        if (reward_length == 0)
            return rewards_addresses;

        rewards_addresses[0] = p.CRV_ADDRESS();
        for (uint i = 1; i < reward_length; i++) 
            rewards_addresses[i] = position_config.gauge_version == GaugeVersion.REWARD ? IGaugeReward(position_config.gauge).rewarded_token() : ILiquidityGaugeV2(position_config.gauge).reward_tokens(i - 1);
    }

    /// @notice Get underlyings address and amounts
    /// @return assets all underlying assets
    /// @return amounts amounts of all underlying assets
    function getUnderlyings(address _position) public view returns(address[] memory assets, uint256[] memory amounts) {
        IPositionManager p = IPositionManager(_position);
        uint lpt_amount = p.totalLPTBalance();
        return p.getUnderlyingAmountsFromLPT(lpt_amount);
    }

    /// @notice Get reward length in the gauge given by position_config
    /// @return reward_length  
    function getRewardLength(address _position) public view returns (uint) {
        PositionConfig memory position_config = IPositionManager(_position).position_config();
        if (position_config.gauge_version == GaugeVersion.NULLGAUGE)
            return 0;

        if (shouldSkipWrongRewardToken(position_config.gauge))
            return 1;

        if (position_config.gauge_version == GaugeVersion.V1)
            return 1;

        if (position_config.gauge_version == GaugeVersion.REWARD) {
            if (IGaugeReward(position_config.gauge).rewarded_token() != address(0))
                return 2;
            return 1;
        }

        if (position_config.gauge_version == GaugeVersion.V4 || position_config.gauge_version == GaugeVersion.VSidechain || position_config.gauge_version == GaugeVersion.V6)
            return 1 + ILiquidityGaugeV2(position_config.gauge).reward_count();

        uint reward_length = 1;    
        for (uint i = 0; i < 8; i++) {
            if (ILiquidityGaugeV2(position_config.gauge).reward_tokens(i) == address(0))
                break;
            reward_length++;
        }
        return reward_length;
    }

    /* TODO: TEMP ignore wrong gauge configuration for Base */
    function shouldSkipWrongRewardToken(address _gauge) public pure returns (bool) {
        return
            _gauge == 0x6616CCfA456F72104452341fa470E9B08A11b1aB ||
            _gauge == 0x93933FA992927284e9d508339153B31eb871e1f4 ||
            _gauge == 0x89289DC2192914a9F0674f1E9A17C56456549b8A ||
            _gauge == 0xE9c898BA654deC2bA440392028D2e7A194E6dc3e ||
            _gauge == 0x79edc58C471Acf2244B8f93d6f425fD06A439407;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "libraries": {
    "contracts/PositionManagerOwnable2StepWithShortcut.sol": {
      "CurveMethods": "0xf7dbfd129f7b68fcf28ea5e5523d8ff592408f3d"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "paris"
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.