Skip to content
Verified contractExactMIT

StrategyBoostHubChildV42

Address0x25d00f49ce4fe090136be666f7d2f741977fc8b5
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,432,182
Creation transaction
0x6694d843d1…8775752a27

contracts/StrategyBoostHubChildV42.sol

// SPDX-License-Identifier: MIT
/**
 * @title CurveYield System Component
 * @notice CurveYield is a decentralized NGO building optimized DeFi systems for the good of all.
 *
 * @dev CurveYield integrates specialized AMM infrastructure, tokenized yield strategies, credit
 * markets, and protocol-owned liquidity into a unified, capital-efficient liquidity stack governed
 * by an open, international DAO community.
 *
 * Protocol operations are enhanced by cross-chain bridging and messaging, MEV capture systems,
 * off-chain to on-chain automation, and peer-to-peer data networks.
 *
 * This contract is one component of the CurveYield system.
 *
 * CurveYield uses proven DeFi primitives where possible and adds targeted coordination and
 * capital-efficiency-enhancing contracts where needed. Users and integrators must review
 * CurveYield documentation before use.
 *
 * Learn more:
 * dApp: https://curveyield.com & https://curveyield.org
 *
 * Decentralized links may have limited or delayed availability during periods of high network activity:
 * https://curveyield.eth.limo
 * https://curveyield.dao
 *
 * Note: curveyield.dao may require a Brave Browser or an Unstoppable Domains browser plugin to use.
 */
pragma solidity ^0.8.20;

import "./StrategyConvexBoostHubStakingV5.sol";
import "./ChildAPR15dV42.sol";

/// @notice The unchanged BoostHub staking adapter with independent 15-day APR observations.
contract StrategyBoostHubChildV42 is StrategyConvexBoostHubStakingV5, ChildAPR15dV42 {
    constructor(
        address staking,
        Addresses memory addresses_,
        FeeSettings memory fees,
        uint256 lockDuration,
        uint256 minWantOutput
    ) StrategyConvexBoostHubStakingV5(staking, addresses_, fees, lockDuration, minWantOutput) {}

    function _aprAssetBalance() internal view override returns (uint256) { return balanceOf(); }
    function _afterAllocationDeposit(uint256 amount, uint256 beforeValue)
        internal override(BaseAllToWantBoostHubV5, ChildAPR15dV42)
    { ChildAPR15dV42._afterAllocationDeposit(amount, beforeValue); }
    function _afterAllocationWithdraw(uint256 amount, uint256 beforeValue)
        internal override(BaseAllToWantBoostHubV5, ChildAPR15dV42)
    { ChildAPR15dV42._afterAllocationWithdraw(amount, beforeValue); }
    function _afterHarvest() internal override(BaseAllToWantBoostHubV5, ChildAPR15dV42) {
        ChildAPR15dV42._afterHarvest();
    }
}

contracts/BaseAllToWantBoostHubV5.sol

// SPDX-License-Identifier: MIT
/**
 * @title CurveYield System Component
 * @notice CurveYield is a decentralized NGO building optimized DeFi systems for the good of all.
 *
 * @dev CurveYield integrates specialized AMM infrastructure, tokenized yield strategies, credit
 * markets, and protocol-owned liquidity into a unified, capital-efficient liquidity stack governed
 * by an open, international DAO community.
 *
 * Protocol operations are enhanced by cross-chain bridging and messaging, MEV capture systems,
 * off-chain to on-chain automation, and peer-to-peer data networks.
 *
 * This contract is one component of the CurveYield system.
 *
 * CurveYield uses proven DeFi primitives where possible and adds targeted coordination and
 * capital-efficiency-enhancing contracts where needed. Users and integrators must review
 * CurveYield documentation before use.
 *
 * Learn more:
 * dApp: https://curveyield.com & https://curveyield.org
 *
 * Decentralized links may have limited or delayed availability during periods of high network activity:
 * https://curveyield.eth.limo
 * https://curveyield.dao
 *
 * Note: curveyield.dao may require a Brave Browser or an Unstoppable Domains browser plugin to use.
 */
pragma solidity ^0.8.20;

// Surgical adaptation of Beefy's BaseAllToNativeFactoryStrat.sol (master).
// Original blob SHA: ffb79bd828a66c12fb2765298ce9241b9f917378
// v5: Direct reward-token -> want conversion, with performance fees only in want.
// One constructor-frozen minimum net want output applies to all non-want rewards.
// Fees are never charged on pre-existing idle underlying principal.
// Rewards are supplied automatically by the BoostHubStaking adapter.
import "@openzeppelin-4/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/IBeefySwapperV2.sol";

abstract contract BaseAllToWantBoostHubV5 {
    using SafeERC20 for IERC20;

    address public immutable vault;
    address public immutable swapper;
    address public immutable want;
    address public immutable adminFeeReceiverAddress;
    uint16 public immutable totalPerformanceFeeBps;
    uint16 public immutable callShareBps;
    uint16 public immutable adminShareBps;

    uint256 public lastHarvest;
    uint256 public totalLocked;
    uint256 public immutable lockDuration;
    uint256 public immutable minWantOutput; // In smallest underlying (want) token units
    bool public constant harvestOnDeposit = false;

    uint256 internal constant FEE_DENOMINATOR = 10_000;
    event StratHarvest(address indexed harvester, uint256 wantHarvested);
    event Deposit(uint256 amount);
    event Withdraw(uint256 amount);
    event ChargedFees(address indexed token, uint256 callFees, uint256 adminFees);
    event RewardSwapDeferred(address indexed token, uint256 amount);
    event RewardOutputBelowMinimum(address indexed token, uint256 expectedWantOutput, uint256 minimumWantOutput);

    struct Addresses {
        address want;
        address vault;
        address swapper;
        address adminFeeReceiver;
    }

    struct FeeSettings {
        uint16 totalPerformanceFeeBps;
        uint16 callShareBps;
        uint16 adminShareBps;
    }

    constructor(
        Addresses memory _a,
        FeeSettings memory _fees,
        uint256 _lockDuration,
        uint256 _minWantOutput
    ) {
        require(_a.want != address(0) && _a.vault != address(0) && _a.swapper != address(0), "Missing address");
        require(_a.adminFeeReceiver != address(0), "Missing admin fee receiver");
        require(_fees.totalPerformanceFeeBps <= FEE_DENOMINATOR, "Invalid performance fee");
        require(uint256(_fees.callShareBps) + _fees.adminShareBps == FEE_DENOMINATOR, "Invalid fee shares");
        want = _a.want;
        vault = _a.vault;
        swapper = _a.swapper;
        adminFeeReceiverAddress = _a.adminFeeReceiver;
        totalPerformanceFeeBps = _fees.totalPerformanceFeeBps;
        callShareBps = _fees.callShareBps;
        adminShareBps = _fees.adminShareBps;
        lockDuration = _lockDuration;
        minWantOutput = _minWantOutput;
    }

    function stratName() public view virtual returns (string memory);
    function balanceOfPool() public view virtual returns (uint256);
    function _deposit(uint256 amount) internal virtual;
    function _withdraw(uint256 amount) internal virtual;
    function _claim() internal virtual returns (address[] memory);
    function _swappableRewards() internal view virtual returns (address[] memory);
    // Optional capital-flow neutral performance-index hooks for v42 child strategies.
    function _afterAllocationDeposit(uint256, uint256) internal virtual {}
    function _afterAllocationWithdraw(uint256, uint256) internal virtual {}
    function _afterHarvest() internal virtual {}

    function deposit() public {
        // Deposit only stakes want; reward discovery happens when harvesting.
        _depositAvailableWant(balanceOfWant());
    }

    function _depositAvailableWant(uint256 wantBal) internal {
        if (wantBal > 0) {
            uint256 totalBefore = balanceOf();
            uint256 assetsBefore = totalBefore > wantBal ? totalBefore - wantBal : 0;
            _deposit(wantBal);
            // ONLY fresh master allocations mint internal APR units.
            _afterAllocationDeposit(wantBal, assetsBefore);
            emit Deposit(wantBal);
        }
    }

    function _reinvestWant(uint256 amount) internal {
        // Compounded yield is retained profit, NOT a new principal allocation;
        // minting units here would artificially erase the children's APR.
        if (amount != 0) {
            _deposit(amount);
            emit Deposit(amount);
        }
    }

    function withdraw(uint256 _amount) external {
        require(msg.sender == vault, "!vault");
        uint256 assetsBefore = balanceOf();
        uint256 wantBal = balanceOfWant();
        if (wantBal < _amount) {
            _withdraw(_amount - wantBal);
            wantBal = balanceOfWant();
        }
        if (wantBal > _amount) wantBal = _amount;
        IERC20(want).safeTransfer(vault, wantBal);
        _afterAllocationWithdraw(wantBal, assetsBefore);
        emit Withdraw(wantBal);
    }

    function claim() external {
        // Claim-only profits must observe the same 72-hour locking policy as harvest.
        uint256 beforeBal = balanceOfWant();
        _claim();
        (uint256 fee, uint256 callerFee) = _wantFees(balanceOfWant() - beforeBal);
        _payWantFees(fee, callerFee, tx.origin);
        uint256 afterBal = balanceOfWant();
        if (afterBal > beforeBal) {
            totalLocked = afterBal - beforeBal + lockedProfit();
            lastHarvest = block.timestamp;
        }
        _afterHarvest();
    }

    function harvest() external {
        _harvest(tx.origin);
    }

    function harvest(address callFeeRecipient) external {
        _harvest(callFeeRecipient);
    }

    function _harvest(address callFeeRecipient) internal {
        require(callFeeRecipient != address(0), "Invalid caller reward recipient");
        uint256 beforeBal = balanceOfWant();
        address[] memory tokens = _claim();
        uint256 wantBal = balanceOfWant();
        // Charge only want *newly received* during staking claims, not idle principal.
        (uint256 fee, uint256 callerFee) = _wantFees(wantBal - beforeBal);
        (uint256 swapFees, uint256 swapCallerFees) = _swapRewardsToWant(tokens, wantBal);
        _payWantFees(fee + swapFees, callerFee + swapCallerFees, callFeeRecipient);

        uint256 afterBal = balanceOfWant();
        if (afterBal > beforeBal) {
            uint256 wantHarvested = afterBal - beforeBal;
            totalLocked = wantHarvested + lockedProfit();
            lastHarvest = block.timestamp;
            _reinvestWant(afterBal);
            emit StratHarvest(msg.sender, wantHarvested);
        }
        _afterHarvest();
    }

    function _swapRewardsToWant(address[] memory swappableRewards, uint256 wantBal)
        internal returns (uint256 fees, uint256 callerFees)
    {
        for (uint256 i; i < swappableRewards.length; ++i) {
            address token = swappableRewards[i];
            // Never convert want: its balance may include users' deposited principal.
            if (token == want) continue;
            uint256 amount = IERC20(token).balanceOf(address(this));
            if (amount == 0) continue;

            // One global threshold in underlying-token base units, using the
            // OmniRouter's direct token -> want quote net of expected fees.
            if (minWantOutput != 0) {
                uint256 quotedWant = _quoteAmountOut(token, want, amount);
                uint256 quotedNetWant = quotedWant - quotedWant * totalPerformanceFeeBps / FEE_DENOMINATOR;
                if (quotedNetWant < minWantOutput) {
                    emit RewardOutputBelowMinimum(token, quotedNetWant, minWantOutput);
                    continue;
                }
            }

            _approveExact(token, swapper, amount);
            // Missing routes or reverting conversions are deferred individually.
            try IBeefySwapperV2(swapper).swap(token, want, amount) returns (uint256) {
                // Measure the real ERC-20 amount received, not the swapper's
                // potentially untrustworthy return value or the input amount.
                uint256 nextWantBal = balanceOfWant();
                uint256 receivedWant = nextWantBal - wantBal;
                wantBal = nextWantBal;
                require(receivedWant != 0, "Router returned no want");
                (uint256 fee, uint256 callerFee) = _wantFees(receivedWant);
                // As in v5, an unexpectedly low *actual* output reverts the
                // harvest atomically; a pre-swap quote is not a slippage limit.
                if (minWantOutput != 0) {
                    require(receivedWant - fee >= minWantOutput, "Want output below minimum");
                }
                // Preserve rounding per reward; transfer the sums only once.
                fees += fee;
                callerFees += callerFee;
            } catch {
                _approveExact(token, swapper, 0);
                emit RewardSwapDeferred(token, amount);
            }
        }
    }

    // Missing or reverting swapper quotes return zero and defer conversion
    // whenever the immutable minimum is nonzero.
    function _quoteAmountOut(address fromToken, address toToken, uint256 amount) internal view returns (uint256) {
        if (amount == 0) return 0;
        if (fromToken == toToken) return amount;
        try IBeefySwapperV2(swapper).getAmountOut(fromToken, toToken, amount) returns (uint256 quoted) {
            return quoted;
        } catch {
            return 0;
        }
    }

    function _wantFees(uint256 grossWant) internal view returns (uint256 fee, uint256 callerFee) {
        fee = grossWant * totalPerformanceFeeBps / FEE_DENOMINATOR;
        callerFee = fee * callShareBps / FEE_DENOMINATOR;
    }

    function _payWantFees(uint256 fee, uint256 callFeeAmount, address callFeeRecipient) internal {
        uint256 adminFeeAmount = fee - callFeeAmount;
        if (callFeeAmount > 0) IERC20(want).safeTransfer(callFeeRecipient, callFeeAmount);
        if (adminFeeAmount > 0) IERC20(want).safeTransfer(adminFeeReceiverAddress, adminFeeAmount);
        if (fee > 0) emit ChargedFees(want, callFeeAmount, adminFeeAmount);
    }

    function _approveExact(address token, address spender, uint256 amount) internal {
        // Supports exact router approvals and the fixed staking allowance at deployment.
        IERC20(token).forceApprove(spender, amount);
    }

    function rewards(uint256 index) external view returns (address) { return _swappableRewards()[index]; }
    function rewardsLength() external view returns (uint256) { return _swappableRewards().length; }

    /// @notice Add retained vault withdrawal fees to the existing time-based profit unlock.
    /// @dev The vault transfers the exact amount of want to this strategy first.
    function lockVaultProfit(uint256 amount) external {
        require(msg.sender == vault, "!vault");
        totalLocked = lockedProfit() + amount;
        lastHarvest = block.timestamp;
    }

    function lockedProfit() public view returns (uint256) {
        if (lockDuration == 0) return 0;
        uint256 elapsed = block.timestamp - lastHarvest;
        uint256 remaining = elapsed < lockDuration ? lockDuration - elapsed : 0;
        return totalLocked * remaining / lockDuration;
    }

    function balanceOf() public view returns (uint256) {
        return balanceOfWant() + balanceOfPool() - lockedProfit();
    }

    function balanceOfWant() public view returns (uint256) {
        return IERC20(want).balanceOf(address(this));
    }

    function rewardsAvailable() external pure returns (uint256) { return 0; }
    function callReward() external pure returns (uint256) { return 0; }
    function depositFee() external pure returns (uint256) { return 0; }
    function withdrawFee() external pure returns (uint256) { return 0; }
}

contracts/ChildAPR15dV42.sol

// SPDX-License-Identifier: MIT
/**
 * @title CurveYield System Component
 * @notice CurveYield is a decentralized NGO building optimized DeFi systems for the good of all.
 *
 * @dev CurveYield integrates specialized AMM infrastructure, tokenized yield strategies, credit
 * markets, and protocol-owned liquidity into a unified, capital-efficient liquidity stack governed
 * by an open, international DAO community.
 *
 * Protocol operations are enhanced by cross-chain bridging and messaging, MEV capture systems,
 * off-chain to on-chain automation, and peer-to-peer data networks.
 *
 * This contract is one component of the CurveYield system.
 *
 * CurveYield uses proven DeFi primitives where possible and adds targeted coordination and
 * capital-efficiency-enhancing contracts where needed. Users and integrators must review
 * CurveYield documentation before use.
 *
 * Learn more:
 * dApp: https://curveyield.com & https://curveyield.org
 *
 * Decentralized links may have limited or delayed availability during periods of high network activity:
 * https://curveyield.eth.limo
 * https://curveyield.dao
 *
 * Note: curveyield.dao may require a Brave Browser or an Unstoppable Domains browser plugin to use.
 */
pragma solidity ^0.8.20;

/// @notice Capital-flow-neutral 15-day PPS APR tracker for master-owned children.
/// @dev Mirrors the vault's 16 daily / 5 recent samples. Units are internal,
///      minted on allocation and burned on deallocation, never transferable.
abstract contract ChildAPR15dV42 {
    struct Sample { uint40 timestamp; uint216 pps; }
    Sample[16] private daily;
    Sample[5] private recent;
    uint8 private dailyCount;
    uint8 private recentCount;
    uint8 private dailyNext;
    uint8 private recentNext;
    uint40 public lastAPRCheckpoint;
    uint40 public lastDailyAPRCheckpoint;
    uint256 public aprUnits;
    uint256 public lastValidAPR;
    bool public hasValidAPR;

    uint256 private constant WAD = 1e18;
    uint256 private constant WINDOW = 15 days;
    uint256 private constant MAX_WINDOW = 30 days;

    function _aprAssetBalance() internal view virtual returns (uint256);

    function _afterAllocationDeposit(uint256 amount, uint256 valueBefore) internal virtual {
        if (amount == 0) return;
        uint256 units = aprUnits;
        // Round shares up: inflows may never falsely increase PPS.
        uint256 minted = units == 0 || valueBefore == 0 ? amount
            : (amount * units + valueBefore - 1) / valueBefore;
        aprUnits = units + minted;
        _snapshot();
    }

    function _afterAllocationWithdraw(uint256 amount, uint256 valueBefore) internal virtual {
        uint256 units = aprUnits;
        if (amount != 0 && units != 0) {
            uint256 burned = valueBefore == 0 ? units
                : (amount * units + valueBefore - 1) / valueBefore;
            aprUnits = burned >= units ? 0 : units - burned;
            // Empty positions should not preserve stale APR for comparisons.
            if (aprUnits == 0) hasValidAPR = false;
        }
        _snapshot();
    }

    function _afterHarvest() internal virtual { _snapshot(); }

    function checkpointAPR() external { _snapshot(); }

    function _pps() internal view returns (uint256) {
        uint256 units = aprUnits;
        if (units == 0) return 0;
        return _aprAssetBalance() * WAD / units;
    }

    function _snapshot() internal {
        if (block.timestamp < uint256(lastAPRCheckpoint) + 4 hours || aprUnits == 0) return;
        uint256 pps = _pps();
        if (pps == 0 || pps > type(uint216).max) return;
        Sample memory s = Sample(uint40(block.timestamp), uint216(pps));
        recent[recentNext] = s;
        recentNext = (recentNext + 1) % 5;
        if (recentCount < 5) ++recentCount;
        lastAPRCheckpoint = uint40(block.timestamp);
        if (block.timestamp >= uint256(lastDailyAPRCheckpoint) + 1 days) {
            daily[dailyNext] = s;
            dailyNext = (dailyNext + 1) % 16;
            if (dailyCount < 16) ++dailyCount;
            lastDailyAPRCheckpoint = uint40(block.timestamp);
        }
        (bool ready, uint256 value) = _compute(pps);
        if (ready) { hasValidAPR = true; lastValidAPR = value; }
    }

    function getAPR() external view returns (uint256) { (, uint256 value) = _read(); return value; }
    function aprReady() external view returns (bool) { (bool ready,) = _read(); return ready; }
    function rate() external view returns (uint256) { (, uint256 value) = _read(); return value / 365 days; }

    function _read() private view returns (bool, uint256) {
        uint256 pps = _pps();
        return pps == 0 ? (false, 0) : _compute(pps);
    }

    function _compute(uint256 nowPps) private view returns (bool, uint256) {
        uint256 target = block.timestamp > WINDOW ? block.timestamp - WINDOW : 0;
        uint256 closest = type(uint256).max;
        uint256 startPps;
        uint256 startTime;
        for (uint256 i; i < dailyCount; ++i) {
            Sample memory s = daily[i];
            if (s.timestamp == 0 || s.timestamp >= block.timestamp || block.timestamp - s.timestamp > MAX_WINDOW) continue;
            uint256 distance = s.timestamp > target ? s.timestamp - target : target - s.timestamp;
            if (distance < closest) { closest = distance; startPps = s.pps; startTime = s.timestamp; }
        }
        if (startPps == 0) {
            uint256 count;
            for (uint256 i; i < recentCount; ++i) {
                Sample memory s = recent[i];
                if (s.timestamp == 0 || s.timestamp >= block.timestamp || block.timestamp - s.timestamp > MAX_WINDOW) continue;
                ++count;
                if (startTime == 0 || s.timestamp < startTime) { startPps = s.pps; startTime = s.timestamp; }
            }
            if (hasValidAPR && count < 5) return (true, lastValidAPR);
        }
        if (startPps == 0) return (hasValidAPR, lastValidAPR);
        if (nowPps <= startPps) return (true, 0);
        // APR is deliberately unsigned like the original vault APR.
        uint256 gainWad = (nowPps - startPps) * WAD / startPps;
        return (true, gainWad * 365 days / (block.timestamp - startTime));
    }
}

contracts/StrategyConvexBoostHubStakingV5.sol

// SPDX-License-Identifier: MIT
/**
 * @title CurveYield System Component
 * @notice CurveYield is a decentralized NGO building optimized DeFi systems for the good of all.
 *
 * @dev CurveYield integrates specialized AMM infrastructure, tokenized yield strategies, credit
 * markets, and protocol-owned liquidity into a unified, capital-efficient liquidity stack governed
 * by an open, international DAO community.
 *
 * Protocol operations are enhanced by cross-chain bridging and messaging, MEV capture systems,
 * off-chain to on-chain automation, and peer-to-peer data networks.
 *
 * This contract is one component of the CurveYield system.
 *
 * CurveYield uses proven DeFi primitives where possible and adds targeted coordination and
 * capital-efficiency-enhancing contracts where needed. Users and integrators must review
 * CurveYield documentation before use.
 *
 * Learn more:
 * dApp: https://curveyield.com & https://curveyield.org
 *
 * Decentralized links may have limited or delayed availability during periods of high network activity:
 * https://curveyield.eth.limo
 * https://curveyield.dao
 *
 * Note: curveyield.dao may require a Brave Browser or an Unstoppable Domains browser plugin to use.
 */
pragma solidity ^0.8.20;

// Based on Beefy StrategyConvexStakingFraxtal.sol (blob 0560055143e89fb62869dcfb140adb75435bf303).
// Main replacements: exact BoostHubStaking Vyper ABI, dynamic rewards, no external strategy factory.
import "./BaseAllToWantBoostHubV5.sol";
import "./interfaces/IBoostHubStakingV1.sol";

contract StrategyConvexBoostHubStakingV5 is BaseAllToWantBoostHubV5 {
    IBoostHubStakingV1 public immutable staking;
    uint256 public constant MAX_STAKING_REWARDS = 9;

    constructor(
        address _staking,
        Addresses memory _addresses,
        FeeSettings memory _fees,
        uint256 _lockDuration,
        uint256 _minWantOutput
    ) BaseAllToWantBoostHubV5(_addresses, _fees, _lockDuration, _minWantOutput) {
        require(_staking != address(0) && _staking.code.length > 0, "Invalid staking");
        require(IBoostHubStakingV1(_staking).lp_token() == want, "Staking want mismatch");
        staking = IBoostHubStakingV1(_staking);
        _approveExact(want, _staking, type(uint256).max);
    }

    function stratName() public pure override returns (string memory) {
        return "ConvexBoostHubStaking";
    }

    function balanceOfPool() public view override returns (uint256) {
        return staking.balanceOf(address(this));
    }

    function _deposit(uint256 amount) internal override {
        // Vyper function selector is deposit(uint256,address), NOT stake/stakeFor.
        staking.deposit(amount, address(this));
    }

    function _withdraw(uint256 amount) internal override {
        if (amount > 0) staking.withdraw(amount);
    }


    function _claim() internal override returns (address[] memory) {
        return staking.harvest_and_claim();
    }

    /// @notice Current accepted reward tokens, read directly from staking (no stale stored list).
    /// Includes want; underlying-token rewards are charged directly without a swap.
    function acceptedRewardTokens() external view returns (address[] memory tokens) {
        uint256 count = staking.reward_count();
        require(count <= MAX_STAKING_REWARDS, "Excess staking rewards");
        address[] memory available = new address[](count);
        uint256 selected;
        for (uint256 i; i < count; ++i) {
            address token = staking.reward_tokens(i);
            if (token != address(0) && !staking.reward_disabled(token)) {
                available[selected++] = token;
            }
        }
        tokens = new address[](selected);
        for (uint256 i; i < selected; ++i) tokens[i] = available[i];
    }

    function _swappableRewards() internal view override returns (address[] memory swappableRewards) {
        uint256 count = staking.reward_count();
        require(count <= MAX_STAKING_REWARDS, "Excess staking rewards");
        address[MAX_STAKING_REWARDS] memory desired;
        uint256 desiredCount;
        for (uint256 i; i < count; ++i) {
            address token = staking.reward_tokens(i);
            if (token == address(0)) continue;
            // The swap loop checks balances once, including disabled-token leftovers.
            // Never swap want (it can be principal) or the staking address;
            // all other ERC-20 rewards, including wrapped native, swap directly to want.
            if (token == want || token == address(staking)) continue;
            desired[desiredCount++] = token;
        }
        swappableRewards = new address[](desiredCount);
        for (uint256 i; i < desiredCount; ++i) swappableRewards[i] = desired[i];
    }
}

contracts/interfaces/IBeefySwapperV2.sol

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

// Signature copied from Beefy's IBeefySwapper.sol; no factory interaction.
interface IBeefySwapperV2 {
    function swap(address fromToken, address toToken, uint256 amountIn) external returns (uint256 amountOut);
    function getAmountOut(address fromToken, address toToken, uint256 amountIn) external view returns (uint256 amountOut);
}

contracts/interfaces/IBoostHubStakingV1.sol

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

// Exact public/external function selectors of the attached BoostHubStaking.vy (Vyper 0.4.3).
interface IBoostHubStakingV1 {
    function lp_token() external view returns (address);
    function balanceOf(address account) external view returns (uint256);
    function deposit(uint256 value, address account) external;
    function withdraw(uint256 value) external;
    function harvest() external;
    function harvest_and_claim() external returns (address[] memory tokens);
    function claim_rewards() external;
    function reward_count() external view returns (uint256);
    function reward_tokens(uint256 index) external view returns (address);
    function reward_disabled(address reward) external view returns (bool);
}

dependencies/node_modules/@openzeppelin-4/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

dependencies/node_modules/@openzeppelin-4/contracts/token/ERC20/extensions/IERC20Permit.sol

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

pragma solidity ^0.8.0;

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

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

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

dependencies/node_modules/@openzeppelin-4/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

dependencies/node_modules/@openzeppelin-4/contracts/utils/Address.sol

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

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin-4/contracts/=dependencies/node_modules/@openzeppelin-4/contracts/",
    "@openzeppelin-5/contracts/=dependencies/node_modules/@openzeppelin-5/contracts/",
    "@openzeppelin/contracts-upgradeable/=dependencies/node_modules/@openzeppelin/contracts-upgradeable/",
    "@openzeppelin/contracts/=dependencies/node_modules/@openzeppelin/contracts/",
    "@uniswap/=dependencies/node_modules/@uniswap/",
    "ds-test/=dependencies/node_modules/@uniswap/v4-core/lib/solmate/lib/ds-test/",
    "erc4626-tests/=dependencies/node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=dependencies/node_modules/@uniswap/v4-core/lib/forge-std/",
    "openzeppelin-contracts/=dependencies/node_modules/@uniswap/v4-core/lib/openzeppelin-contracts/",
    "solmate/src/=dependencies/solmate/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.