Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xEf9bef9AB7b578eb0654F0cD2C75519c9A3f7FE1
Balance 0 ETH
Nonce 101
Code Size 7066 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

7066 bytes
0x608060405234801561000f575f5ffd5b506004361061011c575f3560e01c806375b0ffd1116100a9578063b0020ee71161006e578063b0020ee71461037c578063b4bd6f46146103a3578063cb609077146103d6578063e14e3878146103fd578063ec1100c214610424575f5ffd5b806375b0ffd1146102a3578063780900dc146102ca5780637aaf53e6146103075780638b9d29401461032e57806399248ea714610355575f5ffd5b8063338c5371116100ef578063338c5371146101f25780633bc9a431146102195780634a7500a61461022e5780634a7d5de514610255578063759cb53b1461027c575f5ffd5b806308ecd9a6146101205780630db41f311461016457806322884e2c146101a457806332f6cfba146101cb575b5f5ffd5b6101477f00000000000000000000000052f541764e6e90eebc5c21ff570de0e2d63766b681565b6040516001600160a01b0390911681526020015b60405180910390f35b61018b7fc715e3730000000000000000000000000000000000000000000000000000000081565b6040516001600160e01b0319909116815260200161015b565b6101477f0000000000000000000000002f50d538606fa9edd2b11e2446beb18c9d5846bb81565b6101477f0000000000000000000000009a207a85e372fcdac3014f945a65868f2a05ba1281565b6101477f000000000000000000000000e5d6d047df95c6627326465cb27b64a8b77a8b9181565b61022c610227366004611877565b61044b565b005b6101477f00000000000000000000000074d8dd40118b13b210d0a1639141ce4458cae0c081565b6101477f0000000000000000000000002c043dd5adee81c93a5b5c2ccda00de9c4cbfd4681565b6101477f0000000000000000000000004e3fbd56cd56c3e72c1403e103b45db9da5b9d2b81565b6101477f000000000000000000000000f403c135812408bfbe8713b5a23a04b3d48aae3181565b6102dd6102d8366004611892565b610641565b604080516001600160a01b039485168152928416602084015292169181019190915260600161015b565b6101477f0000000000000000000000002d8bce1fae00a959354acd9ebf9174337a64d4fb81565b6101477f00000000000000000000000093b4b9bd266ffa8af68e39edfa8cfe2a62011ce081565b6101477f000000000000000000000000d533a949740bb3306d119cc777fa900ba034cd5281565b6101477f00000000000000000000000069d61428d089c2f35bf6a472f540d0f82d1ea2cd81565b6103b66103b1366004611877565b61083a565b604080516001600160a01b0393841681529290911660208301520161015b565b6101477f0000000000000000000000001c3a4d06532d9d1c631f99ec50dd72da43a5c6de81565b6101477f00000000000000000000000078f1bba3868b67f4994b3e7f7ec9b0485dc85ad781565b6101477f0000000000000000000000006dfa6232ec23e029d4322115f491a912de9cf9e781565b60405163f815c03d60e01b81526001600160a01b0382811660048301525f917f0000000000000000000000002d8bce1fae00a959354acd9ebf9174337a64d4fb9091169063f815c03d90602401602060405180830381865afa1580156104b3573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906104d791906118a9565b90506001600160a01b038116610500576040516365da5bb960e11b815260040160405180910390fd5b7f0000000000000000000000002c043dd5adee81c93a5b5c2ccda00de9c4cbfd466001600160a01b0316156105a65760405163ce5494bb60e01b81526001600160a01b0383811660048301527f0000000000000000000000002c043dd5adee81c93a5b5c2ccda00de9c4cbfd46169063ce5494bb906024015f604051808303815f87803b15801561058f575f5ffd5b505af11580156105a1573d5f5f3e3d5ffd5b505050505b604051630339050960e51b81526001600160a01b03838116600483015261063d91839185917f0000000000000000000000002d8bce1fae00a959354acd9ebf9174337a64d4fb90911690636720a12090602401602060405180830381865afa158015610614573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061063891906118a9565b610b66565b5050565b5f80807f0000000000000000000000006dfa6232ec23e029d4322115f491a912de9cf9e76001600160a01b031661068b5760405163267f175960e01b815260040160405180910390fd5b604051631526fe2760e01b8152600481018590525f907f000000000000000000000000f403c135812408bfbe8713b5a23a04b3d48aae316001600160a01b031690631526fe279060240160c060405180830381865afa1580156106f0573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061071491906118d3565b505050925050506107248161083a565b80945081955050507f0000000000000000000000006dfa6232ec23e029d4322115f491a912de9cf9e76001600160a01b031663a3f697ba828760405160200161076f91815260200190565b6040516020818303038152906040526040518363ffffffff1660e01b815260040161079b92919061197f565b6020604051808303815f875af11580156107b7573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906107db91906118a9565b604080516001600160a01b0384811682528781166020830152868116828401528316606082015290519193507f08063c8075192206c58e6dd01ffef672f99055179aead6066f80fb31dd2db150919081900360800190a1509193909250565b5f5f61084583610f0f565b610862576040516365da5bb960e11b815260040160405180910390fd5b61086b836110df565b61088857604051637483e90760e01b815260040160405180910390fd5b60405163f815c03d60e01b81526001600160a01b0384811660048301525f917f0000000000000000000000002d8bce1fae00a959354acd9ebf9174337a64d4fb9091169063f815c03d90602401602060405180830381865afa1580156108f0573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061091491906118a9565b6001600160a01b03161461093b5760405163a6ef0ba160e01b815260040160405180910390fd5b5f61094584611209565b6040516001600160601b0319606087811b8216602084015283901b1660348201529091505f9060480160408051601f19818403018152919052805160208201209091506109b37f00000000000000000000000074d8dd40118b13b210d0a1639141ce4458cae0c0838361126a565b6040516001600160601b0319606083811b821660208401525f60348401527f0000000000000000000000009a207a85e372fcdac3014f945a65868f2a05ba12901b166048820152909550605c01604051602081830303815290604052915081805190602001209050610a467f00000000000000000000000078f1bba3868b67f4994b3e7f7ec9b0485dc85ad7838361126a565b9350610a53858488611281565b610a5f868685876112f8565b610a6a858786610b66565b610a7486856113b2565b60405163a129290360e01b81526001600160a01b0387811660048301527f00000000000000000000000052f541764e6e90eebc5c21ff570de0e2d63766b6811660248301527f0000000000000000000000002d8bce1fae00a959354acd9ebf9174337a64d4fb169063a1292903906044015f604051808303815f87803b158015610afc575f5ffd5b505af1158015610b0e573d5f5f3e3d5ffd5b5050604080516001600160a01b03898116825287811660208301528a168183015290517f26ad9f07a47e389150a15677a365d64f42af0000b792c182ada6a3b5ab193a0b9350908190036060019150a1505050915091565b6040516316bfae7f60e31b81526001600160a01b037f0000000000000000000000004e3fbd56cd56c3e72c1403e103b45db9da5b9d2b8116600483015284169063b5fd73f890602401602060405180830381865afa158015610bca573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610bee91906119a2565b610c715760405163023cb23960e41b81526001600160a01b037f0000000000000000000000004e3fbd56cd56c3e72c1403e103b45db9da5b9d2b8116600483015282811660248301528416906323cb2390906044015f604051808303815f87803b158015610c5a575f5ffd5b505af1158015610c6c573d5f5f3e3d5ffd5b505050505b6040515f602482018190529060440160408051601f198184030181529181526020820180516001600160e01b03166354c49fe960e01b179052519091505f906001600160a01b03851690610cc69084906119d2565b5f604051808303815f865af19150503d805f8114610cff576040519150601f19603f3d011682016040523d82523d5f602084013e610d04565b606091505b5050905080610d14575050505050565b5f80805b60088160ff161015610f05576040516354c49fe960e01b815260ff821660048201526001600160a01b038816906354c49fe990602401602060405180830381865afa158015610d69573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610d8d91906118a9565b604051632474e32f60e11b81526001600160a01b038083166004830152919350908816906348e9c65e9060240160c060405180830381865afa158015610dd5573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610df991906119dd565b509196505050506001600160a01b038316159050610f055742610e1f8462278d00611a37565b10610efd576040516316bfae7f60e31b81526001600160a01b03838116600483015289169063b5fd73f890602401602060405180830381865afa158015610e68573d5f5f3e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610e8c91906119a2565b610efd57610e9982611421565b15610efd5760405163023cb23960e41b81526001600160a01b03838116600483015287811660248301528916906323cb2390906044015f604051808303815f87803b158015610ee6575f5ffd5b505af1158015610ef8573d5f5f3e3d5ffd5b505050505b600101610d18565b5050505050505050565b604051633f9095b760e01b81526001600160a01b0382811660048301525f91829182917f0000000000000000000000002f50d538606fa9edd2b11e2446beb18c9d5846bb90911690633f9095b790602401602060405180830381865afa925050508015610f99575060408051601f3d908101601f19168201909252610f9691810190611a56565b60015b15610fa45750600191505b836001600160a01b0316639c868ac06040518163ffffffff1660e01b8152600401602060405180830381865afa925050508015610ffe575060408051601f3d908101601f19168201909252610ffb918101906119a2565b60015b156110065790505b604051633afeeec360e01b81526001600160e01b03197fc715e373000000000000000000000000000000000000000000000000000000001660048201526001600160a01b0385811660248301525f917f0000000000000000000000001c3a4d06532d9d1c631f99ec50dd72da43a5c6de90911690633afeeec390604401602060405180830381865afa15801561109e573d5f5f3e3d5ffd5b505050506040513d601f19601f820116820180604052508101906110c291906119a2565b9050811580156110d6575082806110d65750805b95945050505050565b604051632a704bc360e21b81526001600160a01b0382811660048301525f9182917f00000000000000000000000069d61428d089c2f35bf6a472f540d0f82d1ea2cd169063a9c12f0c90602401602060405180830381865afa158015611147573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061116b91906118a9565b6001600160a01b031614806112035750604051634bc5d73560e01b81526001600160a01b0383811660048301527f00000000000000000000000069d61428d089c2f35bf6a472f540d0f82d1ea2cd1690634bc5d73590602401602060405180830381865afa1580156111df573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061120391906119a2565b92915050565b5f816001600160a01b03166382c630666040518163ffffffff1660e01b8152600401602060405180830381865afa158015611246573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061120391906118a9565b5f6112778484845f611511565b90505b9392505050565b6040516001600160a01b03821660248201525f1960448201525f9060640160408051601f198184030181529190526020810180516001600160e01b031663095ea7b360e01b17905290506112d58382611534565b6112f257604051633e3f8f7360e01b815260040160405180910390fd5b50505050565b604051633e331d7160e11b81526001600160a01b0385811660048301528481166024830152838116604483015282811660648301526001600160e01b03197fc715e373000000000000000000000000000000000000000000000000000000001660848301527f0000000000000000000000002d8bce1fae00a959354acd9ebf9174337a64d4fb1690637c663ae29060a4015f604051808303815f87803b1580156113a0575f5ffd5b505af1158015610f05573d5f5f3e3d5ffd5b6040516001600160a01b03821660248201525f9060440160408051601f198184030181529190526020810180516001600160e01b0316635efcc08b60e11b17905290506113ff8382611534565b61141c57604051631475790360e11b815260040160405180910390fd5b505050565b5f61142b8261171a565b61143657505f919050565b7f0000000000000000000000004e3fbd56cd56c3e72c1403e103b45db9da5b9d2b6001600160a01b0316826001600160a01b03160361147657505f919050565b604051633f9095b760e01b81526001600160a01b0383811660048301527f0000000000000000000000002f50d538606fa9edd2b11e2446beb18c9d5846bb1690633f9095b790602401602060405180830381865afa9250505080156114f8575060408051601f3d908101601f191682019092526114f591810190611a56565b60015b61150457506001919050565b505f92915050565b919050565b5f5f61151d868661176a565b905061152a8385836117c8565b9695505050505050565b5f7f000000000000000000000000e5d6d047df95c6627326465cb27b64a8b77a8b916001600160a01b03167f00000000000000000000000052f541764e6e90eebc5c21ff570de0e2d63766b66001600160a01b0316036116275760405163468721a760e01b81526001600160a01b037f000000000000000000000000e5d6d047df95c6627326465cb27b64a8b77a8b91169063468721a7906115e09086905f9087908290600401611a76565b6020604051808303815f875af11580156115fc573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061162091906119a2565b9050611203565b7f000000000000000000000000e5d6d047df95c6627326465cb27b64a8b77a8b916001600160a01b031663468721a77f00000000000000000000000052f541764e6e90eebc5c21ff570de0e2d63766b65f865f8760405160240161168d93929190611ac9565b60408051601f198184030181529181526020820180516001600160e01b0316635b0e93fb60e11b1790525160e085901b6001600160e01b03191681526116da939291905f90600401611a76565b6020604051808303815f875af11580156116f6573d5f5f3e3d5ffd5b505050506040513d601f19601f8201168201806040525081019061127a91906119a2565b5f6001600160a01b0382161580159061120357507f000000000000000000000000d533a949740bb3306d119cc777fa900ba034cd526001600160a01b0316826001600160a01b0316141592915050565b6060615fd3825111156117905760405163250a241560e21b815260040160405180910390fd5b815161179d90602d611a37565b83836040516020016117b193929190611af5565b604051602081830303815290604052905092915050565b5f834710156117f75760405163cf47918160e01b81524760048201526024810185905260440160405180910390fd5b81515f0361181857604051631328927760e21b815260040160405180910390fd5b8282516020840186f590503d151981151615611839576040513d5f823e3d81fd5b6001600160a01b03811661127a5760405163b06ebf3d60e01b815260040160405180910390fd5b6001600160a01b0381168114611874575f5ffd5b50565b5f60208284031215611887575f5ffd5b813561127a81611860565b5f602082840312156118a2575f5ffd5b5035919050565b5f602082840312156118b9575f5ffd5b815161127a81611860565b8051801515811461150c575f5ffd5b5f5f5f5f5f5f60c087890312156118e8575f5ffd5b86516118f381611860565b602088015190965061190481611860565b604088015190955061191581611860565b606088015190945061192681611860565b608088015190935061193781611860565b915061194560a088016118c4565b90509295509295509295565b5f81518084528060208401602086015e5f602082860101526020601f19601f83011685010191505092915050565b6001600160a01b03831681526040602082018190525f9061127790830184611951565b5f602082840312156119b2575f5ffd5b61127a826118c4565b5f81518060208401855e5f93019283525090919050565b5f61127a82846119bb565b5f5f5f5f5f5f60c087890312156119f2575f5ffd5b86516119fd81611860565b6020880151909650611a0e81611860565b6040880151606089015160808a015160a0909a0151989b929a5090989097909650945092505050565b8082018082111561120357634e487b7160e01b5f52601160045260245ffd5b5f60208284031215611a66575f5ffd5b815180600f0b811461127a575f5ffd5b60018060a01b0385168152836020820152608060408201525f611a9c6080830185611951565b905060028310611aba57634e487b7160e01b5f52602160045260245ffd5b82606083015295945050505050565b6001600160a01b038416815260ff831660208201526060604082018190525f906110d690830184611951565b606160f81b815260f084901b6001600160f01b0319166001820152703d81600a3d39f3363d3d373d3d3d363d7360781b6003820152606083901b6001600160601b03191660148201526e5af43d82803e903d91602b57fd5bf360881b60288201525f6110d660378301846119bb56fea26469706673582212201f95f7ff0ce3b855980a32f613d8c7c25a0eb1ac89322823f2fc48fc547c959764736f6c634300081c0033

Verified Source Code Full Match

Compiler: v0.8.28+commit.7893614a EVM: cancun Optimization: Yes (200 runs)
CurveFactory.sol 200 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {IBooster} from "@interfaces/convex/IBooster.sol";
import {IStrategy} from "@interfaces/stake-dao/IStrategy.sol";
import {ILiquidityGauge} from "@interfaces/curve/ILiquidityGauge.sol";
import {IGaugeController} from "@interfaces/curve/IGaugeController.sol";
import {CurveLocker, CurveProtocol} from "@address-book/src/CurveEthereum.sol";

import {Factory} from "src/Factory.sol";
import {IRewardVault} from "src/interfaces/IRewardVault.sol";
import {ISidecarFactory} from "src/interfaces/ISidecarFactory.sol";

/// @title CurveFactory.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Factory contract for deploying Curve strategies.
contract CurveFactory is Factory {
    /// @notice The bytes4 ID of the Curve protocol
    /// @dev Used to identify the Curve protocol in the registry
    bytes4 private constant CURVE_PROTOCOL_ID = bytes4(keccak256("CURVE"));

    /// @notice Curve Gauge Controller.
    address public immutable GAUGE_CONTROLLER;

    /// @notice CVX token address.
    address public immutable CVX;

    /// @notice Address of the old strategy.
    address public immutable OLD_STRATEGY;

    /// @notice Convex Booster.
    address public immutable BOOSTER;

    /// @notice Convex Minimal Proxy Factory for Only Boost.
    address public immutable CONVEX_SIDECAR_FACTORY;

   


    /// @notice Error thrown when the set reward receiver fails.
    error SetRewardReceiverFailed();

    /// @notice Error thrown when the convex sidecar factory is not set.
    error ConvexSidecarFactoryNotSet();

    /// @notice Event emitted when a vault is deployed.
    event VaultDeployed(address gauge, address vault, address rewardReceiver, address sidecar);


    /// @notice Constructor parameters to avoid stack too deep errors.
     struct ConstructorParams {
        address gaugeController;
        address cvx;
        address oldStrategy;
        address booster;
        address protocolController;
        address vaultImplementation;
        address rewardReceiverImplementation;
        address rewardReceiverMigrationModule;
        address rewardRouter;
        address locker;
        address gateway;
        address convexSidecarFactory;
        address registrar;
    }

    constructor(
        ConstructorParams memory params
    )
        Factory(params.protocolController, params.vaultImplementation, params.rewardReceiverImplementation, params.rewardReceiverMigrationModule,params.rewardRouter, CURVE_PROTOCOL_ID, params.locker, params.gateway, params.registrar)
    {
        GAUGE_CONTROLLER = params.gaugeController;
        CVX = params.cvx;
        OLD_STRATEGY = params.oldStrategy;
        BOOSTER = params.booster;
        CONVEX_SIDECAR_FACTORY = params.convexSidecarFactory;
    }

    /// @notice Create a new vault.
    /// @param _pid Pool id.
    function create(uint256 _pid) external returns (address vault, address rewardReceiver, address sidecar) {
        require(CONVEX_SIDECAR_FACTORY != address(0), ConvexSidecarFactoryNotSet());

        (,, address gauge,,,) = IBooster(BOOSTER).poolInfo(_pid);

        /// 1. Create the vault.
        (vault, rewardReceiver) = createVault(gauge);

        /// 2. Attach the sidecar.
        sidecar = ISidecarFactory(CONVEX_SIDECAR_FACTORY).create(gauge, abi.encode(_pid));

        /// 3. Emit the event.
        emit VaultDeployed(gauge, vault, rewardReceiver, sidecar);
    }

    function _isValidToken(address _token) internal view virtual override returns (bool) {
        /// If the token is not valid, return false.
        if (!super._isValidToken(_token)) return false;

        /// We already add CVX to the vault by default.
        if (_token == CVX) return false;

        /// If the token is available as an inflation receiver, it's not valid.
        try IGaugeController(GAUGE_CONTROLLER).gauge_types(_token) {
            return false;
        } catch {
            return true;
        }
    }

    function _isValidGauge(address _gauge) internal view virtual override returns (bool) {
      bool inController = false;
    bool isKilled = false;

    // Check if gauge is in controller
    try IGaugeController(GAUGE_CONTROLLER).gauge_types(_gauge) {
        inController = true;
    } catch {}

    // Check if gauge is killed
    try ILiquidityGauge(_gauge).is_killed() returns (bool _isKilled) {
        isKilled = _isKilled;
    } catch {}

    // Check whitelist
    bool whitelisted = REGISTRAR.isWhitelisted(PROTOCOL_ID, _gauge);

    // Final condition
    return !isKilled && (inController || whitelisted);
    }

    /// @notice Check if the gauge is shutdown in the old strategy.
    /// @dev If the gauge is shutdown, we can deploy a new strategy.
    function _isValidDeployment(address _gauge) internal view virtual override returns (bool) {
        /// We check if the gauge is deployed in the old strategy by checking if the reward distributor is not 0.
        /// We also check if the gauge is shutdown.
        return
            IStrategy(OLD_STRATEGY).rewardDistributors(_gauge) == address(0)
                || IStrategy(OLD_STRATEGY).isShutdown(_gauge);
    }

    function _getAsset(address _gauge) internal view virtual override returns (address) {
        return ILiquidityGauge(_gauge).lp_token();
    }

    function _setupRewardTokens(address _vault, address _gauge, address _rewardReceiver) internal virtual override {
        /// Add CVX to the vault if it's not already there.
        if (!IRewardVault(_vault).isRewardToken(CVX)) {
            IRewardVault(_vault).addRewardToken(CVX, _rewardReceiver);
        }

        /// Check if the gauge supports extra rewards.
        /// This function is not supported on all gauges, depending on when they were deployed.
        bytes memory data = abi.encodeWithSignature("reward_tokens(uint256)", 0);

        (bool success,) = _gauge.call(data);
        if (!success) return;

        /// Loop through the extra reward tokens.
        /// 8 is the maximum number of extra reward tokens supported by the gauges.
        uint256 periodFinish;
        address _extraRewardToken;
        for (uint8 i = 0; i < 8; i++) {
            /// Get the extra reward token address.
            _extraRewardToken = ILiquidityGauge(_gauge).reward_tokens(i);
            (,, periodFinish,,,) = ILiquidityGauge(_gauge).reward_data(_extraRewardToken);

            /// If the address is 0, it means there are no more extra reward tokens.
            if (_extraRewardToken == address(0)) break;
            /// If the reward data is not active, skip. We allow for 30 days of inactivity.
            if (periodFinish + 30 days < block.timestamp) continue;
            /// If the extra reward token is already in the vault, skip.
            if (IRewardVault(_vault).isRewardToken(_extraRewardToken)) continue;
            /// Performs checks on the extra reward token.
            /// Checks like if the token is also an lp token that can be staked in the locker, these tokens are not supported.
            if (_isValidToken(_extraRewardToken)) {
                /// Then we add the extra reward token to the reward distributor through the strategy.
                IRewardVault(_vault).addRewardToken(_extraRewardToken, _rewardReceiver);
            }
        }
    }

    function _setRewardReceiver(address _gauge, address _rewardReceiver) internal override {
        /// Set _rewardReceiver as the reward receiver on the gauge.
        bytes memory data = abi.encodeWithSignature("set_rewards_receiver(address)", _rewardReceiver);
        require(_executeTransaction(_gauge, data), SetRewardReceiverFailed());
    }

    function _initializeVault(address, address _asset, address _gauge) internal override {
        /// Initialize the vault.
        /// We need to approve the asset to the gauge using the Locker.
        bytes memory data = abi.encodeWithSignature("approve(address,uint256)", _gauge, type(uint256).max);

        /// Execute the transaction.
        require(_executeTransaction(_asset, data), ApproveFailed());
    }
}
IBooster.sol 21 lines
/// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

interface IBooster {
    function poolLength() external view returns (uint256);

    function poolInfo(uint256 pid)
        external
        view
        returns (address lpToken, address token, address gauge, address crvRewards, address stash, bool shutdown);

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

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

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

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

    function claimRewards(uint256 _pid, address gauge) external returns (bool);
}
IStrategy.sol 36 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

interface IStrategy {
    function locker() external view returns (address);

    function deposit(address _token, uint256 amount) external;
    function withdraw(address _token, uint256 amount) external;

    function claimProtocolFees() external;
    function claimNativeRewards() external;
    function harvest(address _asset, bool _distributeSDT, bool _claimExtra) external;
    function harvest(address _asset, bool _distributeSDT, bool _claimExtra, bool) external;

    function rewardDistributors(address _gauge) external view returns (address);
    function isShutdown(address _gauge) external view returns (bool);
    function setShutdownMode(uint8 _shutdownMode) external;

    function feeDistributor() external view returns (address);

    /// Factory functions
    function toggleVault(address vault) external;
    function setGauge(address token, address gauge) external;
    function setLGtype(address gauge, uint256 gaugeType) external;
    function addRewardToken(address _token, address _rewardDistributor) external;
    function acceptRewardDistributorOwnership(address rewardDistributor) external;
    function setRewardDistributor(address gauge, address rewardDistributor) external;
    function addRewardReceiver(address gauge, address rewardReceiver) external;

    // Governance
    function setAccumulator(address newAccumulator) external;
    function setFeeRewardToken(address newFeeRewardToken) external;
    function setFeeDistributor(address newFeeDistributor) external;
    function setFactory(address newFactory) external;
    function governance() external view returns (address);
}
ILiquidityGauge.sol 86 lines
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;

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

interface IL2LiquidityGauge {
    function reward_data(address arg0)
        external
        view
        returns (address distributor, uint256 period_finish, uint256 rate, uint256 last_update, uint256 integral);

    function reward_tokens(uint256 arg0) external view returns (address);
    function is_killed() external view returns (bool);
    function lp_token() external view returns (address);
}

interface ILiquidityGauge is IERC20 {
    event ApplyOwnership(address admin);
    event CommitOwnership(address admin);
    event Deposit(address indexed provider, uint256 value);
    event UpdateLiquidityLimit(
        address user, uint256 original_balance, uint256 original_supply, uint256 working_balance, uint256 working_supply
    );
    event Withdraw(address indexed provider, uint256 value);

    function add_reward(address _reward_token, address _distributor) external;
    function approve(address _spender, uint256 _value) external returns (bool);
    function claim_rewards() external;
    function claim_rewards(address _addr) external;
    function claim_rewards(address _addr, address _receiver) external;
    function claimable_tokens(address addr) external returns (uint256);
    function decreaseAllowance(address _spender, uint256 _subtracted_value) external returns (bool);
    function deposit(uint256 _value) external;
    function deposit(uint256 _value, address _addr) external;
    function deposit(uint256 _value, address _addr, bool _claim_rewards) external;
    function deposit_reward_token(address _reward_token, uint256 _amount) external;
    function increaseAllowance(address _spender, uint256 _added_value) external returns (bool);
    function initialize(address _lp_token) external;
    function kick(address addr) external;
    function set_killed(bool _is_killed) external;
    function set_reward_distributor(address _reward_token, address _distributor) external;
    function set_rewards_receiver(address _receiver) external;
    function transfer(address _to, uint256 _value) external returns (bool);
    function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
    function user_checkpoint(address addr) external returns (bool);
    function withdraw(uint256 _value) external;
    function withdraw(uint256 _value, bool _claim_rewards) external;
    function allowance(address arg0, address arg1) external view returns (uint256);
    function balanceOf(address arg0) external view returns (uint256);
    function claimable_reward(address _user, address _reward_token) external view returns (uint256);
    function claimed_reward(address _addr, address _token) external view returns (uint256);
    function decimals() external view returns (uint256);
    function factory() external view returns (address);
    function future_epoch_time() external view returns (uint256);
    function inflation_rate() external view returns (uint256);
    function integrate_checkpoint() external view returns (uint256);
    function integrate_checkpoint_of(address arg0) external view returns (uint256);
    function integrate_fraction(address arg0) external view returns (uint256);
    function integrate_inv_supply(uint256 arg0) external view returns (uint256);
    function integrate_inv_supply_of(address arg0) external view returns (uint256);
    function is_killed() external view returns (bool);
    function lp_token() external view returns (address);
    function name() external view returns (string memory);
    function period() external view returns (int128);
    function period_timestamp(uint256 arg0) external view returns (uint256);
    function reward_count() external view returns (uint256);
    function reward_data(address arg0)
        external
        view
        returns (
            address token,
            address distributor,
            uint256 period_finish,
            uint256 rate,
            uint256 last_update,
            uint256 integral
        );
    function reward_integral_for(address arg0, address arg1) external view returns (uint256);
    function reward_tokens(uint256 arg0) external view returns (address);
    function rewards_receiver(address arg0) external view returns (address);
    function symbol() external view returns (string memory);
    function totalSupply() external view returns (uint256);
    function working_balances(address arg0) external view returns (uint256);
    function working_supply() external view returns (uint256);
    function admin() external view returns (address);
}
IGaugeController.sol 60 lines
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;

interface IGaugeController {
    struct VotedSlope {
        uint256 slope;
        uint256 power;
        uint256 end;
    }

    struct Points {
        uint256 bias;
        uint256 slope;
    }

    event AddType(string name, int128 type_id);
    event NewGauge(address addr, int128 gauge_type, uint256 weight);
    event NewGaugeWeight(address gauge_address, uint256 time, uint256 weight, uint256 total_weight);
    event NewTypeWeight(int128 type_id, uint256 time, uint256 weight, uint256 total_weight);
    event VoteForGauge(uint256 time, address user, address gauge_addr, uint256 weight);

    function add_gauge(address addr, int128 gauge_type) external;
    function add_gauge(address addr, int128 gauge_type, uint256 weight) external;
    function add_type(string calldata _name) external;
    function add_type(string calldata _name, uint256 weight) external;
    function change_gauge_weight(address addr, uint256 weight) external;
    function change_type_weight(int128 type_id, uint256 weight) external;
    function checkpoint() external;
    function checkpoint_gauge(address addr) external;
    function gauge_relative_weight_write(address addr) external returns (uint256);
    function gauge_relative_weight_write(address addr, uint256 time) external returns (uint256);
    function vote_for_gauge_weights(address _gauge_addr, uint256 _user_weight) external;
    function vote_for_many_gauge_weights(address[8] calldata _gauge_addrs, uint256[8] calldata _user_weight) external;
    function admin() external view returns (address);
    function gauge_exists(address _addr) external view returns (bool);
    function gauge_relative_weight(address addr) external view returns (uint256);
    function gauge_relative_weight(address addr, uint256 time) external view returns (uint256);
    function gauge_type_names(int128 arg0) external view returns (string memory);
    function gauge_types(address _addr) external view returns (int128);
    function gauges(uint256 arg0) external view returns (address);
    function get_gauge_weight(address addr) external view returns (uint256);
    function get_total_weight() external view returns (uint256);
    function get_type_weight(int128 type_id) external view returns (uint256);
    function get_weights_sum_per_type(int128 type_id) external view returns (uint256);
    function last_user_vote(address arg0, address arg1) external view returns (uint256);
    function n_gauge_types() external view returns (int128);
    function n_gauges() external view returns (int128);
    function points_sum(int128 arg0, uint256 arg1) external view returns (Points memory);
    function points_total(uint256 arg0) external view returns (uint256);
    function points_type_weight(int128 arg0, uint256 arg1) external view returns (uint256);
    function points_weight(address arg0, uint256 arg1) external view returns (Points memory);
    function time_sum(uint256 arg0) external view returns (uint256);
    function time_total() external view returns (uint256);
    function time_type_weight(uint256 arg0) external view returns (uint256);
    function time_weight(address arg0) external view returns (uint256);
    function token() external view returns (address);
    function vote_user_power(address arg0) external view returns (uint256);
    function vote_user_slopes(address arg0, address arg1) external view returns (VotedSlope memory);
    function voting_escrow() external view returns (address);
}
CurveEthereum.sol 77 lines
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;

library CurveProtocol {
    address internal constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52;
    address internal constant VECRV = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2;
    address internal constant CRV_USD = 0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E;
    address internal constant SD_VE_CRV = 0x478bBC744811eE8310B461514BDc29D03739084D;

    address internal constant FEE_DISTRIBUTOR = 0xD16d5eC345Dd86Fb63C6a9C43c517210F1027914;
    address internal constant GAUGE_CONTROLLER = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB;
    address internal constant SMART_WALLET_CHECKER = 0xca719728Ef172d0961768581fdF35CB116e0B7a4;
    address internal constant CURVE_REGISTRY = 0xc522A6606BBA746d7960404F22a3DB936B6F4F50;

    address internal constant VOTING_APP_OWNERSHIP = 0xE478de485ad2fe566d49342Cbd03E49ed7DB3356;
    address internal constant VOTING_APP_PARAMETER = 0xBCfF8B0b9419b9A88c44546519b1e909cF330399;
    address internal constant MINTER = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
    address internal constant VE_BOOST = 0xD37A6aa3d8460Bd2b6536d608103D880695A23CD;

    // Convex
    address internal constant CONVEX_PROXY = 0x989AEb4d175e16225E39E87d0D97A3360524AD80;
    address internal constant CONVEX_BOOSTER = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31;
    address internal constant CONVEX_TOKEN = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; // CVX

    address internal constant META_REGISTRY = 0xF98B45FA17DE75FB1aD0e7aFD971b0ca00e379fC;
}

library CurveLocker {
    address internal constant TOKEN = 0xD533a949740bb3306d119CC777fa900bA034cd52;
    address internal constant SDTOKEN = 0xD1b5651E55D4CeeD36251c61c50C889B36F6abB5;
    address internal constant ASDTOKEN = 0x43E54C2E7b3e294De3A155785F52AB49d87B9922;
    address internal constant ASDTOKEN_ADAPTER = 0x4e8DA27Fa7F109565De6FdB813D5AA1A6F73c75f;
    address internal constant SYASDTOKEN = 0x18C11b1DC74cAB82AD18d5034FDe93FE90a41D99;
    address internal constant LOCKER = 0x52f541764E6e90eeBc5c21Ff570De0e2D63766B6;
    address internal constant DEPOSITOR = 0xa50CB9dFFcc740EE6b6f2D4B3CBc3a876b28c335;
    address internal constant GAUGE = 0x7f50786A0b15723D741727882ee99a0BF34e3466;
    address internal constant ACCUMULATOR = 0x11F78501e6b0cbc5DE4c7e6BBabaACdb973eb4Cd;
    address internal constant VOTER = 0xb118fbE8B01dB24EdE7E87DFD19693cfca13e992;

    address internal constant STRATEGY = 0x69D61428d089C2F35Bf6a472F540D0F82D1EA2cd;
    address internal constant FACTORY = 0xDC9718E7704f10DB1aFaad737f8A04bcd14C20AA;
    address internal constant VE_BOOST_DELEGATION = 0xe1F9C8ebBC80A013cAf0940fdD1A8554d763b9cf;
}

library CurveVotemarket {
    address internal constant PLATFORM = 0x0000000895cB182E6f983eb4D8b4E0Aa0B31Ae4c;
    address internal constant CURVE_CONVEX_LOCKER_VM_RECIPIENT = 0x0000000095310137125f82f37FBe5D2F99279947;
    address internal constant CURVE_STAKE_DAO_LOCKER_VM_RECIPIENT = 0x0000000014814b037cF4a091FE00cbA2DeFc6115;
}

library CurveStrategy {
    address internal constant ACCOUNTANT = 0x93b4B9bd266fFA8AF68e39EDFa8cFe2A62011Ce0;
    address internal constant PROTOCOL_TIMELOCK = 0xb27afc7844988948FBd6210AeF4E1362bC2d8E6a;
    address internal constant PROTOCOL_CONTROLLER = 0x2d8BcE1FaE00a959354aCD9eBf9174337A64d4fb;
    address internal constant GATEWAY = 0xe5d6D047DF95c6627326465cB27B64A8b77A8b91;

    address internal constant FEE_RECEIVER = 0x60136fefE23D269aF41aB72DE483D186dC4318D6;

    address internal constant STRATEGY = 0x7D0775442d5961AE7090e4EC6C76180e8EEeEf54;

    address internal constant CONVEX_SIDECAR_IMPLEMENTATION = 0x66c3ce4718A39d44CE2430eB3E8B8d43c18bA1fa;
    address internal constant CONVEX_SIDECAR_FACTORY = 0x7Fa7fDb80b17f502C323D14Fa654a1e56B03C592;

    address internal constant FACTORY = 0x37B015FA4Ba976c57E8e3A0084288d9DcEA06003;
    address internal constant ALLOCATOR = 0x6Dbf307916Ae9c47549AbaF11Cb476252a14Ee9D;

    address internal constant REWARD_VAULT_IMPLEMENTATION = 0x74D8dd40118B13B210D0a1639141cE4458CAe0c0;
    address internal constant REWARD_RECEIVER_IMPLEMENTATION = 0x4E35037263f75F9fFE191B5f9B5C7cd0c3169019;

    address internal constant ROUTER = 0xc3a6CfC4c8112fBfd77f0d095a0eE2f2F4505Eef;
    address internal constant ROUTER_MODULE_DEPOSIT = 0xBf0a5d6a1f9A4098c69cE660F8b115dc8509b7C9;
    address internal constant ROUTER_MODULE_WITHDRAW = 0xE88772DFB857317476b77F1A25b888b9424Cf63c;
    address internal constant ROUTER_MODULE_CLAIM = 0xFD98cEcB88FC61101D4beBf1b6f9E65572222Ff5;
    address internal constant ROUTER_MODULE_MIGRATION_CURVE = 0x0e5Ca5f4989637d480968325B716Db7A6e46466B;
    address internal constant ROUTER_MODULE_MIGRATION_STAKE_DAO_V1 = 0xf0b84B9334132843fc256830Fb941d535853C120;
    address internal constant ROUTER_MODULE_MIGRATION_YEARN = 0x267C77f0616d44eD6D816527974a624B2Ba65eE3;
}
Factory.sol 238 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ProtocolContext} from "src/ProtocolContext.sol";
import {IRegistrar} from "src/interfaces/IRegistrar.sol";
import {RewardReceiverMigrationModule} from "src/modules/RewardReceiverMigrationModule.sol";

/// @title Factory.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Factory is an abstract base contract for implementing protocol-specific vault factories.
///         It provides core functionality for creating and managing vaults across different protocols,
///         including deploying vaults and reward receivers for protocol gauges, validating gauges and tokens,
///         registering vaults with the protocol controller, and setting up reward tokens for vaults.
abstract contract Factory is ProtocolContext {
    //////////////////////////////////////////////////////
    // --- IMMUTABLES
    //////////////////////////////////////////////////////

    /// @notice Registrar address which contains deployable gauges for the factory.
    IRegistrar public immutable REGISTRAR;

    /// @notice Reward vault implementation address
    /// @dev The implementation contract that will be cloned for each new vault
    address public immutable REWARD_VAULT_IMPLEMENTATION;

    /// @notice Reward receiver implementation address
    /// @dev The implementation contract that will be cloned for each new reward receiver
    address public immutable REWARD_RECEIVER_IMPLEMENTATION;

    /// @notice Reward migration module address.
    address public immutable REWARD_RECEIVER_MIGRATION_MODULE;

    /// @notice Reward router address.
    address public immutable REWARD_ROUTER;

    //////////////////////////////////////////////////////
    // --- ERRORS
    //////////////////////////////////////////////////////

    /// @notice Error thrown when the gauge is not a valid candidate
    error InvalidGauge();

    /// @notice Error thrown when the approve fails
    error ApproveFailed();

    /// @notice Error thrown when the token is not valid
    error InvalidToken();

    /// @notice Error thrown when the deployment is not valid
    error InvalidDeployment();

    /// @notice Error thrown when the gauge has been already used
    error AlreadyDeployed();

    //////////////////////////////////////////////////////
    // --- EVENTS
    //////////////////////////////////////////////////////

    /// @notice Emitted when a new vault is deployed
    /// @param vault Address of the deployed vault
    /// @param asset Address of the underlying asset
    /// @param gauge Address of the associated gauge
    event VaultDeployed(address vault, address asset, address gauge);

    //////////////////////////////////////////////////////
    // --- CONSTRUCTOR
    //////////////////////////////////////////////////////

    /// @notice Initializes the factory with protocol controller, reward token, and vault implementation
    /// @param _protocolController Address of the protocol controller
    /// @param _vaultImplementation Address of the reward vault implementation
    /// @param _rewardReceiverImplementation Address of the reward receiver implementation
    /// @param _protocolId Protocol identifier
    /// @param _locker Address of the locker
    /// @param _gateway Address of the gateway
    constructor(
        address _protocolController,
        address _vaultImplementation,
        address _rewardReceiverImplementation,
        address _rewardReceiverMigrationModule,
        address _rewardRouter,
        bytes4 _protocolId,
        address _locker,
        address _gateway,
        address _registrar
    ) ProtocolContext(_protocolId, _protocolController, _locker, _gateway) {
        require(
            _protocolController != address(0) && _vaultImplementation != address(0)
                && _rewardReceiverImplementation != address(0),
            ZeroAddress()
        );

        REWARD_ROUTER = _rewardRouter;
        REGISTRAR = IRegistrar(_registrar);
        REWARD_VAULT_IMPLEMENTATION = _vaultImplementation;
        REWARD_RECEIVER_IMPLEMENTATION = _rewardReceiverImplementation;
        REWARD_RECEIVER_MIGRATION_MODULE = _rewardReceiverMigrationModule;
    }

    //////////////////////////////////////////////////////
    // --- EXTERNAL FUNCTIONS
    //////////////////////////////////////////////////////

    /// @notice Create a new vault for a given gauge
    /// @dev Deploys a vault and reward receiver for the gauge, registers them, and sets up reward tokens
    /// @param gauge Address of the gauge
    /// @return vault Address of the deployed vault
    /// @return rewardReceiver Address of the deployed reward receiver
    /// @custom:throws InvalidGauge If the gauge is not valid
    /// @custom:throws InvalidDeployment If the deployment is not valid
    /// @custom:throws GaugeAlreadyUsed If the gauge has already been used
    function createVault(address gauge) public virtual returns (address vault, address rewardReceiver) {
        /// Perform checks on the gauge to make sure it's valid and can be used
        require(_isValidGauge(gauge), InvalidGauge());
        require(_isValidDeployment(gauge), InvalidDeployment());
        require(PROTOCOL_CONTROLLER.vault(gauge) == address(0), AlreadyDeployed());

        /// Get the asset address from the gauge
        address asset = _getAsset(gauge);

        /// Prepare the initialization data for the vault
        /// The vault needs: gauge and asset
        bytes memory data = abi.encodePacked(gauge, asset);

        /// Generate a deterministic salt based on the gauge and asset
        bytes32 salt = keccak256(data);

        /// Clone the vault implementation with the initialization data
        vault = Clones.cloneDeterministicWithImmutableArgs(REWARD_VAULT_IMPLEMENTATION, data, salt);

        /// Prepare the initialization data for the reward receiver
        /// The reward receiver needs: vault
        data = abi.encodePacked(vault, address(0), REWARD_ROUTER);

        /// Generate a deterministic salt based on the initialization data.
        salt = keccak256(data);

        /// Deploy Reward Receiver.
        rewardReceiver = Clones.cloneDeterministicWithImmutableArgs(REWARD_RECEIVER_IMPLEMENTATION, data, salt);

        /// Initialize the vault.
        /// @dev Can be approval if needed etc.
        _initializeVault(vault, asset, gauge);

        /// Register the vault in the protocol controller
        _registerVault(gauge, vault, asset, rewardReceiver);

        /// Add extra reward tokens to the vault
        _setupRewardTokens(vault, gauge, rewardReceiver);

        /// Set the reward receiver for the gauge
        _setRewardReceiver(gauge, rewardReceiver);

        /// Set the valid allocation target.
        PROTOCOL_CONTROLLER.setValidAllocationTarget(gauge, LOCKER);

        emit VaultDeployed(vault, asset, gauge);
    }

    /// @notice Sync reward tokens for a gauge
    /// @dev Updates the reward tokens for an existing vault
    /// @param gauge Address of the gauge
    /// @custom:throws InvalidGauge If the gauge is not valid or has no associated vault
    function syncRewardTokens(address gauge) external {
        address vault = PROTOCOL_CONTROLLER.vault(gauge);
        require(vault != address(0), InvalidGauge());

        /// 0. Migrate the reward receiver if the migration module is set.
        if (REWARD_RECEIVER_MIGRATION_MODULE != address(0)) {
            RewardReceiverMigrationModule(REWARD_RECEIVER_MIGRATION_MODULE).migrate(gauge);
        }

        _setupRewardTokens(vault, gauge, PROTOCOL_CONTROLLER.rewardReceiver(gauge));
    }

    //////////////////////////////////////////////////////
    // --- INTERNAL VIRTUAL FUNCTIONS
    //////////////////////////////////////////////////////

    /// @notice Get the asset address from a gauge
    /// @dev Must be implemented by derived factories to handle protocol-specific asset retrieval
    /// @param gauge Address of the gauge
    /// @return The address of the asset associated with the gauge
    function _getAsset(address gauge) internal view virtual returns (address);

    /// @notice Check if a deployment is valid
    /// @dev Can be overridden by derived factories to add additional deployment validation
    /// @return True if the deployment is valid, false otherwise
    function _isValidDeployment(address) internal view virtual returns (bool) {
        return true;
    }

    /// @notice Initialize the vault
    /// @param vault Address of the vault
    /// @param asset Address of the asset
    /// @param gauge Address of the gauge
    function _initializeVault(address vault, address asset, address gauge) internal virtual;

    /// @notice Register the vault in the protocol controller
    /// @param gauge Address of the gauge
    /// @param vault Address of the vault
    /// @param asset Address of the asset
    /// @param rewardReceiver Address of the reward receiver
    function _registerVault(address gauge, address vault, address asset, address rewardReceiver) internal {
        PROTOCOL_CONTROLLER.registerVault(gauge, vault, asset, rewardReceiver, PROTOCOL_ID);
    }

    /// @notice Setup reward tokens for the vault
    /// @dev Must be implemented by derived factories to handle protocol-specific reward token setup
    /// @param vault Address of the vault
    /// @param gauge Address of the gauge
    /// @param rewardReceiver Address of the reward receiver
    function _setupRewardTokens(address vault, address gauge, address rewardReceiver) internal virtual;

    /// @notice Set the reward receiver for a gauge
    /// @dev Must be implemented by derived factories to handle protocol-specific reward receiver setup
    /// @param gauge Address of the gauge
    /// @param rewardReceiver Address of the reward receiver
    function _setRewardReceiver(address gauge, address rewardReceiver) internal virtual;

    /// @notice Check if a gauge is valid
    /// @dev Must be implemented by derived factories to handle protocol-specific gauge validation
    /// @param gauge Address of the gauge
    /// @return isValid True if the gauge is valid
    function _isValidGauge(address gauge) internal view virtual returns (bool);

    /// @notice Check if a token is valid as a reward token
    /// @dev Validates that the token is not zero address and not the main reward token
    /// @param token Address of the token
    /// @return isValid True if the token is valid
    function _isValidToken(address token) internal view virtual returns (bool) {
        return token != address(0) && token != REWARD_TOKEN;
    }
}
IRewardVault.sol 59 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IAccountant} from "src/interfaces/IAccountant.sol";

/// @title IRewardVault
/// @notice Interface for the RewardVault contract
interface IRewardVault is IERC4626 {
    function addRewardToken(address rewardsToken, address distributor) external;

    function depositRewards(address _rewardsToken, uint128 _amount) external;

    function deposit(uint256 assets, address receiver, address referrer) external returns (uint256 shares);

    function deposit(address account, address receiver, uint256 assets, address referrer)
        external
        returns (uint256 shares);

    function claim(address[] calldata tokens, address receiver) external returns (uint256[] memory amounts);

    function claim(address account, address[] calldata tokens, address receiver)
        external
        returns (uint256[] memory amounts);

    function getRewardsDistributor(address token) external view returns (address);

    function getLastUpdateTime(address token) external view returns (uint32);

    function getPeriodFinish(address token) external view returns (uint32);

    function getRewardRate(address token) external view returns (uint128);

    function getRewardPerTokenStored(address token) external view returns (uint128);

    function getRewardPerTokenPaid(address token, address account) external view returns (uint128);

    function getClaimable(address token, address account) external view returns (uint128);

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

    function lastTimeRewardApplicable(address token) external view returns (uint256);

    function rewardPerToken(address token) external view returns (uint128);

    function earned(address account, address token) external view returns (uint128);

    function isRewardToken(address rewardToken) external view returns (bool);

    function resumeVault() external;

    function gauge() external view returns (address);

    function ACCOUNTANT() external view returns (IAccountant);

    function checkpoint(address account) external;

    function PROTOCOL_ID() external view returns (bytes4);
}
ISidecarFactory.sol 7 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface ISidecarFactory {
    function sidecar(address gauge) external view returns (address);
    function create(address token, bytes memory args) external returns (address);
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @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);
}
Clones.sol 262 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    error CloneArgumentsTooLong();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        return clone(implementation, 0);
    }

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple times will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
     * access the arguments within the implementation, use {fetchCloneArgs}.
     *
     * This function uses the create opcode, which should never revert.
     */
    function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
        return cloneWithImmutableArgs(implementation, args, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
     * parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneWithImmutableArgs(
        address implementation,
        bytes memory args,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        assembly ("memory-safe") {
            instance := create(value, add(bytecode, 0x20), mload(bytecode))
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation` with custom
     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
     * access the arguments within the implementation, use {fetchCloneArgs}.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
     * `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
     * at the same address.
     */
    function cloneDeterministicWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
     * but with a `value` parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministicWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        return Create2.deploy(value, salt, bytecode);
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
     */
    function predictDeterministicAddressWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        return Create2.computeAddress(salt, keccak256(bytecode), deployer);
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
     */
    function predictDeterministicAddressWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
    }

    /**
     * @dev Get the immutable args attached to a clone.
     *
     * - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
     *   function will return an empty array.
     * - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
     *   `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
     *   creation.
     * - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
     *   function should only be used to check addresses that are known to be clones.
     */
    function fetchCloneArgs(address instance) internal view returns (bytes memory) {
        bytes memory result = new bytes(instance.code.length - 45); // revert if length is too short
        assembly ("memory-safe") {
            extcodecopy(instance, add(result, 32), 45, mload(result))
        }
        return result;
    }

    /**
     * @dev Helper that prepares the initcode of the proxy with immutable args.
     *
     * An assembly variant of this function requires copying the `args` array, which can be efficiently done using
     * `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
     * abi.encodePacked is more expensive but also more portable and easier to review.
     *
     * NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
     * With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
     */
    function _cloneCodeWithImmutableArgs(
        address implementation,
        bytes memory args
    ) private pure returns (bytes memory) {
        if (args.length > 24531) revert CloneArgumentsTooLong();
        return
            abi.encodePacked(
                hex"61",
                uint16(args.length + 45),
                hex"3d81600a3d39f3363d3d373d3d3d363d73",
                implementation,
                hex"5af43d82803e903d91602b57fd5bf3",
                args
            );
    }
}
ProtocolContext.sol 138 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {IModuleManager} from "@interfaces/safe/IModuleManager.sol";

import {IAccountant} from "src/interfaces/IAccountant.sol";
import {IProtocolController} from "src/interfaces/IProtocolController.sol";

/// @title ProtocolContext.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Base contract providing shared protocol configuration and transaction execution.
contract ProtocolContext {
    //////////////////////////////////////////////////////
    // --- IMMUTABLES
    //////////////////////////////////////////////////////

    /// @notice Unique identifier for the protocol (e.g., keccak256("CURVE") for Curve)
    /// @dev Used to look up protocol-specific components in ProtocolController
    bytes4 public immutable PROTOCOL_ID;

    /// @notice The locker contract that holds and manages protocol tokens (e.g., veCRV)
    /// @dev On L2s, this may be the same as GATEWAY when no separate locker exists
    address public immutable LOCKER;

    /// @notice Safe multisig that owns the locker and executes privileged operations
    /// @dev All protocol interactions go through this gateway for security
    address public immutable GATEWAY;

    /// @notice The accountant responsible for tracking rewards and user balances
    /// @dev Retrieved from ProtocolController during construction
    address public immutable ACCOUNTANT;

    /// @notice The main reward token for this protocol (e.g., CRV for Curve)
    /// @dev Retrieved from the accountant's configuration
    address public immutable REWARD_TOKEN;

    /// @notice Reference to the central registry for protocol components
    IProtocolController public immutable PROTOCOL_CONTROLLER;

    //////////////////////////////////////////////////////
    // --- ERRORS
    //////////////////////////////////////////////////////

    /// @notice Error thrown when a required address is zero
    error ZeroAddress();

    /// @notice Error thrown when a protocol ID is zero
    error InvalidProtocolId();

    //////////////////////////////////////////////////////
    // --- CONSTRUCTOR
    //////////////////////////////////////////////////////

    /// @notice Initializes protocol configuration that all inheriting contracts will use
    /// @dev Retrieves accountant and reward token from ProtocolController for consistency
    /// @param _protocolId The protocol identifier (must match registered protocol in controller)
    /// @param _protocolController The protocol controller contract address
    /// @param _locker The locker contract address (pass address(0) for L2s where gateway acts as locker)
    /// @param _gateway The gateway contract address (Safe multisig)
    /// @custom:throws ZeroAddress If protocol controller or gateway is zero
    /// @custom:throws InvalidProtocolId If protocol ID is empty
    constructor(bytes4 _protocolId, address _protocolController, address _locker, address _gateway) {
        require(_protocolController != address(0) && _gateway != address(0), ZeroAddress());
        require(_protocolId != bytes4(0), InvalidProtocolId());

        GATEWAY = _gateway;
        PROTOCOL_ID = _protocolId;
        ACCOUNTANT = IProtocolController(_protocolController).accountant(_protocolId);
        REWARD_TOKEN = IAccountant(ACCOUNTANT).REWARD_TOKEN();
        PROTOCOL_CONTROLLER = IProtocolController(_protocolController);

        // L2 optimization: Gateway can act as both transaction executor and token holder
        if (_locker == address(0)) {
            LOCKER = GATEWAY;
        } else {
            LOCKER = _locker;
        }
    }

    //////////////////////////////////////////////////////
    // --- INTERNAL FUNCTIONS
    //////////////////////////////////////////////////////

    /// @notice Executes privileged transactions through the Safe module system
    /// @dev Handles two execution patterns:
    ///      - Mainnet: Gateway -> Locker -> Target (locker holds funds and executes)
    ///      - L2: Gateway acts as locker and executes directly on target
    /// @param target The address of the contract to interact with
    /// @param data The calldata to send to the target
    /// @return success Whether the transaction executed successfully
    function _executeTransaction(address target, bytes memory data) internal returns (bool success) {
        if (LOCKER == GATEWAY) {
            // L2 pattern: Gateway holds funds and executes directly
            success = IModuleManager(GATEWAY).execTransactionFromModule(target, 0, data, IModuleManager.Operation.Call);
        } else {
            // Mainnet pattern: Gateway instructs locker (which holds funds) to execute
            // The locker contract has the necessary approvals and balances
            success = IModuleManager(GATEWAY)
                .execTransactionFromModule(
                    LOCKER,
                    0,
                    abi.encodeWithSignature("execute(address,uint256,bytes)", target, 0, data),
                    IModuleManager.Operation.Call
                );
        }
    }

    /// @notice Executes privileged transactions through the Safe module system
    /// @dev Handles two execution patterns:
    ///      - Mainnet: Gateway -> Locker -> Target (locker holds funds and executes)
    ///      - L2: Gateway acts as locker and executes directly on target
    /// @param target The address of the contract to interact with
    /// @param data The calldata to send to the target
    /// @return success Whether the transaction executed successfully
    function _executeTransactionReturnData(address target, bytes memory data)
        internal
        returns (bool success, bytes memory returnData)
    {
        if (LOCKER == GATEWAY) {
            // L2 pattern: Gateway holds funds and executes directly
            (success, returnData) = IModuleManager(GATEWAY)
                .execTransactionFromModuleReturnData(target, 0, data, IModuleManager.Operation.Call);
        } else {
            // Mainnet pattern: Gateway instructs locker (which holds funds) to execute
            // The locker contract has the necessary approvals and balances
            (success, returnData) = IModuleManager(GATEWAY)
                .execTransactionFromModuleReturnData(
                    LOCKER,
                    0,
                    abi.encodeWithSignature("execute(address,uint256,bytes)", target, 0, data),
                    IModuleManager.Operation.Call
                );
        }
    }
}
IRegistrar.sol 25 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/// @title IRegistrar
/// @author Stake DAO
/// @notice Interface for the Registrar contract that manages whitelisted deployment targets per protocol.
interface IRegistrar {
    /// @notice Emitted when a deployment target is whitelisted or unwhitelisted for a protocol.
    /// @param protocolId Protocol ID (bytes4)
    /// @param target     Address (gauge/asset) that is whitelisted or unwhitelisted
    /// @param whitelisted    Boolean if whitelisted
    event WhitelistedTarget(bytes4 indexed protocolId, address indexed target, bool whitelisted);

    /// @notice Set or unset an allowed target for a given protocol.
    /// @param protocolId ID of the protocol (bytes4)
    /// @param target     Address to allow/disallow
    /// @param allowed    Boolean if allowed
    function setAllowed(bytes4 protocolId, address target, bool allowed) external;

    /// @notice Check if a target is whitelisted for a given protocol.
    /// @param protocolId Protocol ID (bytes4)
    /// @param target     Address to check
    /// @return whitelisted   True if whitelisted, false if not whitelisted
    function isWhitelisted(bytes4 protocolId, address target) external view returns (bool whitelisted);
}
RewardReceiverMigrationModule.sol 174 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ILiquidityGauge} from "@interfaces/curve/ILiquidityGauge.sol";

import {ProtocolContext} from "src/ProtocolContext.sol";

import {IStrategy} from "src/interfaces/IStrategy.sol";
import {IRewardReceiver} from "src/interfaces/IRewardReceiver.sol";
import {ICurveFactory} from "src/interfaces/IFactoryWithSidecar.sol";
import {ConvexSidecar} from "src/integrations/curve/ConvexSidecar.sol";
import {OnlyBoostAllocator} from "src/integrations/curve/OnlyBoostAllocator.sol";
import {ConvexSidecarFactory} from "src/integrations/curve/ConvexSidecarFactory.sol";

/// @title RewardReceiverMigrationModule.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice RewardReceiverMigrationModule is a module that migrates the reward receiver from a legacy reward receiver to a new reward receiver.
contract RewardReceiverMigrationModule is ProtocolContext {

    /// @notice Cache struct to avoid stack too deep errors.
    struct Cache {
        address vault;
        address strategy;
        address allocator;
        address rewardReceiver;
        address sidecarFactory;
        address sidecar;
        address asset;
        address factory;
        address newRewardReceiverImplementation;
    }

    /// @notice The reward router address.
    address public immutable REWARD_ROUTER;

    /// @notice The old Convex sidecar factory address.
    address public immutable OLD_SIDECAR_FACTORY;

    /// @notice The new Convex sidecar factory address.
    address public immutable NEW_SIDECAR_FACTORY;

    /// @notice Error thrown when the set reward receiver fails.
    error SetRewardReceiverFailed();

    /// @notice Error thrown when the set locker only fails.
    error SetLockerOnlyFailed();

    /// @notice Error thrown when the curve factory does not point to the expected sidecar factory.
    error UnexpectedSidecarFactory(address expected, address actual);

    /// @notice Emitted when the migration is completed.
    event MigrationCompleted(address indexed vault, address indexed gauge, address newSidecar, address newRewardReceiver);

    constructor(bytes4 _protocolId, address _protocolController, address _locker, address _gateway, address _rewardRouter, address _oldSidecarFactory, address _newSidecarFactory)
        ProtocolContext(_protocolId, _protocolController, _locker, _gateway)
    {
        REWARD_ROUTER = _rewardRouter;
        OLD_SIDECAR_FACTORY = _oldSidecarFactory;
        NEW_SIDECAR_FACTORY = _newSidecarFactory;
    }

    /// @notice Migrates the reward receiver for a given gauge.
    /// @dev Because the old ConvexSidecar implementation use reward receiver address as immutable argument, we need to migrate sidecar as well.
    function migrate(address gauge) external {
        /// 0a. Cache the required addresses to avoid stack too deep errors.
        address factory = PROTOCOL_CONTROLLER.factory(PROTOCOL_ID);
        Cache memory cache = Cache({
            vault: PROTOCOL_CONTROLLER.vault(gauge),
            strategy: PROTOCOL_CONTROLLER.strategy(PROTOCOL_ID),
            allocator: PROTOCOL_CONTROLLER.allocator(PROTOCOL_ID),
            rewardReceiver: PROTOCOL_CONTROLLER.rewardReceiver(gauge),
            sidecarFactory: ICurveFactory(factory).CONVEX_SIDECAR_FACTORY(),
            sidecar: ConvexSidecarFactory(OLD_SIDECAR_FACTORY).sidecar(gauge),
            asset: PROTOCOL_CONTROLLER.asset(gauge),
            factory: factory,
            newRewardReceiverImplementation: ICurveFactory(factory).REWARD_RECEIVER_IMPLEMENTATION()
        });

        require (cache.sidecarFactory == NEW_SIDECAR_FACTORY, UnexpectedSidecarFactory(NEW_SIDECAR_FACTORY, cache.sidecarFactory));

        address legacyRewardReceiver = _getLegacyRewardReceiver(cache.rewardReceiver);
        bytes memory data = abi.encodePacked(cache.vault, legacyRewardReceiver, REWARD_ROUTER);

        /// 0b. Check if the migration is possible.
        if(_isAlreadyMigrated(gauge, cache.factory, cache.newRewardReceiverImplementation, data)) return;

        /// 1a. Flush residual rewards if the old sidecar is not zero address.
        uint pid;
        address newSidecar;
        if(cache.sidecar != address(0)) {
            /// 1b. Flush residual rewards using `ConvexSidecar.claimExtraRewards()`
            ConvexSidecar(cache.sidecar).claimExtraRewards();

            /// 1c. Cache the pid.
            pid = ConvexSidecar(cache.sidecar).pid();

            /// 1d. Freeze Convex allocations using `OnlyBoostAllocator.setLockerOnly(gauge, true)`
            require(_executeTransaction(address(cache.allocator), abi.encodeWithSelector(OnlyBoostAllocator.setLockerOnly.selector, gauge, true)), SetLockerOnlyFailed());

            /// 1e. Rebalance the strategy to drain the old sidecar.
            IStrategy(cache.strategy).rebalance(gauge);

            /// 1f. Disable old sidecar in the ProtocolController using `removeValidAllocationTarget(gauge, oldSidecar)` 
            PROTOCOL_CONTROLLER.removeValidAllocationTarget(gauge, cache.sidecar);

            /// 1g. Deploy new sidecar using `ConvexSidecarFactory.create(gauge, abi.encode(pid))` using the new ConvexSidecarFactory contract
            newSidecar = ConvexSidecarFactory(cache.sidecarFactory).create(gauge, abi.encode(pid));

            /// 1i. Reenable Convex allocations using `OnlyBoostAllocator.setLockerOnly(gauge, false)`
            require(_executeTransaction(address(cache.allocator), abi.encodeWithSelector(OnlyBoostAllocator.setLockerOnly.selector, gauge, false)), SetLockerOnlyFailed());

            /// 1j. Repopulate the new sidecar using `Strategy.rebalance(gauge)`
            IStrategy(cache.strategy).rebalance(gauge);
        }


        /// 2 Generate a deterministic salt based on the initialization data.
        bytes32 salt = keccak256(data);

        /// 2b. Clone the reward receiver implementation with the initialization data.
        address newRewardReceiver = Clones.cloneDeterministicWithImmutableArgs(cache.newRewardReceiverImplementation, data, salt);

        /// 3. Update the reward receiver in the ProtocolController.
        PROTOCOL_CONTROLLER.registerVault(gauge, cache.vault, cache.asset, newRewardReceiver, PROTOCOL_ID);

        /// 4. Set the reward receiver for the gauge.
        _setRewardReceiver(gauge, newRewardReceiver);

        /// 5. Emit the migration completed event.
        emit MigrationCompleted(cache.vault, gauge, newSidecar, newRewardReceiver);
    }

    /// @notice Checks if the migration is possible.
    /// @dev The migration is onlu possible if the gauge was not already migrated.
    /// It should not revert. This function is used in the Factory to migrate before syncing extra rewards.
    function _isAlreadyMigrated(address gauge, address factory, address newRewardReceiverImplementation, bytes memory data) internal view returns (bool) {
        return PROTOCOL_CONTROLLER.rewardReceiver(gauge) == getRewardReceiverAddress(newRewardReceiverImplementation, factory, data)
            || PROTOCOL_CONTROLLER.rewardReceiver(gauge) == getRewardReceiverAddress(newRewardReceiverImplementation, address(this), data);
    }

    /// @notice Computes the reward receiver address for a given deployer and data.
    /// @param deployer The deployer of the reward receiver (factory or module).
    /// @return rewardReceiver The address of the reward receiver.
    function getRewardReceiverAddress(address newRewardReceiverImplementation, address deployer, bytes memory data) internal pure returns (address rewardReceiver) {
        bytes32 salt = keccak256(data);
        return Clones.predictDeterministicAddressWithImmutableArgs(newRewardReceiverImplementation, data, salt, deployer);
    }

    /// @notice Computes the legacy reward receiver address for a given current reward receiver.
    /// @param current The current reward receiver address.
    /// @return legacy The legacy reward receiver address.
    function _getLegacyRewardReceiver(address current) internal view returns (address legacy) {
        if (current == address(0)) return current;

        try IRewardReceiver(current).legacyRewardReceiver() returns (address _legacy) {
            legacy = _legacy;
        } catch {
            return current;
        }
    }

    /// @notice Sets the reward receiver for a gauge.
    /// @param _gauge The gauge to set the reward receiver for.
    /// @param _rewardReceiver The reward receiver to set.
    function _setRewardReceiver(address _gauge, address _rewardReceiver) internal {
        /// Set _rewardReceiver as the reward receiver on the gauge.
        bytes memory data = abi.encodeWithSignature("set_rewards_receiver(address)", _rewardReceiver);
        require(_executeTransaction(_gauge, data), SetRewardReceiverFailed());
    }
}
IERC4626.sol 230 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import {IStrategy} from "src/interfaces/IStrategy.sol";

interface IAccountant {
    function checkpoint(
        address gauge,
        address from,
        address to,
        uint128 amount,
        IStrategy.PendingRewards calldata pendingRewards,
        IStrategy.HarvestPolicy policy
    ) external;

    function checkpoint(
        address gauge,
        address from,
        address to,
        uint128 amount,
        IStrategy.PendingRewards calldata pendingRewards,
        IStrategy.HarvestPolicy policy,
        address referrer
    ) external;

    function totalSupply(address asset) external view returns (uint128);
    function balanceOf(address asset, address account) external view returns (uint128);

    function claim(address[] calldata _gauges, bytes[] calldata harvestData) external;
    function claim(address[] calldata _gauges, bytes[] calldata harvestData, address receiver) external;
    function claim(address[] calldata _gauges, address account, bytes[] calldata harvestData, address receiver) external;

    function claimProtocolFees() external;
    function harvest(address[] calldata _gauges, bytes[] calldata _harvestData, address _receiver) external;

    function REWARD_TOKEN() external view returns (address);

    function getPendingRewards(address vault) external view returns (uint128);
    function getPendingRewards(address vault, address account) external view returns (uint256);

    function SCALING_FACTOR() external view returns (uint128);
}
Create2.sol 92 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        assembly ("memory-safe") {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
            // if no address was created, and returndata is not empty, bubble revert
            if and(iszero(addr), not(iszero(returndatasize()))) {
                let p := mload(0x40)
                returndatacopy(p, 0, returndatasize())
                revert(p, returndatasize())
            }
        }
        if (addr == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        assembly ("memory-safe") {
            let ptr := mload(0x40) // Get free memory pointer

            // |                   | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |-------------------|---------------------------------------------------------------------------|
            // | bytecodeHash      |                                                        CCCCCCCCCCCCC...CC |
            // | salt              |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer          | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF              |            FF                                                             |
            // |-------------------|---------------------------------------------------------------------------|
            // | memory            | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 85) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }
}
Errors.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}
IModuleManager.sol 93 lines
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/**
 * @title IModuleManager - An interface of contract managing Safe modules
 * @notice Modules are extensions with unlimited access to a Safe that can be added to a Safe by its owners.
 *            ⚠️ WARNING: Modules are a security risk since they can execute arbitrary transactions,
 *            so only trusted and audited modules should be added to a Safe. A malicious module can
 *            completely takeover a Safe.
 * @author @safe-global/safe-protocol
 */
interface IModuleManager {
    enum Operation {
        Call,
        DelegateCall
    }
    event EnabledModule(address indexed module);
    event DisabledModule(address indexed module);
    event ExecutionFromModuleSuccess(address indexed module);
    event ExecutionFromModuleFailure(address indexed module);
    event ChangedModuleGuard(address indexed moduleGuard);

    /**
     * @notice Enables the module `module` for the Safe.
     * @dev This can only be done via a Safe transaction.
     * @param module Module to be whitelisted.
     */
    function enableModule(address module) external;

    /**
     * @notice Disables the module `module` for the Safe.
     * @dev This can only be done via a Safe transaction.
     * @param prevModule Previous module in the modules linked list.
     * @param module Module to be removed.
     */
    function disableModule(address prevModule, address module) external;

    /**
     * @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token)
     * @param to Destination address of module transaction.
     * @param value Ether value of module transaction.
     * @param data Data payload of module transaction.
     * @param operation Operation type of module transaction.
     * @return success Boolean flag indicating if the call succeeded.
     */
    function execTransactionFromModule(address to, uint256 value, bytes memory data, Operation operation)
        external
        returns (bool success);

    /**
     * @notice Execute `operation` (0: Call, 1: DelegateCall) to `to` with `value` (Native Token) and return data
     * @param to Destination address of module transaction.
     * @param value Ether value of module transaction.
     * @param data Data payload of module transaction.
     * @param operation Operation type of module transaction.
     * @return success Boolean flag indicating if the call succeeded.
     * @return returnData Data returned by the call.
     */
    function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Operation operation)
        external
        returns (bool success, bytes memory returnData);

    /**
     * @notice Returns if a module is enabled
     * @return True if the module is enabled
     */
    function isModuleEnabled(address module) external view returns (bool);

    /**
     * @notice Returns an array of modules.
     *         If all entries fit into a single page, the next pointer will be 0x1.
     *         If another page is present, next will be the last element of the returned array.
     * @param start Start of the page. Has to be a module or start pointer (0x1 address)
     * @param pageSize Maximum number of modules that should be returned. Has to be > 0
     * @return array Array of modules.
     * @return next Start of the next page.
     */
    function getModulesPaginated(address start, uint256 pageSize)
        external
        view
        returns (address[] memory array, address next);

    /**
     * @dev Set a module guard that checks transactions initiated by the module before execution
     *      This can only be done via a Safe transaction.
     *      ⚠️ IMPORTANT: Since a module guard has full power to block Safe transaction execution initiated via a module,
     *        a broken module guard can cause a denial of service for the Safe modules. Make sure to carefully
     *        audit the module guard code and design recovery mechanisms.
     * @notice Set Module Guard `moduleGuard` for the Safe. Make sure you trust the module guard.
     * @param moduleGuard The address of the module guard to be used or the zero address to disable the module guard.
     */
    function setModuleGuard(address moduleGuard) external;
}
IProtocolController.sol 38 lines
/// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface IProtocolController {
    function vault(address) external view returns (address);
    function asset(address) external view returns (address);
    function rewardReceiver(address) external view returns (address);

    function allowed(address, address, bytes4 selector) external view returns (bool);
    function permissionSetters(address) external view returns (bool);
    function isRegistrar(address) external view returns (bool);

    function locker(bytes4 protocolId) external view returns (address);
    function gateway(bytes4 protocolId) external view returns (address);
    function strategy(bytes4 protocolId) external view returns (address);
    function allocator(bytes4 protocolId) external view returns (address);
    function accountant(bytes4 protocolId) external view returns (address);
    function feeReceiver(bytes4 protocolId) external view returns (address);
    function factory(bytes4 protocolId) external view returns (address);

    function isPaused(bytes4) external view returns (bool);
    function isShutdown(address) external view returns (bool);

    function registerVault(address _gauge, address _vault, address _asset, address _rewardReceiver, bytes4 _protocolId)
        external;

    function setValidAllocationTarget(address _gauge, address _target) external;
    function removeValidAllocationTarget(address _gauge, address _target) external;
    function isValidAllocationTarget(address _gauge, address _target) external view returns (bool);

    function pause(bytes4 protocolId) external;
    function unpause(bytes4 protocolId) external;
    function shutdown(address _gauge) external;
    function unshutdown(address _gauge) external;

    function setPermissionSetter(address _setter, bool _allowed) external;
    function setPermission(address _contract, address _caller, bytes4 _selector, bool _allowed) external;
}
IStrategy.sol 32 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import "src/interfaces/IAllocator.sol";

interface IStrategy {
    /// @notice The policy for harvesting rewards.
    enum HarvestPolicy {
        CHECKPOINT,
        HARVEST
    }

    struct PendingRewards {
        uint128 feeSubjectAmount;
        uint128 totalAmount;
    }

    function deposit(IAllocator.Allocation calldata allocation, HarvestPolicy policy)
        external
        returns (PendingRewards memory pendingRewards);
    function withdraw(IAllocator.Allocation calldata allocation, HarvestPolicy policy, address receiver)
        external
        returns (PendingRewards memory pendingRewards);

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

    function harvest(address gauge, bytes calldata extraData) external returns (PendingRewards memory pendingRewards);
    function flush() external;

    function shutdown(address gauge) external;
    function rebalance(address gauge) external;
}
IRewardReceiver.sol 11 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

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

interface IRewardReceiver {
    function distributeRewards() external;
    function distributeRewardToken(IERC20 token) external;
    function pullRewards(address token) external returns (uint128 amount);
    function legacyRewardReceiver() external view returns (address);
}
IFactoryWithSidecar.sol 15 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {IFactory} from 'src/interfaces/IFactory.sol';

/// @title IFactoryWithSidecar.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Interface for factories that support Convex sidecar functionality.
interface ICurveFactory is IFactory {
    /// @notice Convex sidecar factory address
    function CONVEX_SIDECAR_FACTORY() external view returns (address);
}
ConvexSidecar.sol 209 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

/// Interfaces
import {IBooster} from "@interfaces/convex/IBooster.sol";
import {IBaseRewardPool} from "@interfaces/convex/IBaseRewardPool.sol";
import {IStashTokenWrapper} from "@interfaces/convex/IStashTokenWrapper.sol";

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

/// Project Contracts
import {Sidecar} from "src/Sidecar.sol";
import {ImmutableArgsParser} from "src/libraries/ImmutableArgsParser.sol";

/// @title ConvexSidecar.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Sidecar for managing Convex rewards and deposits.
contract ConvexSidecar is Sidecar {
    using SafeERC20 for IERC20;
    using ImmutableArgsParser for address;

    /// @notice The bytes4 ID of the Curve protocol
    /// @dev Used to identify the Curve protocol in the registry
    bytes4 private constant CURVE_PROTOCOL_ID = bytes4(keccak256("CURVE"));

    //////////////////////////////////////////////////////
    // ---  IMPLEMENTATION CONSTANTS
    //////////////////////////////////////////////////////

    /// @notice Convex Reward Token address.
    IERC20 public immutable CVX;

    /// @notice Convex Booster address.
    address public immutable BOOSTER;

    /// @notice Thrown when the reward receiver is not set in the protocol controller.
    error RewardReceiverNotSet();

    //////////////////////////////////////////////////////
    // --- ISIDECAR CLONE IMMUTABLES
    //////////////////////////////////////////////////////

    /// @notice Staking token address.
    function asset() public view override returns (IERC20 _asset) {
        return IERC20(address(this).readAddress(0));
    }

    /// @notice Curve gauge associated with the sidecar.
    function gauge() public view returns (address _gauge) {
        return address(this).readAddress(20);
    }

    function rewardReceiver() public view override returns (address _rewardReceiver) {
        _rewardReceiver = PROTOCOL_CONTROLLER.rewardReceiver(gauge());
        if (_rewardReceiver == address(0)) revert RewardReceiverNotSet();
    }

    //////////////////////////////////////////////////////
    // --- CONVEX CLONE IMMUTABLES
    //////////////////////////////////////////////////////

    /// @notice Staking Convex LP contract address.
    function baseRewardPool() public view returns (IBaseRewardPool _baseRewardPool) {
        return IBaseRewardPool(address(this).readAddress(40));
    }

    /// @notice Identifier of the pool on Convex.
    function pid() public view returns (uint256 _pid) {
        return address(this).readUint256(60);
    }

    //////////////////////////////////////////////////////
    // --- CONSTRUCTOR
    //////////////////////////////////////////////////////

    constructor(address _accountant, address _protocolController, address _cvx, address _booster)
        Sidecar(CURVE_PROTOCOL_ID, _accountant, _protocolController)
    {
        CVX = IERC20(_cvx);
        BOOSTER = _booster;
    }

    //////////////////////////////////////////////////////
    // --- INITIALIZATION
    //////////////////////////////////////////////////////

    /// @notice Initialize the contract by approving the ConvexCurve booster to spend the LP token.
    function _initialize() internal override {
        require(asset().allowance(address(this), address(BOOSTER)) == 0, AlreadyInitialized());

        asset().forceApprove(address(BOOSTER), type(uint256).max);
    }

    //////////////////////////////////////////////////////
    // --- ISIDECAR OPERATIONS OVERRIDE
    //////////////////////////////////////////////////////

    /// @notice Deposit LP token into Convex.
    /// @param amount Amount of LP token to deposit.
    /// @dev The reason there's an empty address parameter is to keep flexibility for future implementations.
    /// Not all fallbacks will be minimal proxies, so we need to keep the same function signature.
    /// Only callable by the strategy.
    function _deposit(uint256 amount) internal override {
        /// Deposit the LP token into Convex and stake it (true) to receive rewards.
        IBooster(BOOSTER).deposit(pid(), amount, true);
    }

    /// @notice Withdraw LP token from Convex.
    /// @param amount Amount of LP token to withdraw.
    /// @param receiver Address to receive the LP token.
    function _withdraw(uint256 amount, address receiver) internal override {
        /// Withdraw from Convex gauge without claiming rewards (false).
        baseRewardPool().withdrawAndUnwrap(amount, false);

        /// Send the LP token to the receiver.
        asset().safeTransfer(receiver, amount);
    }

    /// @notice Claim rewards from Convex.
    /// @return rewardTokenAmount Amount of reward token claimed.
    function _claim() internal override returns (uint256 rewardTokenAmount) {
        /// Claim rewardToken.
        baseRewardPool().getReward(address(this), false);

        rewardTokenAmount = REWARD_TOKEN.balanceOf(address(this));

        if (rewardTokenAmount > 0) {
            /// Send the reward token to the accountant.
            REWARD_TOKEN.safeTransfer(ACCOUNTANT, rewardTokenAmount);
        }
    }

    /// @notice Get the balance of the LP token on Convex held by this contract.
    function balanceOf() public view override returns (uint256) {
        return baseRewardPool().balanceOf(address(this));
    }

    /// @notice Get the reward tokens from the base reward pool.
    /// @return Array of all extra reward tokens.
    function getRewardTokens() public view override returns (address[] memory) {
        // Check if there is extra rewards
        uint256 extraRewardsLength = baseRewardPool().extraRewardsLength();

        address[] memory tokens = new address[](extraRewardsLength);

        address _token;
        for (uint256 i; i < extraRewardsLength;) {
            /// Get the address of the virtual balance pool.
            _token = baseRewardPool().extraRewards(i);

            tokens[i] = IBaseRewardPool(_token).rewardToken();

            /// For PIDs greater than 150, the virtual balance pool also has a wrapper.
            /// So we need to get the token from the wrapper.
            /// Try catch because pid 151 case is only on Mainnet, not on L2s.
            /// More: https://docs.convexfinance.com/convexfinanceintegration/baserewardpool
            try IStashTokenWrapper(tokens[i]).token() returns (address _t) {
                tokens[i] = _t;
            } catch {}

            unchecked {
                ++i;
            }
        }

        return tokens;
    }

    /// @notice Get the amount of reward token earned by the strategy.
    /// @return The amount of reward token earned by the strategy.
    function getPendingRewards() public view override returns (uint256) {
        return baseRewardPool().earned(address(this)) + REWARD_TOKEN.balanceOf(address(this));
    }

    //////////////////////////////////////////////////////
    // --- EXTRA CONVEX OPERATIONS
    //////////////////////////////////////////////////////

    function claimExtraRewards() external {
        address[] memory extraRewardTokens = getRewardTokens();

        /// It'll claim rewardToken but we'll leave it here for clarity until the claim() function is called by the strategy.
        baseRewardPool().getReward(address(this), true);

        /// Send the reward token to the reward receiver.
        address receiver = rewardReceiver();
        uint256 balance = CVX.balanceOf(address(this));
        if (balance > 0) {
            CVX.safeTransfer(receiver, balance);
        }

        /// Handle the extra reward tokens.
        for (uint256 i = 0; i < extraRewardTokens.length;) {
            uint256 _balance = IERC20(extraRewardTokens[i]).balanceOf(address(this));
            if (_balance > 0) {
                /// Send the whole balance to the reward receiver.
                IERC20(extraRewardTokens[i]).safeTransfer(receiver, _balance);
            }

            unchecked {
                ++i;
            }
        }
    }
}
OnlyBoostAllocator.sol 262 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Allocator} from "src/Allocator.sol";
import {IBalanceProvider} from "src/interfaces/IBalanceProvider.sol";
import {ISidecar} from "src/interfaces/ISidecar.sol";
import {IConvexSidecarFactory} from "src/interfaces/IConvexSidecarFactory.sol";


/// @title OnlyBoostAllocator.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Calculates the optimal LP token allocation for Stake DAO Locker and Convex.
contract OnlyBoostAllocator is Allocator {
    using Math for uint256;

    /// @notice Address of the Curve Boost Delegation V3 contract
    address public immutable BOOST_PROVIDER;

    /// @notice Address of the Convex Boost Holder contract
    address public immutable CONVEX_BOOST_HOLDER;

    /// @notice Address of the Convex Sidecar Factory contract
    IConvexSidecarFactory public immutable CONVEX_SIDECAR_FACTORY;

    /// @notice Gauges forced to allocate 100% to the locker (used during migrations).
    mapping(address => bool) public lockerOnly;

    /// @notice Emitted when the locker-only override is toggled for a gauge.
    event LockerOnlyUpdated(address indexed gauge, bool lockerOnly);

    /// @notice Initializes the OnlyBoostAllocator contract
    /// @param _locker Address of the Stake DAO Liquidity Locker
    /// @param _gateway Address of the gateway contract
    /// @param _convexSidecarFactory Address of the Convex Sidecar Factory contract
    constructor(
        address _locker,
        address _gateway,
        address _convexSidecarFactory,
        address _boostProvider,
        address _convexBoostHolder
    ) Allocator(_locker, _gateway) {
        BOOST_PROVIDER = _boostProvider;
        CONVEX_BOOST_HOLDER = _convexBoostHolder;
        CONVEX_SIDECAR_FACTORY = IConvexSidecarFactory(_convexSidecarFactory);
    }

    /// @notice Enables or disables sidecar allocations for a gauge.
    /// @dev Need to rebalance the allocator to update the allocation targets, else the deposit/withdrawal will fail.
    function setLockerOnly(address gauge, bool value) external onlyLocker {
        lockerOnly[gauge] = value;
        emit LockerOnlyUpdated(gauge, value);
    }

    //////////////////////////////////////////////////////
    // --- DEPOSIT ALLOCATION
    //////////////////////////////////////////////////////

    /// @inheritdoc Allocator
    function getDepositAllocation(address asset, address gauge, uint256 amount)
        public
        view
        override
        returns (Allocation memory alloc)
    {
        // 1. Resolve the sidecar for the gauge.
        address sidecar = CONVEX_SIDECAR_FACTORY.getSidecar(gauge);

        if (sidecar == address(0)) {
            return super.getDepositAllocation(asset, gauge, amount);
        }

        // 3. Prepare targets and amounts containers.
        alloc.asset = asset;
        alloc.gauge = gauge;
        alloc.targets = _targets(sidecar);
        alloc.amounts = _pair(0, 0);

        if (lockerOnly[gauge]) {
            alloc.amounts[1] = amount;
            return alloc;
        }

        // 4. Fetch current balances.
        uint256 balanceOfLocker = IBalanceProvider(gauge).balanceOf(LOCKER);

        // 5. Get the optimal balance based on Convex balance and veBoost ratio.
        uint256 optimalBalanceOfLocker = getOptimalLockerBalance(gauge);

        // 6. Calculate the amount of lps to deposit into the locker.
        alloc.amounts[1] =
            optimalBalanceOfLocker > balanceOfLocker ? Math.min(optimalBalanceOfLocker - balanceOfLocker, amount) : 0;

        // 7. Calculate the amount of lps to deposit into the sidecar.
        alloc.amounts[0] = amount - alloc.amounts[1];
    }

    //////////////////////////////////////////////////////
    // --- WITHDRAWAL ALLOCATION
    //////////////////////////////////////////////////////

    /// @inheritdoc Allocator
    function getWithdrawalAllocation(address asset, address gauge, uint256 amount)
        public
        view
        override
        returns (Allocation memory alloc)
    {
        // 1. Resolve the sidecar.
        address sidecar = CONVEX_SIDECAR_FACTORY.getSidecar(gauge);

        // 2. Fallback to base allocator if none.
        if (sidecar == address(0)) {
            return super.getWithdrawalAllocation(asset, gauge, amount);
        }

        // 3. Prepare return struct.
        alloc.asset = asset;
        alloc.gauge = gauge;
        alloc.targets = _targets(sidecar);
        alloc.amounts = _pair(0, 0);

        // 4. Current balances.
        uint256 balanceOfSidecar = ISidecar(sidecar).balanceOf();
        uint256 balanceOfLocker = IBalanceProvider(gauge).balanceOf(LOCKER);

        // 5. Calculate the optimal amount of lps that must be held by the locker.
        uint256 optimalBalanceOfLocker = getOptimalLockerBalance(gauge);

        // 6. Calculate the total balance.
        uint256 totalBalance = balanceOfSidecar + balanceOfLocker;

        if (lockerOnly[gauge]) {
            if (totalBalance <= amount) {
                alloc.amounts[0] = balanceOfSidecar;
                alloc.amounts[1] = balanceOfLocker;
            } else {
                alloc.amounts[0] = Math.min(amount, balanceOfSidecar);
                uint256 remaining = amount - alloc.amounts[0];
                alloc.amounts[1] = Math.min(remaining, balanceOfLocker);
            }
            return alloc;
        }

        // 7. Adjust the withdrawal based on the optimal amount for Stake DAO
        if (totalBalance <= amount) {
            // 7a. If the total balance is less than or equal to the withdrawal amount, withdraw everything
            alloc.amounts[0] = balanceOfSidecar;
            alloc.amounts[1] = balanceOfLocker;
        } else if (optimalBalanceOfLocker >= balanceOfLocker) {
            // 7b. If Stake DAO balance is below optimal, prioritize withdrawing from Convex
            alloc.amounts[0] = Math.min(amount, balanceOfSidecar);
            alloc.amounts[1] = amount > alloc.amounts[0] ? amount - alloc.amounts[0] : 0;
        } else {
            // 7c. If Stake DAO is above optimal, prioritize withdrawing from Stake DAO,
            //     but only withdraw as much as needed to bring the balance down to the optimal amount.
            alloc.amounts[1] = Math.min(amount, balanceOfLocker - optimalBalanceOfLocker);
            alloc.amounts[0] = amount > alloc.amounts[1] ? Math.min(amount - alloc.amounts[1], balanceOfSidecar) : 0;

            // 7d. If there is still more to withdraw, withdraw the rest from Stake DAO.
            if (amount > alloc.amounts[0] + alloc.amounts[1]) {
                alloc.amounts[1] += amount - alloc.amounts[0] - alloc.amounts[1];
            }
        }
    }

    //////////////////////////////////////////////////////
    // --- REBALANCE ALLOCATION
    //////////////////////////////////////////////////////

    /// @inheritdoc Allocator
    function getRebalancedAllocation(address asset, address gauge, uint256 totalBalance)
        public
        view
        override
        returns (Allocation memory alloc)
    {
        // 1. Resolve sidecar.
        address sidecar = CONVEX_SIDECAR_FACTORY.getSidecar(gauge);
        if (sidecar == address(0)) {
            return super.getRebalancedAllocation(asset, gauge, totalBalance);
        }


        // 2. Prepare struct.
        alloc.asset = asset;
        alloc.gauge = gauge;
        alloc.targets = _targets(sidecar);
        alloc.amounts = _pair(0, 0);


        if (lockerOnly[gauge]) {
            alloc.amounts[0] = 0;
            alloc.amounts[1] = totalBalance;
        }
        else {
            // 3. For rebalancing, we still want to match the optimal balance based on Convex holdings
            // This ensures we maintain the boost-maximizing ratio
            uint256 optimalLockerBalance = getOptimalLockerBalance(gauge);

            // Cap the locker amount to the total balance available
            alloc.amounts[1] = Math.min(optimalLockerBalance, totalBalance);
            alloc.amounts[0] = totalBalance - alloc.amounts[1];

        }
    }

    //////////////////////////////////////////////////////
    // --- VIEW HELPER FUNCTIONS
    //////////////////////////////////////////////////////

    /// @inheritdoc Allocator
    function getAllocationTargets(address gauge) public view override returns (address[] memory) {
        address sidecar = CONVEX_SIDECAR_FACTORY.getSidecar(gauge);
        if (sidecar == address(0)) {
            return super.getAllocationTargets(gauge);
        }

        return _targets(sidecar);
    }

    /// @notice Returns the optimal amount of LP token that must be held by Stake DAO Locker
    /// @dev Calculates the optimal balance to maximize boost efficiency
    /// @param gauge Address of the Curve gauge
    /// @return balanceOfLocker Optimal amount of LP token that should be held by Stake DAO Locker
    function getOptimalLockerBalance(address gauge) public view returns (uint256 balanceOfLocker) {
        // 1. Get the balance of veBoost on Stake DAO and Convex
        uint256 veBoostOfLocker = IBalanceProvider(BOOST_PROVIDER).balanceOf(LOCKER);
        uint256 veBoostOfConvex = IBalanceProvider(BOOST_PROVIDER).balanceOf(CONVEX_BOOST_HOLDER);

        // 2. Get the balance of the liquidity gauge on Convex
        uint256 balanceOfConvex = IBalanceProvider(gauge).balanceOf(CONVEX_BOOST_HOLDER);

        // 3. If there is no balance of Convex or no veBoost on Convex, return 0
        if (balanceOfConvex == 0 || veBoostOfConvex == 0) return 0;

        // 4. Compute the optimal balance for Stake DAO based on veBoost ratio
        // This ensures Stake DAO gets LP tokens proportional to its veBoost advantage
        balanceOfLocker = balanceOfConvex.mulDiv(veBoostOfLocker, veBoostOfConvex);
    }

    //////////////////////////////////////////////////////
    // --- HELPER FUNCTIONS
    //////////////////////////////////////////////////////

    /// @dev Returns the pair `[sidecar, LOCKER]` used by allocation targets.
    function _targets(address sidecar) private view returns (address[] memory arr) {
        arr = new address[](2);
        arr[0] = sidecar;
        arr[1] = LOCKER;
    }

    /// @dev Utility to allocate a two‑element uint256 array.
    function _pair(uint256 a0, uint256 a1) private pure returns (uint256[] memory arr) {
        arr = new uint256[](2);
        arr[0] = a0;
        arr[1] = a1;
    }
}
ConvexSidecarFactory.sol 108 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {SidecarFactory} from "src/SidecarFactory.sol";
import {IBooster} from "@interfaces/convex/IBooster.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ConvexSidecar} from "src/integrations/curve/ConvexSidecar.sol";

/// @title ConvexSidecarFactory.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Factory contract for deploying ConvexSidecar instances.
contract ConvexSidecarFactory is SidecarFactory {
    /// @notice The bytes4 ID of the Convex protocol
    /// @dev Used to identify the Convex protocol in the registry
    bytes4 private constant CURVE_PROTOCOL_ID = bytes4(keccak256("CURVE"));

    /// @notice Convex Booster contract address
    address public immutable BOOSTER;

    address public constant OLD_SIDECAR_FACTORY = 0x7Fa7fDb80b17f502C323D14Fa654a1e56B03C592;

    /// @notice Error emitted when the pool is shutdown
    error PoolShutdown();

    /// @notice Error emitted when the arguments are invalid
    error InvalidArguments();

    /// @notice Error emitted when the reward receiver is not set
    error VaultNotDeployed();

      /// @notice Constructor
    /// @param _implementation Address of the sidecar implementation
    /// @param _protocolController Address of the protocol controller
    /// @param _booster Address of the Convex Booster contract
    constructor(address _implementation, address _protocolController, address _booster)
        SidecarFactory(CURVE_PROTOCOL_ID, _implementation, _protocolController)
    {
        BOOSTER = _booster;
    }

    /// @notice Convenience function to create a sidecar with a uint256 pid parameter
    /// @param pid Pool ID in Convex
    /// @return sidecar Address of the created sidecar
    function create(address gauge, uint256 pid) external returns (address sidecar) {
        bytes memory args = abi.encode(pid);
        return create(gauge, args);
    }

    /// @notice Validates the gauge and arguments for Convex
    /// @param gauge The gauge to validate
    /// @param args The arguments containing the pool ID
    function _isValidGauge(address gauge, bytes memory args) internal view override {
        require(args.length == 32, InvalidArguments());

        uint256 pid = abi.decode(args, (uint256));

        // Get the pool info from Convex
        (,, address curveGauge,,, bool isShutdown) = IBooster(BOOSTER).poolInfo(pid);

        // Ensure the pool is not shutdown
        if (isShutdown) revert PoolShutdown();

        // Ensure the gauge matches
        if (curveGauge != gauge) revert InvalidGauge();
    }

    /// @notice Creates a ConvexSidecar for a gauge
    /// @param gauge The gauge to create a sidecar for
    /// @param args The arguments containing the pool ID
    /// @return sidecarAddress Address of the created sidecar
    function _create(address gauge, bytes memory args) internal override returns (address sidecarAddress) {
        uint256 pid = abi.decode(args, (uint256));

        // Get the LP token and base reward pool from Convex
        (address lpToken,,, address baseRewardPool,,) = IBooster(BOOSTER).poolInfo(pid);

        address rewardReceiver = PROTOCOL_CONTROLLER.rewardReceiver(gauge);
        require(rewardReceiver != address(0), VaultNotDeployed());

        // Encode the immutable arguments for the clone
        bytes memory data = abi.encodePacked(lpToken, gauge, baseRewardPool, pid);

        // Create a deterministic salt based on the token and gauge
        bytes32 salt = keccak256(data);

        // Clone the implementation contract
        sidecarAddress = Clones.cloneDeterministicWithImmutableArgs(IMPLEMENTATION, data, salt);

        // Initialize the sidecar
        ConvexSidecar(sidecarAddress).initialize();

        // Set the valid allocation target
        PROTOCOL_CONTROLLER.setValidAllocationTarget(gauge, sidecarAddress);

        return sidecarAddress;
    }

    function getSidecar(address gauge) public view returns (address _sidecar) {
        _sidecar = sidecar[gauge];

        if (_sidecar == address(0)) {
            _sidecar = ConvexSidecarFactory(OLD_SIDECAR_FACTORY).sidecar(gauge);
        }
    }
}
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
IAllocator.sol 26 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface IAllocator {
    struct Allocation {
        address asset;
        address gauge;
        address[] targets;
        uint256[] amounts;
    }

    function getDepositAllocation(address asset, address gauge, uint256 amount)
        external
        view
        returns (Allocation memory);
    function getWithdrawalAllocation(address asset, address gauge, uint256 amount)
        external
        view
        returns (Allocation memory);
    function getRebalancedAllocation(address asset, address gauge, uint256 amount)
        external
        view
        returns (Allocation memory);

    function getAllocationTargets(address gauge) external view returns (address[] memory);
}
SafeERC20.sol 198 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.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 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);
    }
}
IFactory.sol 9 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface IFactory {
    function createVault(address gauge) external returns (address vault, address rewardReceiver);
    function syncRewardTokens(address gauge) external;

    function REWARD_RECEIVER_IMPLEMENTATION() external view returns (address);
}
IBaseRewardPool.sol 13 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

interface IBaseRewardPool {
    function rewardToken() external view returns (address);
    function extraRewardsLength() external view returns (uint256);
    function extraRewards(uint256 index) external view returns (address);
    function withdrawAndUnwrap(uint256 amount, bool claim) external returns (bool);
    function getReward(address _account, bool _claimExtras) external returns (bool);
    function balanceOf(address _account) external view returns (uint256);
    function earned(address _account) external view returns (uint256);
    function rewardRate() external view returns (uint256);
}
IStashTokenWrapper.sol 6 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.19;

interface IStashTokenWrapper {
    function token() external view returns (address);
}
Sidecar.sol 169 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

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

import {ISidecar} from "src/interfaces/ISidecar.sol";
import {IAccountant} from "src/interfaces/IAccountant.sol";
import {IProtocolController} from "src/interfaces/IProtocolController.sol";

/// @title Sidecar.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Sidecar is an abstract base contract for protocol-specific yield sources that complement the main locker strategy.
///         It enables yield diversification beyond the main protocol locker (e.g., Convex alongside veCRV) and provides
///         a protocol-agnostic base that can be extended for any yield source. Sidecars are managed by the Strategy
///         for unified deposit/withdraw/harvest operations, with rewards flowing through the Accountant for consistent distribution.
abstract contract Sidecar is ISidecar {
    using SafeERC20 for IERC20;

    //////////////////////////////////////////////////////
    // --- IMMUTABLES
    //////////////////////////////////////////////////////

    /// @notice Protocol identifier matching the Strategy that manages this sidecar
    bytes4 public immutable PROTOCOL_ID;

    /// @notice Accountant that receives and distributes rewards from this sidecar
    address public immutable ACCOUNTANT;

    /// @notice Main protocol reward token claimed by this sidecar (e.g., CRV)
    IERC20 public immutable REWARD_TOKEN;

    /// @notice Registry used to verify the authorized strategy for this protocol
    IProtocolController public immutable PROTOCOL_CONTROLLER;

    //////////////////////////////////////////////////////
    // --- STORAGE
    //////////////////////////////////////////////////////

    /// @notice Prevents double initialization in factory deployment pattern
    bool private _initialized;

    //////////////////////////////////////////////////////
    // --- ERRORS
    //////////////////////////////////////////////////////

    error ZeroAddress();

    error OnlyStrategy();

    error OnlyAccountant();

    error AlreadyInitialized();

    error NotInitialized();

    error InvalidProtocolId();

    //////////////////////////////////////////////////////
    // --- MODIFIERS
    //////////////////////////////////////////////////////

    /// @notice Restricts access to the authorized strategy for this protocol
    /// @dev Prevents unauthorized manipulation of user funds
    modifier onlyStrategy() {
        require(PROTOCOL_CONTROLLER.strategy(PROTOCOL_ID) == msg.sender, OnlyStrategy());
        _;
    }

    //////////////////////////////////////////////////////
    // --- CONSTRUCTOR
    //////////////////////////////////////////////////////

    /// @notice Sets up immutable protocol connections
    /// @dev Called by factory during deployment. Reward token fetched from accountant
    /// @param _protocolId Protocol identifier for strategy verification
    /// @param _accountant Where to send claimed rewards for distribution
    /// @param _protocolController Registry for strategy lookup and validation
    constructor(bytes4 _protocolId, address _accountant, address _protocolController) {
        require(_protocolId != bytes4(0), InvalidProtocolId());
        require(_accountant != address(0) && _protocolController != address(0), ZeroAddress());

        PROTOCOL_ID = _protocolId;
        ACCOUNTANT = _accountant;
        PROTOCOL_CONTROLLER = IProtocolController(_protocolController);
        REWARD_TOKEN = IERC20(IAccountant(_accountant).REWARD_TOKEN());

        _initialized = true;
    }

    //////////////////////////////////////////////////////
    // --- EXTERNAL FUNCTIONS
    //////////////////////////////////////////////////////

    /// @notice One-time setup for protocol-specific configuration
    /// @dev Factory pattern: minimal proxy clones need post-deployment init
    ///      Base constructor sets _initialized=true, clones must call this
    function initialize() external {
        if (_initialized) revert AlreadyInitialized();
        _initialized = true;
        _initialize();
    }

    /// @notice Stakes LP tokens into the protocol-specific yield source
    /// @dev Strategy transfers tokens here first, then calls deposit
    /// @param amount LP tokens to stake (must already be transferred)
    function deposit(uint256 amount) external onlyStrategy {
        _deposit(amount);
    }

    /// @notice Unstakes LP tokens and sends directly to receiver
    /// @dev Used during user withdrawals and emergency shutdowns
    /// @param amount LP tokens to unstake from yield source
    /// @param receiver Where to send the unstaked tokens (vault or user)
    function withdraw(uint256 amount, address receiver) external onlyStrategy {
        _withdraw(amount, receiver);
    }

    /// @notice Harvests rewards and transfers to accountant
    /// @dev Part of Strategy's harvest flow. Returns amount for accounting
    /// @return Amount of reward tokens sent to accountant
    function claim() external onlyStrategy returns (uint256) {
        return _claim();
    }

    //////////////////////////////////////////////////////
    // --- IMMUTABLES
    //////////////////////////////////////////////////////

    /// @notice LP token this sidecar manages (e.g., CRV/ETH LP)
    /// @dev Must match the asset used by the associated Strategy
    function asset() public view virtual returns (IERC20);

    /// @notice Where extra rewards (not main protocol rewards) should be sent
    /// @dev Typically the RewardVault for the gauge this sidecar supports
    function rewardReceiver() public view virtual returns (address);

    //////////////////////////////////////////////////////
    // --- INTERNAL VIRTUAL FUNCTIONS
    //////////////////////////////////////////////////////

    /// @dev Protocol-specific setup (approvals, staking contracts, etc.)
    function _initialize() internal virtual;

    /// @dev Stakes tokens in protocol-specific way (e.g., Convex deposit)
    /// @param amount Tokens to stake (already transferred to this contract)
    function _deposit(uint256 amount) internal virtual;

    /// @dev Claims all available rewards and transfers to accountant
    /// @return Total rewards claimed and transferred
    function _claim() internal virtual returns (uint256);

    /// @dev Unstakes from protocol and sends tokens to receiver
    /// @param amount Tokens to unstake
    /// @param receiver Destination for unstaked tokens
    function _withdraw(uint256 amount, address receiver) internal virtual;

    /// @notice Total LP tokens staked in this sidecar
    /// @dev Used by Strategy to calculate total assets across all sources
    /// @return Current staked balance
    function balanceOf() public view virtual returns (uint256);

    /// @notice Unclaimed rewards available for harvest
    /// @dev May perform view-only simulation or on-chain checkpoint
    /// @return Claimable reward token amount
    function getPendingRewards() public virtual returns (uint256);
}
ImmutableArgsParser.sol 28 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";

/// @title ImmutableArgsParser
/// @notice A library for reading immutable arguments from a clone.
library ImmutableArgsParser {
    /// @dev Safely read an `address` from `clone`'s immutable args at `offset`.
    function readAddress(address clone, uint256 offset) internal view returns (address result) {
        bytes memory args = Clones.fetchCloneArgs(clone);
        assembly {
            // Load 32 bytes starting at `args + offset + 32`. Then shift right
            // by 96 bits (12 bytes) so that the address is right‐aligned and
            // the high bits are cleared.
            result := shr(96, mload(add(add(args, 0x20), offset)))
        }
    }

    /// @dev Safely read a `uint256` from `clone`'s immutable args at `offset`.
    function readUint256(address clone, uint256 offset) internal view returns (uint256 result) {
        bytes memory args = Clones.fetchCloneArgs(clone);
        assembly {
            // Load the entire 32‐byte word directly.
            result := mload(add(add(args, 0x20), offset))
        }
    }
}
Math.sol 685 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

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

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

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        uint256 mLen = m.length;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            result += SafeCast.toUint(value > 1);
        }
        return result;
    }

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

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

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

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

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

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

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

            result += SafeCast.toUint(value > (1 << 8) - 1);
        }
        return result;
    }

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

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
Allocator.sol 119 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {IAllocator} from "src/interfaces/IAllocator.sol";

/// @title Allocator.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice Allocator determines where to deploy capital for optimal yield generation.
///         The base implementation sends everything to the locker, while protocol-specific allocators
///         (e.g., OnlyBoostAllocator) can override to split funds between locker and sidecars
///         based on yield optimization strategies.
contract Allocator is IAllocator {
    /// @notice The locker that holds and stakes protocol tokens (e.g., veCRV holder)
    address public immutable LOCKER;

    /// @notice Safe multisig that executes transactions (same as locker on L2s)
    address public immutable GATEWAY;

    /// @notice Error thrown when the gateway is zero address
    error GatewayZeroAddress();

    /// @notice Error thrown when the caller is not the locker
    error OnlyLocker();

    /// @notice Modifier to restrict functions to the gateway
    modifier onlyLocker() {
        require(msg.sender == LOCKER, OnlyLocker());
        _;
    }

    /// @notice Initializes the allocator with locker and gateway addresses
    /// @param _locker Protocol's token holder (pass 0 for L2s where gateway holds tokens)
    /// @param _gateway Safe multisig that executes transactions
    constructor(address _locker, address _gateway) {
        require(_gateway != address(0), GatewayZeroAddress());

        GATEWAY = _gateway;
        // L2 optimization: gateway acts as both executor and token holder
        // @dev Security: ensures LOCKER is never zero, critical for fund routing
        LOCKER = _locker == address(0) ? _gateway : _locker;
    }

    /// @notice Calculates where to send deposited LP tokens
    /// @dev Base: 100% to locker. Override for complex strategies (e.g., split with Convex)
    /// @param asset LP token being deposited
    /// @param gauge Target gauge for staking
    /// @param amount Total amount to allocate
    /// @return Allocation with single target (locker) and full amount
    function getDepositAllocation(address asset, address gauge, uint256 amount)
        public
        view
        virtual
        returns (Allocation memory)
    {
        address[] memory targets = new address[](1);
        targets[0] = LOCKER;

        uint256[] memory amounts = new uint256[](1);
        amounts[0] = amount;

        return Allocation({asset: asset, gauge: gauge, targets: targets, amounts: amounts});
    }

    /// @notice Calculates where to pull LP tokens from during withdrawal
    /// @dev Base: 100% from locker. Override to handle multiple sources
    /// @param asset LP token being withdrawn
    /// @param gauge Source gauge
    /// @param amount Total amount to withdraw
    /// @return Allocation with single source (locker) and full amount
    function getWithdrawalAllocation(address asset, address gauge, uint256 amount)
        public
        view
        virtual
        returns (Allocation memory)
    {
        address[] memory targets = new address[](1);
        targets[0] = LOCKER;

        uint256[] memory amounts = new uint256[](1);
        amounts[0] = amount;

        return Allocation({asset: asset, gauge: gauge, targets: targets, amounts: amounts});
    }

    /// @notice Calculates optimal distribution when rebalancing positions
    /// @dev Base: same as deposit. Override to implement rebalancing logic
    /// @param asset LP token to rebalance
    /// @param gauge Target gauge
    /// @param amount Total amount to redistribute
    /// @return Allocation with rebalancing targets and amounts
    function getRebalancedAllocation(address asset, address gauge, uint256 amount)
        public
        view
        virtual
        returns (Allocation memory)
    {
        return getDepositAllocation(asset, gauge, amount);
    }

    /// @notice Lists all possible allocation targets for a gauge
    /// @dev Base: only locker. Override to include sidecars
    /// @return targets Array of addresses that can receive allocations
    function getAllocationTargets(
        address /*gauge*/
    )
        public
        view
        virtual
        returns (address[] memory)
    {
        address[] memory targets = new address[](1);
        targets[0] = LOCKER;

        return targets;
    }
}
IBalanceProvider.sol 7 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface IBalanceProvider {
    function balanceOf(address _address) external view returns (uint256);
    function totalSupply() external view returns (uint256);
}
ISidecar.sol 16 lines
/// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

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

interface ISidecar {
    function balanceOf() external view returns (uint256);
    function deposit(uint256 amount) external;
    function withdraw(uint256 amount, address receiver) external;
    function getPendingRewards() external returns (uint256);
    function getRewardTokens() external view returns (address[] memory);

    function claim() external returns (uint256);

    function asset() external view returns (IERC20);
}
IConvexSidecarFactory.sol 8 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

interface IConvexSidecarFactory {
    function getSidecar(address gauge) external view returns (address);
}


SidecarFactory.sol 93 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;

import {ISidecarFactory} from "src/interfaces/ISidecarFactory.sol";
import {IProtocolController} from "src/interfaces/IProtocolController.sol";

/// @title SidecarFactory.
/// @author Stake DAO
/// @custom:github @stake-dao
/// @custom:contact [email protected]

/// @notice SidecarFactory is an abstract base factory contract for deploying protocol-specific sidecar instances.
///         It creates deterministic minimal proxies for sidecar implementations, enabling efficient deployment
///         of multiple sidecars with minimal gas costs.
abstract contract SidecarFactory is ISidecarFactory {
    /// @notice The protocol ID
    bytes4 public immutable PROTOCOL_ID;

    /// @notice The protocol controller address
    IProtocolController public immutable PROTOCOL_CONTROLLER;

    /// @notice The implementation address
    address public immutable IMPLEMENTATION;

    /// @notice Mapping of gauges to sidecars
    mapping(address => address) public sidecar;

    /// @notice Error emitted when the gauge is invalid
    error InvalidGauge();

    /// @notice Error emitted when the token is invalid
    error InvalidToken();

    /// @notice Error emitted when a zero address is provided
    error ZeroAddress();

    /// @notice Error emitted when a protocol ID is zero
    error InvalidProtocolId();

    /// @notice Error emitted when the sidecar is already deployed
    error SidecarAlreadyDeployed();

    /// @notice Event emitted when a new sidecar is created
    /// @param gauge Address of the gauge
    /// @param sidecar Address of the created sidecar
    /// @param args Additional arguments used for creation
    event SidecarCreated(address indexed gauge, address indexed sidecar, bytes args);

    /// @notice Constructor
    /// @param _implementation Address of the sidecar implementation
    /// @param _protocolController Address of the protocol controller
    /// @param _protocolId Protocol ID
    constructor(bytes4 _protocolId, address _implementation, address _protocolController) {
        require(_implementation != address(0) && _protocolController != address(0), ZeroAddress());
        require(_protocolId != bytes4(0), InvalidProtocolId());

        PROTOCOL_ID = _protocolId;
        IMPLEMENTATION = _implementation;
        PROTOCOL_CONTROLLER = IProtocolController(_protocolController);
    }

    /// @notice Create a new sidecar for a gauge
    /// @param gauge Gauge address
    /// @param args Encoded arguments for sidecar creation
    /// @return sidecarAddress Address of the created sidecar
    function create(address gauge, bytes memory args) public virtual override returns (address sidecarAddress) {
        require(sidecar[gauge] == address(0), SidecarAlreadyDeployed());

        // Validate the gauge and args
        _isValidGauge(gauge, args);

        // Create the sidecar
        sidecarAddress = _create(gauge, args);

        // Store the sidecar address
        sidecar[gauge] = sidecarAddress;

        emit SidecarCreated(gauge, sidecarAddress, args);
    }

    /// @notice Validates the gauge and arguments
    /// @dev Must be implemented by derived factories to handle protocol-specific validation
    /// @param gauge The gauge to validate
    /// @param args The arguments to validate
    function _isValidGauge(address gauge, bytes memory args) internal virtual;

    /// @notice Creates a sidecar for a gauge
    /// @dev Must be implemented by derived factories to handle protocol-specific sidecar creation
    /// @param gauge The gauge to create a sidecar for
    /// @param args The arguments for sidecar creation
    /// @return sidecarAddress Address of the created sidecar
    function _create(address gauge, bytes memory args) internal virtual returns (address sidecarAddress);
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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);
}
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

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

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

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

Read Contract

ACCOUNTANT 0x8b9d2940 → address
BOOSTER 0x75b0ffd1 → address
CONVEX_SIDECAR_FACTORY 0xec1100c2 → address
CVX 0x759cb53b → address
GATEWAY 0x338c5371 → address
GAUGE_CONTROLLER 0x22884e2c → address
LOCKER 0x08ecd9a6 → address
OLD_STRATEGY 0xb0020ee7 → address
PROTOCOL_CONTROLLER 0x7aaf53e6 → address
PROTOCOL_ID 0x0db41f31 → bytes4
REGISTRAR 0xcb609077 → address
REWARD_RECEIVER_IMPLEMENTATION 0xe14e3878 → address
REWARD_RECEIVER_MIGRATION_MODULE 0x4a7d5de5 → address
REWARD_ROUTER 0x32f6cfba → address
REWARD_TOKEN 0x99248ea7 → address
REWARD_VAULT_IMPLEMENTATION 0x4a7500a6 → address

Write Contract 3 functions

These functions modify contract state and require a wallet transaction to execute.

create 0x780900dc
uint256 _pid
returns: address, address, address
createVault 0xb4bd6f46
address gauge
returns: address, address
syncRewardTokens 0x3bc9a431
address gauge

Recent Transactions

No transactions found for this address