Skip to content
Verified contractExactMIT

BlueFundVault

Address0xccb60e210e1448dff4e2a93ca54354db8f176ac2
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,322,602
Creation transaction
0xc5e5ef5b62…ab1dc5be71

src/BlueFundVault.sol

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

import {IERC20} from "./interfaces/IERC20.sol";
import {IEToken} from "./interfaces/IEToken.sol";
import {IPolicyPool} from "./interfaces/IPolicyPool.sol";

/// @title BlueFundVault
/// @notice Single-owner custody vault holding USDC and four Ensuro eTokens
///         (Spot Junior, Senior Tranche, Rentennials Junior, Cliff Horizon Junior).
///         A keeper calls `rebalance` with absolute USDC targets derived from
///         the paper-trade harness (`last_signal.json`).
///
/// Capital flow:
///   owner --fund--> vault --PolicyPool.deposit--> eTokens
///   eTokens --PolicyPool.withdraw--> vault USDC --withdrawCash--> owner
///
/// Withdrawals from Ensuro take whatever is liquid (SCR may block the rest);
/// `PolicyPool.withdraw` returns the actual amount and does not revert short.
///
/// Rate limits and shift caps are DIRECTIONAL: they constrain increases in
/// allocation only. Reductions (exits) execute immediately and uncapped so the
/// kill-switch can move from full allocation to the floor in a single call.
contract BlueFundVault {
    // -- Mainnet constants --
    IERC20 public constant USDC =
        IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);

    IPolicyPool public constant POLICY_POOL =
        IPolicyPool(0xd81A8B5bE59cEAE0f9E27455A998B4fDac9fA0a3);

    IEToken public constant SPOT =
        IEToken(0x12a4f34d27B1D54defD4Eb39799971E26D9025E7);

    IEToken public constant SENIOR =
        IEToken(0xa551285B49A29cBDBAE7fC5C6a61fadC918Ad224);

    IEToken public constant RENTENNIALS =
        IEToken(0xfA9888B740031FA16E635244A6A33A5851980b34);

    IEToken public constant CLIFF =
        IEToken(0xB375f428De1143bD08EB20151559a221744249c7);

    // -- Roles --
    address public owner;
    address public pendingOwner;
    address public keeper;

    // -- Pause --
    bool public paused;

    // -- Allocation caps (bps of NAV; 9500 = 95%) --
    // Set at 95% rather than 100% so the circuit breaker still exists: a buggy
    // signal engine cannot put the entire book into one sleeve, but the real
    // allocation (which can legitimately reach ~88% Senior) is not blocked.
    uint256 public constant BPS_DENOMINATOR = 10_000;
    uint256 public maxSpotBps;
    uint256 public maxSeniorBps;
    uint256 public maxRentBps;
    uint256 public maxCliffBps;

    /// @notice Max INCREASE per sleeve per rebalance, as bps of NAV (3000 = 30%).
    ///         Does not constrain reductions.
    uint256 public maxSleeveShiftBps;

    /// @notice Minimum seconds between keeper rebalances that INCREASE allocation.
    ///         Exits bypass this entirely.
    uint256 public minRebalanceInterval;
    uint256 public lastRebalanceAt;

    // -- Reentrancy lock --
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;
    uint256 private _status;

    // -- Events --
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferStarted(address indexed currentOwner, address indexed pendingOwner);
    event KeeperUpdated(address indexed previousKeeper, address indexed newKeeper);
    event Funded(address indexed from, uint256 amount);
    event CashWithdrawn(address indexed to, uint256 amount);
    event Rebalanced(
        uint256 spotTarget,
        uint256 seniorTarget,
        uint256 rentTarget,
        uint256 cliffTarget,
        uint256 idleAfter
    );
    event Deposited(IEToken indexed eToken, uint256 amount);
    event Withdrawn(IEToken indexed eToken, uint256 requested, uint256 actual);
    event TokenRescued(address indexed token, address indexed to, uint256 amount);
    event ETHRescued(address indexed to, uint256 amount);
    event MaxAllocationUpdated(
        uint256 maxSpotBps,
        uint256 maxSeniorBps,
        uint256 maxRentBps,
        uint256 maxCliffBps
    );
    event MaxSleeveShiftUpdated(uint256 maxSleeveShiftBps);
    event MinRebalanceIntervalUpdated(uint256 minRebalanceInterval);
    event PauseToggled(bool paused);

    // -- Errors --
    error NotOwner();
    error NotKeeper();
    error NotPendingOwner();
    error ZeroAddress();
    error OwnerKeeperSame();
    error TransferFailed();
    error TargetsExceedNav(uint256 targetsSum, uint256 nav);
    error ReentrantCall();
    error CannotRescueManagedToken(address token);
    error AllocationCapExceeded(address eToken, uint256 target, uint256 maxAllowed);
    error RebalanceShiftExceeded(address eToken, uint256 shift, uint256 maxAllowed);
    error RebalanceTooSoon(uint256 earliestAllowed);
    error InvalidAllocationBps(uint256 bps);
    error VaultPaused();
    error NotManagedToken(address token);

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyKeeper() {
        if (msg.sender != keeper) revert NotKeeper();
        _;
    }

    modifier nonReentrant() {
        if (_status == _ENTERED) revert ReentrantCall();
        _status = _ENTERED;
        _;
        _status = _NOT_ENTERED;
    }

    modifier whenNotPaused() {
        if (paused) revert VaultPaused();
        _;
    }

    constructor(address owner_, address keeper_) {
        if (owner_ == address(0) || keeper_ == address(0)) revert ZeroAddress();
        if (owner_ == keeper_) revert OwnerKeeperSame();
        owner = owner_;
        keeper = keeper_;
        maxSpotBps = 9500;
        maxSeniorBps = 9500;
        maxRentBps = 9500;
        maxCliffBps = 9500;
        maxSleeveShiftBps = 3000;
        minRebalanceInterval = 1 days;
        _status = _NOT_ENTERED;
        emit OwnershipTransferred(address(0), owner_);
        emit KeeperUpdated(address(0), keeper_);
        emit MaxAllocationUpdated(9500, 9500, 9500, 9500);
        emit MaxSleeveShiftUpdated(3000);
        emit MinRebalanceIntervalUpdated(1 days);
    }

    // -- Views --

    function idleUsdc() public view returns (uint256) {
        return USDC.balanceOf(address(this));
    }

    /// @notice eToken balances are 1:1 with USDC (confirmed via fork test).
    function totalAssets() public view returns (uint256) {
        return idleUsdc()
            + SPOT.balanceOf(address(this))
            + SENIOR.balanceOf(address(this))
            + RENTENNIALS.balanceOf(address(this))
            + CLIFF.balanceOf(address(this));
    }

    /// @return idle / Spot / Senior / Rentennials / Cliff balances and total NAV.
    function positions()
        external
        view
        returns (
            uint256 idle,
            uint256 spot,
            uint256 senior,
            uint256 rent,
            uint256 cliff,
            uint256 nav
        )
    {
        idle = idleUsdc();
        spot = SPOT.balanceOf(address(this));
        senior = SENIOR.balanceOf(address(this));
        rent = RENTENNIALS.balanceOf(address(this));
        cliff = CLIFF.balanceOf(address(this));
        nav = idle + spot + senior + rent + cliff;
    }

    // -- Owner --

    function fund(uint256 amount) external onlyOwner nonReentrant whenNotPaused {
        _safeTransferFrom(address(USDC), msg.sender, address(this), amount);
        emit Funded(msg.sender, amount);
    }

    /// @notice Send idle USDC to the owner address ONLY. Not an arbitrary
    ///         destination - even a compromised owner key can only send to itself.
    ///         Works when paused - this is a recovery path.
    function withdrawCash(uint256 amount) external onlyOwner nonReentrant {
        _safeTransfer(address(USDC), owner, amount);
        emit CashWithdrawn(owner, amount);
    }

    /// @notice Withdraw everything from all four eTokens, then send all idle
    ///         USDC to the owner. If any single pool reverts the whole call
    ///         fails - use emergencyWithdraw() per pool instead.
    ///         Works when paused - this is a recovery path.
    function emergencyExit() external onlyOwner nonReentrant {
        _withdrawAll(SPOT);
        _withdrawAll(SENIOR);
        _withdrawAll(RENTENNIALS);
        _withdrawAll(CLIFF);
        uint256 cash = idleUsdc();
        if (cash > 0) {
            _safeTransfer(address(USDC), owner, cash);
            emit CashWithdrawn(owner, cash);
        }
    }

    /// @notice Withdraw everything from ONE eToken. Use when emergencyExit()
    ///         fails because one pool reverts - the other pools are not held
    ///         hostage. Works when paused.
    function emergencyWithdraw(IEToken eToken) external onlyOwner nonReentrant {
        if (
            eToken != SPOT && eToken != SENIOR && eToken != RENTENNIALS && eToken != CLIFF
        ) {
            revert NotManagedToken(address(eToken));
        }
        _withdrawAll(eToken);
    }

    /// @notice Step 1 of 2: propose a new owner.
    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroAddress();
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    /// @notice Step 2 of 2: the pending owner accepts.
    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        emit OwnershipTransferred(owner, pendingOwner);
        owner = pendingOwner;
        pendingOwner = address(0);
    }

    function setKeeper(address newKeeper) external onlyOwner {
        if (newKeeper == address(0)) revert ZeroAddress();
        emit KeeperUpdated(keeper, newKeeper);
        keeper = newKeeper;
    }

    function setMaxAllocationBps(
        uint256 spotBps,
        uint256 seniorBps,
        uint256 rentBps,
        uint256 cliffBps
    ) external onlyOwner {
        if (spotBps > BPS_DENOMINATOR) revert InvalidAllocationBps(spotBps);
        if (seniorBps > BPS_DENOMINATOR) revert InvalidAllocationBps(seniorBps);
        if (rentBps > BPS_DENOMINATOR) revert InvalidAllocationBps(rentBps);
        if (cliffBps > BPS_DENOMINATOR) revert InvalidAllocationBps(cliffBps);
        maxSpotBps = spotBps;
        maxSeniorBps = seniorBps;
        maxRentBps = rentBps;
        maxCliffBps = cliffBps;
        emit MaxAllocationUpdated(spotBps, seniorBps, rentBps, cliffBps);
    }

    function setMaxSleeveShiftBps(uint256 bps) external onlyOwner {
        if (bps > BPS_DENOMINATOR) revert InvalidAllocationBps(bps);
        maxSleeveShiftBps = bps;
        emit MaxSleeveShiftUpdated(bps);
    }

    function setMinRebalanceInterval(uint256 interval) external onlyOwner {
        minRebalanceInterval = interval;
        emit MinRebalanceIntervalUpdated(interval);
    }

    /// @notice Toggle pause. Blocks fund and rebalance. Does NOT block
    ///         emergencyExit, emergencyWithdraw, withdrawCash or rescue paths.
    function setPaused(bool _paused) external onlyOwner {
        paused = _paused;
        emit PauseToggled(_paused);
    }

    /// @notice Recover an ERC20 accidentally sent to the vault.
    /// @dev Blocked for managed assets: USDC and the four eTokens.
    function rescueToken(address token, address to, uint256 amount)
        external
        onlyOwner
        nonReentrant
    {
        if (to == address(0) || token == address(0)) revert ZeroAddress();
        if (
            token == address(USDC) || token == address(SPOT) || token == address(SENIOR)
                || token == address(RENTENNIALS) || token == address(CLIFF)
        ) {
            revert CannotRescueManagedToken(token);
        }
        _safeTransfer(token, to, amount);
        emit TokenRescued(token, to, amount);
    }

    function rescueETH(address to, uint256 amount) external onlyOwner nonReentrant {
        if (to == address(0)) revert ZeroAddress();
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert TransferFailed();
        emit ETHRescued(to, amount);
    }

    receive() external payable {}

    // -- Keeper --

    /// @notice Move the vault toward absolute USDC targets for each pool.
    ///         Idle = NAV - (spot + senior + rent + cliff).
    ///
    /// Order: withdraw overweight pools first (frees USDC), then deposit into
    /// underweight pools. Rentennials and Cliff deposits are clamped to that
    /// pool's SCR. Partial Ensuro withdrawals are accepted.
    ///
    /// Rate limit applies ONLY when a target increases. Exits are immediate.
    function rebalance(
        uint256 spotTarget,
        uint256 seniorTarget,
        uint256 rentTarget,
        uint256 cliffTarget
    ) external onlyKeeper nonReentrant whenNotPaused {
        if (_isIncreasingAny(spotTarget, seniorTarget, rentTarget, cliffTarget)) {
            _enforceRebalanceCooldown();
        }
        _rebalance(spotTarget, seniorTarget, rentTarget, cliffTarget);
    }

    /// @notice Owner-only rebalance that skips the cooldown entirely.
    function forceRebalance(
        uint256 spotTarget,
        uint256 seniorTarget,
        uint256 rentTarget,
        uint256 cliffTarget
    ) external onlyOwner nonReentrant whenNotPaused {
        _rebalance(spotTarget, seniorTarget, rentTarget, cliffTarget);
    }

    // -- Internals --

    /// @notice True if any target exceeds the current balance of that sleeve.
    function _isIncreasingAny(
        uint256 spotTarget,
        uint256 seniorTarget,
        uint256 rentTarget,
        uint256 cliffTarget
    ) internal view returns (bool) {
        return spotTarget > SPOT.balanceOf(address(this))
            || seniorTarget > SENIOR.balanceOf(address(this))
            || rentTarget > RENTENNIALS.balanceOf(address(this))
            || cliffTarget > CLIFF.balanceOf(address(this));
    }

    function _enforceRebalanceCooldown() internal view {
        if (lastRebalanceAt == 0) return;
        uint256 earliest = lastRebalanceAt + minRebalanceInterval;
        if (block.timestamp < earliest) revert RebalanceTooSoon(earliest);
    }

    function _rebalance(
        uint256 spotTarget,
        uint256 seniorTarget,
        uint256 rentTarget,
        uint256 cliffTarget
    ) internal {
        // Hard ceiling: satellite sleeves cannot exceed that pool's SCR.
        uint256 rentScr = RENTENNIALS.scr();
        if (rentTarget > rentScr) {
            rentTarget = rentScr;
        }
        uint256 cliffScr = CLIFF.scr();
        if (cliffTarget > cliffScr) {
            cliffTarget = cliffScr;
        }

        uint256 nav = totalAssets();
        uint256 targetsSum = spotTarget + seniorTarget + rentTarget + cliffTarget;
        if (targetsSum > nav) revert TargetsExceedNav(targetsSum, nav);

        _enforceAllocationCap(SPOT, spotTarget, nav, maxSpotBps);
        _enforceAllocationCap(SENIOR, seniorTarget, nav, maxSeniorBps);
        _enforceAllocationCap(RENTENNIALS, rentTarget, nav, maxRentBps);
        _enforceAllocationCap(CLIFF, cliffTarget, nav, maxCliffBps);

        uint256 spotBal = SPOT.balanceOf(address(this));
        uint256 seniorBal = SENIOR.balanceOf(address(this));
        uint256 rentBal = RENTENNIALS.balanceOf(address(this));
        uint256 cliffBal = CLIFF.balanceOf(address(this));

        // shift caps are DIRECTIONAL: only constrain increases
        _enforceSleeveShift(SPOT, spotBal, spotTarget, nav, maxSleeveShiftBps);
        _enforceSleeveShift(SENIOR, seniorBal, seniorTarget, nav, maxSleeveShiftBps);
        _enforceSleeveShift(RENTENNIALS, rentBal, rentTarget, nav, maxSleeveShiftBps);
        _enforceSleeveShift(CLIFF, cliffBal, cliffTarget, nav, maxSleeveShiftBps);

        // 1. Withdraw overweight
        if (spotBal > spotTarget) {
            _withdrawFrom(SPOT, spotBal - spotTarget);
        }
        if (seniorBal > seniorTarget) {
            _withdrawFrom(SENIOR, seniorBal - seniorTarget);
        }
        if (rentBal > rentTarget) {
            _withdrawFrom(RENTENNIALS, rentBal - rentTarget);
        }
        if (cliffBal > cliffTarget) {
            _withdrawFrom(CLIFF, cliffBal - cliffTarget);
        }

        // Re-read after possible partial withdrawals.
        spotBal = SPOT.balanceOf(address(this));
        seniorBal = SENIOR.balanceOf(address(this));
        rentBal = RENTENNIALS.balanceOf(address(this));
        cliffBal = CLIFF.balanceOf(address(this));

        // 2. Deposit underweight from idle USDC
        if (spotBal < spotTarget) {
            _depositTo(SPOT, spotTarget - spotBal);
        }
        if (seniorBal < seniorTarget) {
            _depositTo(SENIOR, seniorTarget - seniorBal);
        }
        if (rentBal < rentTarget) {
            _depositTo(RENTENNIALS, rentTarget - rentBal);
        }
        if (cliffBal < cliffTarget) {
            _depositTo(CLIFF, cliffTarget - cliffBal);
        }

        lastRebalanceAt = block.timestamp;
        emit Rebalanced(spotTarget, seniorTarget, rentTarget, cliffTarget, idleUsdc());
    }

    function _enforceAllocationCap(
        IEToken eToken,
        uint256 target,
        uint256 nav,
        uint256 maxBps
    ) internal pure {
        uint256 maxAllowed = (nav * maxBps) / BPS_DENOMINATOR;
        if (target > maxAllowed) {
            revert AllocationCapExceeded(address(eToken), target, maxAllowed);
        }
    }

    /// @notice Only constrains INCREASES. Reductions are uncapped so the
    ///         kill-switch can go from full to floor in one call.
    function _enforceSleeveShift(
        IEToken eToken,
        uint256 balance,
        uint256 target,
        uint256 nav,
        uint256 maxBps
    ) internal pure {
        if (target <= balance) return; // exits uncapped
        uint256 shift = target - balance;
        uint256 maxAllowed = (nav * maxBps) / BPS_DENOMINATOR;
        if (shift > maxAllowed) {
            revert RebalanceShiftExceeded(address(eToken), shift, maxAllowed);
        }
    }

    function _depositTo(IEToken eToken, uint256 amount) internal {
        uint256 idle = idleUsdc();
        if (amount > idle) amount = idle;
        if (amount == 0) return;

        _safeApprove(address(USDC), address(POLICY_POOL), amount);
        POLICY_POOL.deposit(eToken, amount);
        emit Deposited(eToken, amount);
    }

    function _withdrawFrom(IEToken eToken, uint256 amount) internal {
        if (amount == 0) return;
        uint256 actual = POLICY_POOL.withdraw(eToken, amount);
        emit Withdrawn(eToken, amount, actual);
    }

    /// @notice Withdraw the vault's entire balance of an eToken. Uses balanceOf
    ///         rather than type(uint256).max because Ensuro reverts on max uint
    ///         (confirmed via mainnet fork test on all four pools).
    function _withdrawAll(IEToken eToken) internal {
        uint256 bal = eToken.balanceOf(address(this));
        if (bal == 0) return;
        uint256 actual = POLICY_POOL.withdraw(eToken, bal);
        emit Withdrawn(eToken, bal, actual);
    }

    // -- SafeERC20 helpers (inline, no OZ dependency) --

    function _safeTransfer(address token, address to, uint256 amount) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.transfer.selector, to, amount)
        );
        if (!success || (data.length > 0 && !abi.decode(data, (bool)))) {
            revert TransferFailed();
        }
    }

    function _safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, amount)
        );
        if (!success || (data.length > 0 && !abi.decode(data, (bool)))) {
            revert TransferFailed();
        }
    }

    function _safeApprove(address token, address spender, uint256 amount) internal {
        if (IERC20(token).allowance(address(this), spender) != 0) {
            (bool s0, bytes memory d0) = token.call(
                abi.encodeWithSelector(IERC20.approve.selector, spender, 0)
            );
            if (!s0 || (d0.length > 0 && !abi.decode(d0, (bool)))) revert TransferFailed();
        }
        (bool success, bytes memory data) = token.call(
            abi.encodeWithSelector(IERC20.approve.selector, spender, amount)
        );
        if (!success || (data.length > 0 && !abi.decode(data, (bool)))) {
            revert TransferFailed();
        }
    }
}

src/interfaces/IERC20.sol

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

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);

    function allowance(address owner, address spender) external view returns (uint256);

    function approve(address spender, uint256 amount) external returns (bool);

    function transfer(address to, uint256 amount) external returns (bool);

    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

src/interfaces/IEToken.sol

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

/// @notice Minimal Ensuro eToken surface. Balances are 1:1 with USDC (6 decimals).
/// @dev Docs: https://docs.ensuro.co/ensuro-docs/smart-contracts/contracts/etoken
interface IEToken {
    function balanceOf(address account) external view returns (uint256);

    function scr() external view returns (uint256);

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

src/interfaces/IPolicyPool.sol

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

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

/// @notice Minimal Ensuro PolicyPool surface used by BlueFundVault.
/// @dev Docs: https://docs.ensuro.co/ensuro-docs/smart-contracts/contracts/policypool
interface IPolicyPool {
    function deposit(IEToken eToken, uint256 amount) external;

    /// @return actual Amount withdrawn. May be less than `amount` if SCR-locked.
    ///         Pass type(uint256).max to withdraw as much as possible.
    function withdraw(IEToken eToken, uint256 amount) external returns (uint256 actual);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.