ETH Price: $2,706.99 (+2.90%)

Contract

0x7a57429755Fc2F6fEa171Bdb7d9788E4A0E7f63c
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Token Holdings

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To
Harvest215271312025-01-01 4:08:5949 days ago1735704539IN
0x7a574297...4A0E7f63c
0 ETH0.001894652.47294201
Harvest211059662024-11-03 8:37:59108 days ago1730623079IN
0x7a574297...4A0E7f63c
0 ETH0.002423362.79618465
Manage194795742024-03-21 0:46:47335 days ago1710982007IN
0x7a574297...4A0E7f63c
0 ETH0.024660830.229203
Transfer Ownersh...194251002024-03-13 8:56:35343 days ago1710320195IN
0x7a574297...4A0E7f63c
0 ETH0.0026872353.1894061
Update Manager R...194019172024-03-10 3:09:11346 days ago1710040151IN
0x7a574297...4A0E7f63c
0 ETH0.0016065948.65232072
Update Harvester...194019162024-03-10 3:08:59346 days ago1710040139IN
0x7a574297...4A0E7f63c
0 ETH0.0014263143.25326695
Initialize194019142024-03-10 3:08:35346 days ago1710040115IN
0x7a574297...4A0E7f63c
0 ETH0.0143588948.27736995

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Minimal Proxy Contract for 0xbec45a9506d191f9705c77dccd291c2609d18e4c

Contract Name:
ConvexCurveManager

Compiler Version
v0.8.20+commit.a1b79de6

Optimization Enabled:
Yes with 200 runs

Other Settings:
shanghai EvmVersion

Contract Source Code (Solidity Standard Json-Input format)

File 1 of 17 : ConvexCurveManager.sol
// SPDX-License-Identifier: MIT

pragma solidity =0.8.20;

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

import { IMultipleRewardDistributor } from "../../common/rewards/distributor/IMultipleRewardDistributor.sol";
import { IConvexVirtualBalanceRewardPool } from "../../interfaces/convex/IConvexVirtualBalanceRewardPool.sol";
import { IStashTokenWrapper } from "../../interfaces/convex/IStashTokenWrapper.sol";
import { ILiquidityManager } from "../../interfaces/voting-escrow/ILiquidityManager.sol";
import { IConvexBasicRewards } from "../../interfaces/IConvexBasicRewards.sol";
import { IConvexBooster } from "../../interfaces/IConvexBooster.sol";

import { WordCodec } from "../../common/codec/WordCodec.sol";

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

contract ConvexCurveManager is LiquidityManagerBase {
  using SafeERC20 for IERC20;
  using WordCodec for bytes32;

  /*************
   * Constants *
   *************/

  /// @dev The address of Convex CVX token.
  address private constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B;

  /// @dev The address of Convex Booster.
  address private constant BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31;

  /// @dev The offset of pid in `_miscData`.
  uint256 private constant PID_OFFSET = 61;

  /// @dev The rewarder of pid in `_miscData`.
  uint256 private constant REWARDER_OFFSET = 77;

  /*************
   * Variables *
   *************/

  /// @dev the list of reward tokens.
  address[] private rewards;

  /***************
   * Constructor *
   ***************/

  function initialize(
    address _operator,
    address _token,
    address _rewarder
  ) external initializer {
    __LiquidityManagerBase_init(_operator, _token);

    uint256 _pid = IConvexBasicRewards(_rewarder).pid();

    bytes32 _data = _miscData;
    _data = _data.insertUint(_pid, PID_OFFSET, 16);
    _data = _data.insertUint(uint256(uint160(_rewarder)), REWARDER_OFFSET, 160);
    _miscData = _data;

    IERC20(_token).safeApprove(BOOSTER, type(uint256).max);
    syncRewardToken();
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc ILiquidityManager
  function getRewardTokens() external view returns (address[] memory) {
    return rewards;
  }

  /// @notice Return the pid in Convex Booster.
  function pid() public view returns (uint256) {
    return _miscData.decodeUint(PID_OFFSET, 16);
  }

  /// @notice Return the address of rewarder.
  function rewarder() public view returns (address) {
    return address(uint160(_miscData.decodeUint(REWARDER_OFFSET, 160)));
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Sync reward tokens from ConvexBasicRewards contract.
  function syncRewardToken() public {
    delete rewards;

    address staker = rewarder();
    rewards.push(IConvexBasicRewards(staker).rewardToken());

    uint256 _length = IConvexBasicRewards(staker).extraRewardsLength();
    bool _hasCVX = false;
    for (uint256 i = 0; i < _length; i++) {
      address _rewarder = IConvexBasicRewards(staker).extraRewards(i);
      address _wrapper = IConvexVirtualBalanceRewardPool(_rewarder).rewardToken();
      // old rewarders didn't use token wrapper
      try IStashTokenWrapper(_wrapper).token() returns (address _token) {
        if (_token == CVX) _hasCVX = true;
        rewards.push(_token);
      } catch {
        if (_wrapper == CVX) _hasCVX = true;
        rewards.push(_wrapper);
      }
    }
    if (!_hasCVX) rewards.push(CVX);

    _length = rewards.length;
    for (uint256 i = 0; i < _length; ++i) {
      address _token = rewards[i];
      IERC20(_token).safeApprove(operator, 0);
      IERC20(_token).safeApprove(operator, type(uint256).max);
    }
  }

  /// @inheritdoc ILiquidityManager
  function manage() public override {
    uint256 _balance = IERC20(token).balanceOf(address(this));
    if (_balance == 0) return;

    _manageUnderlying(address(0), _balance, false);
  }

  /// @inheritdoc ILiquidityManager
  function harvest(address _receiver) external {
    // try to deposit first
    uint256 _balance = IERC20(token).balanceOf(address(this));
    if (_balance > 0) {
      IConvexBooster(BOOSTER).deposit(pid(), _balance, true);
    }

    // harvest
    IConvexBasicRewards(rewarder()).getReward();

    // distribute rewards
    uint256 _harvesterRatio = getHarvesterRatio();
    uint256 _managerRatio = getManagerRatio();
    uint256 _length = rewards.length;
    address _operator = operator;
    for (uint256 i = 0; i < _length; ++i) {
      address _rewardToken = rewards[i];
      uint256 _rewardAmount = IERC20(_rewardToken).balanceOf(address(this)) - incentive[_rewardToken];
      if (_rewardAmount == 0) continue;

      unchecked {
        uint256 _incentive = (_rewardAmount * _managerRatio) / FEE_PRECISION;
        if (_incentive > 0) incentive[_rewardToken] += _incentive;

        uint256 _bounty = (_rewardAmount * _harvesterRatio) / FEE_PRECISION;
        if (_bounty > 0) {
          IERC20(_rewardToken).safeTransfer(_receiver, _bounty);
        }

        IMultipleRewardDistributor(_operator).depositReward(_rewardToken, _rewardAmount - _incentive - _bounty);
      }
    }
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @inheritdoc LiquidityManagerBase
  function _managedBalance() internal view virtual override returns (uint256) {
    unchecked {
      return IERC20(token).balanceOf(address(this)) + IConvexBasicRewards(rewarder()).balanceOf(address(this));
    }
  }

  /// @inheritdoc LiquidityManagerBase
  function _deposit(
    address _receiver,
    uint256,
    bool _manage
  ) internal virtual override {
    if (_manage) {
      // deposit to underlying strategy
      uint256 _balance = IERC20(token).balanceOf(address(this));
      if (_balance > 0) {
        _manageUnderlying(_receiver, _balance, true);
      }
    }
  }

  /// @inheritdoc LiquidityManagerBase
  function _withdraw(address _receiver, uint256 _amount) internal virtual override {
    if (_amount > 0) {
      uint256 _balance = IERC20(token).balanceOf(address(this));
      if (_amount > _balance) {
        unchecked {
          IConvexBasicRewards(rewarder()).withdrawAndUnwrap(_amount - _balance, false);
        }
      }
      IERC20(token).safeTransfer(_receiver, _amount);
    }
  }

  /// @dev Internal function to manage underlying assets
  function _manageUnderlying(
    address _receiver,
    uint256 _balance,
    bool _incentived
  ) internal {
    // deposit to booster
    IConvexBooster(BOOSTER).deposit(pid(), _balance, true);

    // send incentive
    if (_incentived) {
      uint256 _length = rewards.length;
      for (uint256 i = 0; i < _length; ++i) {
        address _rewardToken = rewards[i];
        uint256 _incentive = incentive[_rewardToken];
        if (_incentive > 0) {
          IERC20(_rewardToken).safeTransfer(_receiver, _incentive);
          incentive[_rewardToken] = 0;
        }
      }
    }
  }
}

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

pragma solidity ^0.8.0;

import "../utils/Context.sol";

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

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

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

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

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

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

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

File 3 of 17 : Ownable2Step.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./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.
 *
 * By default, the owner account will be the one that deploys the contract. 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.
     */
    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();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }
}

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

pragma solidity ^0.8.2;

import "../../utils/Address.sol";

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.0;

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

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

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

File 6 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 7 of 17 : SafeERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

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

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

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

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

File 9 of 17 : Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

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

File 10 of 17 : WordCodec.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

// solhint-disable no-inline-assembly

/// @dev A subset copied from the following contracts:
///
/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodec.sol`
/// + `balancer-labs/v2-solidity-utils/contracts/helpers/WordCodecHelpers.sol`
library WordCodec {
  /// @dev Inserts an unsigned integer of bitLength, shifted by an offset, into a 256 bit word,
  /// replacing the old value. Returns the new word.
  function insertUint(
    bytes32 word,
    uint256 value,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (bytes32 result) {
    // Equivalent to:
    // uint256 mask = (1 << bitLength) - 1;
    // bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));
    // result = clearedWord | bytes32(value << offset);
    assembly {
      let mask := sub(shl(bitLength, 1), 1)
      let clearedWord := and(word, not(shl(offset, mask)))
      result := or(clearedWord, shl(offset, value))
    }
  }

  /// @dev Decodes and returns an unsigned integer with `bitLength` bits, shifted by an offset, from a 256 bit word.
  function decodeUint(
    bytes32 word,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (uint256 result) {
    // Equivalent to:
    // result = uint256(word >> offset) & ((1 << bitLength) - 1);
    assembly {
      result := and(shr(offset, word), sub(shl(bitLength, 1), 1))
    }
  }

  /// @dev Inserts a signed integer shifted by an offset into a 256 bit word, replacing the old value. Returns
  /// the new word.
  ///
  /// Assumes `value` can be represented using `bitLength` bits.
  function insertInt(
    bytes32 word,
    int256 value,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (bytes32) {
    unchecked {
      uint256 mask = (1 << bitLength) - 1;
      bytes32 clearedWord = bytes32(uint256(word) & ~(mask << offset));
      // Integer values need masking to remove the upper bits of negative values.
      return clearedWord | bytes32((uint256(value) & mask) << offset);
    }
  }

  /// @dev Decodes and returns a signed integer with `bitLength` bits, shifted by an offset, from a 256 bit word.
  function decodeInt(
    bytes32 word,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (int256 result) {
    unchecked {
      int256 maxInt = int256((1 << (bitLength - 1)) - 1);
      uint256 mask = (1 << bitLength) - 1;

      int256 value = int256(uint256(word >> offset) & mask);
      // In case the decoded value is greater than the max positive integer that can be represented with bitLength
      // bits, we know it was originally a negative integer. Therefore, we mask it to restore the sign in the 256 bit
      // representation.
      //
      // Equivalent to:
      // result = value > maxInt ? (value | int256(~mask)) : value;
      assembly {
        result := or(mul(gt(value, maxInt), not(mask)), value)
      }
    }
  }

  /// @dev Decodes and returns a boolean shifted by an offset from a 256 bit word.
  function decodeBool(bytes32 word, uint256 offset) internal pure returns (bool result) {
    // Equivalent to:
    // result = (uint256(word >> offset) & 1) == 1;
    assembly {
      result := and(shr(offset, word), 1)
    }
  }

  /// @dev Inserts a boolean value shifted by an offset into a 256 bit word, replacing the old value. Returns the new
  /// word.
  function insertBool(
    bytes32 word,
    bool value,
    uint256 offset
  ) internal pure returns (bytes32 result) {
    // Equivalent to:
    // bytes32 clearedWord = bytes32(uint256(word) & ~(1 << offset));
    // bytes32 referenceInsertBool = clearedWord | bytes32(uint256(value ? 1 : 0) << offset);
    assembly {
      let clearedWord := and(word, not(shl(offset, 1)))
      result := or(clearedWord, shl(offset, value))
    }
  }

  function clearWordAtPosition(
    bytes32 word,
    uint256 offset,
    uint256 bitLength
  ) internal pure returns (bytes32 clearedWord) {
    unchecked {
      uint256 mask = (1 << bitLength) - 1;
      clearedWord = bytes32(uint256(word) & ~(mask << offset));
    }
  }
}

File 11 of 17 : IMultipleRewardDistributor.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IMultipleRewardDistributor {
  /**********
   * Events *
   **********/

  /// @notice Emitted when new reward token is registered.
  ///
  /// @param token The address of reward token.
  /// @param distributor The address of reward distributor.
  event RegisterRewardToken(address indexed token, address indexed distributor);

  /// @notice Emitted when the reward distributor is updated.
  ///
  /// @param token The address of reward token.
  /// @param oldDistributor The address of previous reward distributor.
  /// @param newDistributor The address of current reward distributor.
  event UpdateRewardDistributor(address indexed token, address indexed oldDistributor, address indexed newDistributor);

  /// @notice Emitted when a reward token is unregistered.
  ///
  /// @param token The address of reward token.
  event UnregisterRewardToken(address indexed token);

  /// @notice Emitted when a reward token is deposited.
  ///
  /// @param token The address of reward token.
  /// @param amount The amount of reward token deposited.
  event DepositReward(address indexed token, uint256 amount);

  /**********
   * Errors *
   **********/

  /// @dev Thrown when caller access an unactive reward token.
  error NotActiveRewardToken();

  /// @dev Thrown when the address of reward distributor is `address(0)`.
  error RewardDistributorIsZero();

  /// @dev Thrown when caller is not reward distributor.
  error NotRewardDistributor();

  /// @dev Thrown when caller try to register an existing reward token.
  error DuplicatedRewardToken();

  /// @dev Thrown when caller try to unregister a reward with pending rewards.
  error RewardDistributionNotFinished();

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return the address of reward distributor.
  ///
  /// @param token The address of reward token.
  function distributors(address token) external view returns (address);

  /// @notice Return the list of active reward tokens.
  function getActiveRewardTokens() external view returns (address[] memory);

  /// @notice Return the list of historical reward tokens.
  function getHistoricalRewardTokens() external view returns (address[] memory);

  /// @notice Return the amount of pending distributed rewards in current period.
  ///
  /// @param token The address of reward token.
  /// @return distributable The amount of reward token can be distributed in current period.
  /// @return undistributed The amount of reward token still locked in current period.
  function pendingRewards(address token) external view returns (uint256 distributable, uint256 undistributed);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Deposit new rewards to this contract.
  ///
  /// @param token The address of reward token.
  /// @param amount The amount of new rewards.
  function depositReward(address token, uint256 amount) external;
}

File 12 of 17 : IConvexVirtualBalanceRewardPool.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;

interface IConvexVirtualBalanceRewardPool {
  function rewardToken() external view returns (address);

  function earned(address account) external view returns (uint256);
}

File 13 of 17 : IStashTokenWrapper.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;

interface IStashTokenWrapper {
  function token() external view returns (address);

  function rewardPool() external view returns (address);

  function isInvalid() external view returns (bool);

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

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

  function decimals() external view returns (uint8);

  function totalSupply() external view returns (uint256);

  function balanceOf(address _account) external view returns (uint256);

  function transfer(address _recipient, uint256 _amount) external returns (bool);
}

File 14 of 17 : IConvexBasicRewards.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;

interface IConvexBasicRewards {
  function pid() external view returns (uint256);

  function totalSupply() external view returns (uint256);

  function periodFinish() external view returns (uint256);

  function rewardRate() external view returns (uint256);

  function stakingToken() external view returns (address);

  function stakeFor(address, uint256) external returns (bool);

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

  function earned(address) external view returns (uint256);

  function withdrawAll(bool) external returns (bool);

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

  function withdrawAndUnwrap(uint256, bool) external returns (bool);

  function getReward() external returns (bool);

  function stake(uint256) external returns (bool);

  function rewardToken() external view returns (address);

  function extraRewards(uint256) external view returns (address);

  function extraRewardsLength() external view returns (uint256);
}

File 15 of 17 : IConvexBooster.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0 || ^0.8.0;
pragma abicoder v2;

interface IConvexBooster {
  struct PoolInfo {
    address lptoken;
    address token;
    address gauge;
    address crvRewards;
    address stash;
    bool shutdown;
  }

  function poolInfo(uint256 _pid) external view returns (PoolInfo memory);

  function depositAll(uint256 _pid, bool _stake) external returns (bool);

  function deposit(
    uint256 _pid,
    uint256 _amount,
    bool _stake
  ) external returns (bool);

  function earmarkRewards(uint256 _pid) external returns (bool);

  function earmarkFees() external returns (bool);
}

File 16 of 17 : ILiquidityManager.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface ILiquidityManager {
  /**********
   * Events *
   **********/

  /// @notice Emitted when the ratio for manager is updated.
  /// @param oldRatio The value of the previous ratio, multipled by 1e9.
  /// @param newRatio The value of the current ratio, multipled by 1e9.
  event UpdateManagerRatio(uint256 oldRatio, uint256 newRatio);

  /// @notice Emitted when the ratio for harvester is updated.
  /// @param oldRatio The value of the previous ratio, multipled by 1e9.
  /// @param newRatio The value of the current ratio, multipled by 1e9.
  event UpdateHarvesterRatio(uint256 oldRatio, uint256 newRatio);

  /**********
   * Errors *
   **********/

  /// @dev Thrown when try to kill the manager more than once.
  error AlreadyKilled();

  /// @dev Thrown when the call is not operator.
  error CallerIsNotOperator();

  /// @dev Thrown when the manager ratio exceeds `MAX_MANAGER_RATIO`.
  error ManagerRatioTooLarge();

  /// @dev Thrown when the harvester ratio exceeds `MAX_HARVESTER_RATIO`.
  error HarvesterRatioTooLarge();

  /*************************
   * Public View Functions *
   *************************/

  /// @notice Return whether the manager is active.
  function isActive() external view returns (bool);

  /// @notice Return the list of reward tokens.
  function getRewardTokens() external view returns (address[] memory);

  /// @notice Return the fee ratio distributed to treasury, multipled by 1e9.
  function getManagerRatio() external view returns (uint256);

  /// @notice Return the fee ratio distributed to harvester, multipled by 1e9.
  function getHarvesterRatio() external view returns (uint256);

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @notice Deposit token to corresponding manager.
  /// @dev Requirements:
  ///   + Caller should make sure the token is already transfered into the manager contract.
  ///   + Caller should make sure the deposit amount is greater than zero.
  ///
  /// @param receiver The address of recipient who will receive the share.
  /// @param amount The amount of token to deposit.
  /// @param manage Whether to deposit the token to underlying strategy.
  function deposit(
    address receiver,
    uint256 amount,
    bool manage
  ) external;

  /// @notice Withdraw underlying token from corresponding manager.
  /// @dev Requirements:
  ///   + Caller should make sure the withdraw amount is greater than zero.
  ///
  /// @param receiver The address of recipient who will receive the token.
  /// @param amount The amount of token to withdraw.
  function withdraw(address receiver, uint256 amount) external;

  /// @notice Emergency function to execute arbitrary call.
  /// @dev This function should be only used in case of emergency. It should never be called explicitly
  ///  in any contract in normal case.
  ///
  /// @param to The address of target contract to call.
  /// @param value The value passed to the target contract.
  /// @param data The calldata pseed to the target contract.
  function execute(
    address to,
    uint256 value,
    bytes calldata data
  ) external payable returns (bool, bytes memory);

  /// @notice Manage the deposited token. Usually the token will be
  /// deposited to another protocol which could generate more yields.
  function manage() external;

  /// @notice Harvest pending rewards from underlying protocol.
  /// @param receiver The address of the recipient for harvest incentive.
  function harvest(address receiver) external;
}

File 17 of 17 : LiquidityManagerBase.sol
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import { Ownable2Step } from "@openzeppelin/contracts-v4/access/Ownable2Step.sol";
import { Initializable } from "@openzeppelin/contracts-v4/proxy/utils/Initializable.sol";

import { WordCodec } from "../../common/codec/WordCodec.sol";

import { ILiquidityManager } from "../../interfaces/voting-escrow/ILiquidityManager.sol";

// solhint-disable func-name-mixedcase

abstract contract LiquidityManagerBase is Initializable, Ownable2Step, ILiquidityManager {
  using WordCodec for bytes32;

  /*************
   * Constants *
   *************/

  /// @dev The offset of active flag in `_miscData`.
  uint256 private constant ACTIVE_FLAG_OFFSET = 0;

  /// @dev The offset of manager ratio in `_miscData`.
  uint256 private constant MANAGER_RATIO_OFFSET = 1;

  /// @dev The offset of harvester ratio in `_miscData`.
  uint256 private constant HARVESTER_RATIO_OFFSET = 31;

  /// @dev The maximum manager ratio.
  uint256 private constant MAX_MANAGER_RATIO = 5e8; // 20%

  /// @dev The maximum harvester ratio.
  uint256 private constant MAX_HARVESTER_RATIO = 1e8; // 20%

  /// @dev The fee denominator used for rate calculation.
  uint256 internal constant FEE_PRECISION = 1e9;

  /*************
   * Variables *
   *************/

  /// @notice The address of operator, usually the `LiquidityGauge` contract.
  address public operator;

  /// @notice The address of managed token.
  address public token;

  /// @notice Mapping from reward token address to the amount of incentive for manager.
  mapping(address => uint256) public incentive;

  /// @dev `_miscData` is a storage slot that can be used to store unrelated pieces of information.
  /// All LiquidityManagerBase store the *active flag*, *manager ratio* and *harvester ratio*, but
  /// the `miscData`can be extended to store more pieces of information.
  ///
  /// The *active flag* is stored in the first bit, and the *manager ratio* is stored in the next most
  /// significant 30 bits, and the *harvester ratio* is stored in the next most significant 30 bits,
  /// leaving the remaining 195 bits free to store any other information derived pools might need.
  ///
  /// - The *manager ratio* and *harvester ratio* are charged each time when harvester harvest the pool revenue.
  ///
  /// [ active flag | manager ratio | harvester ratio | available ]
  /// [    1 bit    |    30 bits    |     30 bits     |  195 bits ]
  /// [ MSB                                                   LSB ]
  bytes32 internal _miscData;

  /// @dev reserved slots.
  uint256[46] private __gap;

  /*************
   * Modifiers *
   *************/

  modifier onlyOperator() {
    if (_msgSender() != operator) {
      revert CallerIsNotOperator();
    }
    _;
  }

  modifier whenNotKilled() {
    if (!isActive()) revert AlreadyKilled();
    _;
  }

  /***************
   * Constructor *
   ***************/

  function __LiquidityManagerBase_init(address _operator, address _token) internal onlyInitializing {
    _transferOwnership(_msgSender());

    operator = _operator;
    token = _token;

    // Set active
    _miscData = _miscData.insertBool(true, ACTIVE_FLAG_OFFSET);
  }

  /*************************
   * Public View Functions *
   *************************/

  /// @inheritdoc ILiquidityManager
  function isActive() public view override returns (bool) {
    return _miscData.decodeBool(ACTIVE_FLAG_OFFSET);
  }

  /// @inheritdoc ILiquidityManager
  function getManagerRatio() public view override returns (uint256) {
    return _miscData.decodeUint(MANAGER_RATIO_OFFSET, 30);
  }

  /// @inheritdoc ILiquidityManager
  function getHarvesterRatio() public view override returns (uint256) {
    return _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);
  }

  /****************************
   * Public Mutated Functions *
   ****************************/

  /// @inheritdoc ILiquidityManager
  function deposit(
    address _receiver,
    uint256 _amount,
    bool _manage
  ) external onlyOperator whenNotKilled {
    _deposit(_receiver, _amount, _manage);
  }

  /// @inheritdoc ILiquidityManager
  function withdraw(address _receiver, uint256 _amount) external onlyOperator whenNotKilled {
    _withdraw(_receiver, _amount);
  }

  /************************
   * Restricted Functions *
   ************************/

  /// @inheritdoc ILiquidityManager
  function execute(
    address _to,
    uint256 _value,
    bytes calldata _data
  ) external payable onlyOwner returns (bool, bytes memory) {
    // solhint-disable-next-line avoid-low-level-calls
    (bool success, bytes memory result) = _to.call{ value: _value }(_data);
    return (success, result);
  }

  /// @notice Kill the liquidity manager and withdraw all token back to operator.
  function kill() external onlyOwner whenNotKilled {
    _miscData = _miscData.insertBool(false, ACTIVE_FLAG_OFFSET);

    // Send all funds back to operator
    uint256 _balance = _managedBalance();
    _withdraw(operator, _balance);
  }

  /// @notice Update the fee ratio distributed to manager.
  /// @param _newRatio The new ratio to update, multipled by 1e9.
  function updateManagerRatio(uint32 _newRatio) external onlyOwner {
    if (uint256(_newRatio) > MAX_MANAGER_RATIO) {
      revert ManagerRatioTooLarge();
    }

    bytes32 _data = _miscData;
    uint256 _oldRatio = _miscData.decodeUint(MANAGER_RATIO_OFFSET, 30);
    _miscData = _data.insertUint(_newRatio, MANAGER_RATIO_OFFSET, 30);

    emit UpdateManagerRatio(_oldRatio, _newRatio);
  }

  /// @notice Update the fee ratio distributed to harvester.
  /// @param _newRatio The new ratio to update, multipled by 1e9.
  function updateHarvesterRatio(uint32 _newRatio) external onlyOwner {
    if (uint256(_newRatio) > MAX_HARVESTER_RATIO) {
      revert HarvesterRatioTooLarge();
    }

    bytes32 _data = _miscData;
    uint256 _oldRatio = _miscData.decodeUint(HARVESTER_RATIO_OFFSET, 30);
    _miscData = _data.insertUint(_newRatio, HARVESTER_RATIO_OFFSET, 30);

    emit UpdateHarvesterRatio(_oldRatio, _newRatio);
  }

  /**********************
   * Internal Functions *
   **********************/

  /// @dev Internal function to return all managed tokens.
  function _managedBalance() internal view virtual returns (uint256);

  /// @dev Internal function to deposit token.
  ///
  /// @param _receiver The address of recipient who will receive the share.
  /// @param _amount The amount of token to deposit.
  /// @param _manage Whether to deposit the token to underlying strategy.
  function _deposit(
    address _receiver,
    uint256 _amount,
    bool _manage
  ) internal virtual;

  /// @dev Internal function to withdraw token.
  ///
  /// @param _receiver The address of recipient who will receive the token.
  /// @param _amount The amount of token to withdraw.
  function _withdraw(address _receiver, uint256 _amount) internal virtual;
}

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

Contract ABI

[{"inputs":[],"name":"AlreadyKilled","type":"error"},{"inputs":[],"name":"CallerIsNotOperator","type":"error"},{"inputs":[],"name":"HarvesterRatioTooLarge","type":"error"},{"inputs":[],"name":"ManagerRatioTooLarge","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferStarted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRatio","type":"uint256"}],"name":"UpdateHarvesterRatio","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"oldRatio","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"newRatio","type":"uint256"}],"name":"UpdateManagerRatio","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"},{"internalType":"bool","name":"_manage","type":"bool"}],"name":"deposit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"execute","outputs":[{"internalType":"bool","name":"","type":"bool"},{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"getHarvesterRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getManagerRatio","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getRewardTokens","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"}],"name":"harvest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"incentive","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_operator","type":"address"},{"internalType":"address","name":"_token","type":"address"},{"internalType":"address","name":"_rewarder","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isActive","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"kill","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"manage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewarder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"syncRewardToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_newRatio","type":"uint32"}],"name":"updateHarvesterRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_newRatio","type":"uint32"}],"name":"updateManagerRatio","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_receiver","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}]

Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

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

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading
[ 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.