Skip to content
Verified contractExactMIT

MindVault

Address0xdb3f630660d51ecbce040da1f9ced2665dfd2772
Balance

0.041797 ETH

 

Transactions

11

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 800 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,284,624
Creation transaction
0x858f0642fc…6d5499cae3

64 files

The source code is large: one file is shown at a time. Choose a file in the list.

src/MindVault.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Ownable2Step, Ownable} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {MindFactory} from "./MindFactory.sol";
import {MindCoin} from "./MindCoin.sol";

/// @title MindVault (v2)
/// @notice v2: a mind acts only once its coin has graduated from the bonding curve (and only into graduated
/// pools); fees booked while it is on the curve wait here.
/// Every mind's treasury, booked per coin. The mind never holds a key. It proposes, the engine's
/// operator key signs, and this contract decides. The operator can only swap through the mind's own pools,
/// burn, and pay people who hold the coin, inside per-action, rolling hourly and rolling daily limits and a
/// price-impact cap measured from the block-start price. Nobody, owner included, can withdraw a treasury to
/// an address of their choosing.
///
/// Rolling windows: every ETH outflow (buyback, back, ETH airdrop) and every held-token outflow (sell, coin
/// airdrop) is written into time buckets. The cap for a window is a share of (balance now + what went out in
/// the window), i.e. the treasury as it stood before the window's spending plus anything that came in since.
/// Buckets are coarse, so a window is never shorter than advertised: the hour cap covers 60 to 70 minutes and
/// the day cap covers 24 to 26 hours. In any 24h the operator can move at most dayBps of a treasury.
contract MindVault is Ownable2Step, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;
    using StateLibrary for IPoolManager;

    error NotFactory();
    error NotOperator();
    error NotGuardian();
    error NotMind();
    error IsPaused();
    /// the coin's pool liquidity was removed (MindFactory.pull). Its mind can no longer act, like a pause that stays.
    error CoinPulled();
    error OverActionLimit();
    error OverHourLimit();
    error OverDayLimit();
    error OverPayoutLimit();
    error Insufficient();
    error NotHolder(address who);
    error BadRecipient(address who);
    error BadLength();
    error BadLimits();
    error BadRole();
    error TooYoung();
    error EthTransfer();
    /// this block's price-impact budget for the pool is already used up. Try again next block.
    error OverImpact();
    /// v2: the coin is still on its bonding curve. Minds wake, and their treasuries can act, at graduation.
    error NotGraduated();

    struct Limits {
        uint16 actionBps; // max share of the treasury's ETH (or of a held token) in one action
        uint16 hourBps; // max out per rolling hour
        uint16 dayBps; // max out per rolling day
        uint16 impactBps; // max price move from the block-start price
        uint16 payoutHourBps; // max ETH paid to holders per rolling hour
    }

    /// @dev a meter is a ring of packed buckets: slot k holds buckets 2k (low 128 bits) and 2k+1 (high).
    /// bucket = index (top 32 bits of the 128) | amount (low 96 bits)
    struct Book {
        uint256 eth;
        uint256 credits;
        bool paused;
        mapping(uint256 => uint256) hourM;
        mapping(uint256 => uint256) dayM;
        mapping(uint256 => uint256) payM;
    }

    uint16 internal constant BPS = 10_000;
    uint256 public constant MAX_RECIPIENTS = 50;
    /// a mind may only back coins that have traded for at least a day. Stops launch-and-farm by a bad
    /// operator, and minds being talked into backing a coin that was launched an hour ago to be dumped on them.
    uint256 public constant BACK_MIN_AGE = 1 days;
    uint256 public constant PAYOUT_GAS = 30_000;
    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD;

    uint256 internal constant HOUR_GRAN = 10 minutes;
    uint256 internal constant HOUR_N = 7; // remembers >= 60 minutes
    uint256 internal constant DAY_GRAN = 2 hours;
    uint256 internal constant DAY_N = 13; // remembers >= 24 hours
    uint256 internal constant M96 = (1 << 96) - 1;
    uint256 internal constant M128 = (1 << 128) - 1;

    /// hard caps, the owner can tighten but never loosen past these
    uint16 public constant CAP_ACTION_BPS = 2_000;
    uint16 public constant CAP_HOUR_BPS = 4_000;
    uint16 public constant CAP_DAY_BPS = 7_000;
    uint16 public constant CAP_IMPACT_BPS = 1_000;
    uint16 public constant CAP_PAYOUT_HOUR_BPS = 2_500;

    MindFactory public immutable factory;
    IPoolManager public immutable poolManager;

    address public operator;
    address public guardian;
    address public creditsPayee;
    bool public pausedAll;

    Limits public limits = Limits({actionBps: 1_000, hourBps: 2_500, dayBps: 5_000, impactBps: 300, payoutHourBps: 1_000});

    mapping(address => Book) internal _books;
    /// coin => token => amount the coin's treasury holds (its own coin, or other minds it backed)
    mapping(address => mapping(address => uint256)) public heldOf;
    mapping(address => mapping(address => mapping(uint256 => uint256))) internal _heldHourM;
    mapping(address => mapping(address => mapping(uint256 => uint256))) internal _heldDayM;

    event Deposited(address indexed coin, uint256 eth, uint256 credits, uint256 coinAmount);
    event Action(
        address indexed coin,
        bytes32 indexed thought,
        string kind,
        address token,
        uint256 ethDelta,
        uint256 tokenDelta,
        int256 sign
    );
    event Airdropped(address indexed coin, bytes32 indexed thought, address indexed to, uint256 amount, bool inEth);
    /// an ETH payout the recipient refused (reverted or ran out of gas). The ETH stays in the treasury.
    event AirdropFailed(address indexed coin, bytes32 indexed thought, address indexed to, uint256 amount);
    event CreditsDrawn(address indexed coin, uint256 amount);
    event Paused(address indexed coin, bool paused);
    event LimitsSet(Limits limits);
    event RolesSet(address operator, address guardian, address creditsPayee);

    constructor(MindFactory _factory, address _owner, address _operator, address _guardian, address _creditsPayee)
        Ownable(_owner)
    {
        if (_operator == address(0) || _creditsPayee == address(0)) revert BadRole();
        factory = _factory;
        poolManager = _factory.poolManager();
        operator = _operator;
        guardian = _guardian;
        creditsPayee = _creditsPayee;
    }

    /// @dev refunds come from the factory, sell proceeds straight from the pool manager
    receive() external payable {
        if (msg.sender != address(factory) && msg.sender != address(poolManager)) revert NotFactory();
    }

    modifier onlyOperator() {
        if (msg.sender != operator) revert NotOperator();
        _;
    }

    modifier live(address coin) {
        if (!factory.isMind(coin)) revert NotMind();
        if (pausedAll || _books[coin].paused) revert IsPaused();
        if (factory.pulled(coin)) revert CoinPulled();
        if (!factory.graduated(coin)) revert NotGraduated();
        _;
    }

    // ---------------------------------------------------------------- admin

    function setRoles(address _operator, address _guardian, address _creditsPayee) external onlyOwner {
        if (_operator == address(0) || _creditsPayee == address(0)) revert BadRole();
        operator = _operator;
        guardian = _guardian;
        creditsPayee = _creditsPayee;
        emit RolesSet(_operator, _guardian, _creditsPayee);
    }

    function setLimits(Limits calldata l) external onlyOwner {
        if (
            l.actionBps > CAP_ACTION_BPS || l.hourBps > CAP_HOUR_BPS || l.dayBps > CAP_DAY_BPS
                || l.impactBps > CAP_IMPACT_BPS || l.payoutHourBps > CAP_PAYOUT_HOUR_BPS || l.impactBps == 0
        ) revert BadLimits();
        limits = l;
        emit LimitsSet(l);
    }

    /// @notice circuit breaker. Guardian or owner.
    function setPaused(address coin, bool p) external {
        if (msg.sender != guardian && msg.sender != owner()) revert NotGuardian();
        if (coin == address(0)) pausedAll = p;
        else _books[coin].paused = p;
        emit Paused(coin, p);
    }

    // ---------------------------------------------------------------- deposits

    function deposit(address coin, uint256 credits, uint256 coinAmount) external payable {
        if (msg.sender != address(factory)) revert NotFactory();
        Book storage b = _books[coin];
        b.eth += msg.value - credits;
        b.credits += credits;
        if (coinAmount > 0) heldOf[coin][coin] += coinAmount;
        emit Deposited(coin, msg.value - credits, credits, coinAmount);
    }

    // ---------------------------------------------------------------- actions

    /// @notice buy the mind's own coin with treasury ETH. Burn it, or keep it as a reserve.
    function buyback(address coin, uint256 ethAmount, uint256 minOut, bool burnIt, bytes32 thought)
        external
        onlyOperator
        live(coin)
        nonReentrant
    {
        (uint256 out, uint256 used) = _buy(coin, coin, ethAmount, minOut);
        if (burnIt) MindCoin(coin).burn(out);
        else heldOf[coin][coin] += out;
        emit Action(coin, thought, burnIt ? "buyback-burn" : "buyback", coin, used, out, -1);
    }

    /// @notice back another mind: buy its coin with this mind's treasury ETH
    function back(address coin, address target, uint256 ethAmount, uint256 minOut, bytes32 thought)
        external
        onlyOperator
        live(coin)
        nonReentrant
    {
        if (target == coin || !factory.isMind(target)) revert NotMind();
        if (!factory.graduated(target)) revert NotGraduated();
        (, uint40 launchedAt,) = factory.minds(target);
        if (block.timestamp < uint256(launchedAt) + BACK_MIN_AGE) revert TooYoung();
        (uint256 out, uint256 used) = _buy(coin, target, ethAmount, minOut);
        heldOf[coin][target] += out;
        emit Action(coin, thought, "back", target, used, out, -1);
    }

    /// @notice burn coins the treasury holds. Not metered: burning cannot move value to anyone.
    function burn(address coin, uint256 amount, bytes32 thought) external onlyOperator live(coin) nonReentrant {
        if (heldOf[coin][coin] < amount) revert Insufficient();
        heldOf[coin][coin] -= amount;
        MindCoin(coin).burn(amount);
        emit Action(coin, thought, "burn", coin, 0, amount, 0);
    }

    /// @notice sell a held token (own coin or a backed mind) back to ETH, into this mind's treasury
    function sell(address coin, address token, uint256 amount, uint256 minOut, bytes32 thought)
        external
        onlyOperator
        live(coin)
        nonReentrant
    {
        if (!factory.isMind(token)) revert NotMind();
        if (!factory.graduated(token)) revert NotGraduated();
        _checkHeld(coin, token, amount);
        heldOf[coin][token] -= amount;
        IERC20(token).forceApprove(address(factory), amount);
        (uint256 out, uint256 used) = factory.swap(
            token, false, amount, minOut, _limit(token, false), address(this)
        );
        heldOf[coin][token] += amount - used;
        _recordHeld(coin, token, used);
        _books[coin].eth += out;
        emit Action(coin, thought, "sell", token, out, used, 1);
    }

    /// @notice pay holders. Every recipient must hold the coin at execution time. An ETH payout a recipient
    /// refuses is skipped (AirdropFailed) and stays in the treasury, so one hostile holder cannot block the rest.
    function airdrop(address coin, address[] calldata to, uint256[] calldata amounts, bool inEth, bytes32 thought)
        external
        onlyOperator
        live(coin)
        nonReentrant
    {
        uint256 n = to.length;
        if (n == 0 || n != amounts.length || n > MAX_RECIPIENTS) revert BadLength();
        uint256 total;
        for (uint256 i; i < n; ++i) {
            total += amounts[i];
        }

        Book storage b = _books[coin];
        if (inEth) {
            _checkEth(b, total);
            uint256 h = _sum(b.hourM, HOUR_GRAN, HOUR_N);
            uint256 p = _sum(b.payM, HOUR_GRAN, HOUR_N);
            if (p + total > (b.eth + h) * limits.payoutHourBps / BPS) revert OverPayoutLimit();
            b.eth -= total;
        } else {
            _checkHeld(coin, coin, total);
            heldOf[coin][coin] -= total;
            _recordHeld(coin, coin, total);
        }

        uint256 paid = _pay(coin, to, amounts, inEth, thought);
        if (inEth) {
            b.eth += total - paid; // refused payouts stay in the treasury
            _recordEth(b, paid);
            _add(b.payM, HOUR_GRAN, HOUR_N, paid);
        }
        emit Action(
            coin,
            thought,
            inEth ? "airdrop-eth" : "airdrop",
            inEth ? address(0) : coin,
            inEth ? paid : 0,
            inEth ? 0 : total,
            inEth ? int256(-1) : int256(0)
        );
    }

    function _pay(address coin, address[] calldata to, uint256[] calldata amounts, bool inEth, bytes32 thought)
        internal
        returns (uint256 paid)
    {
        address hookAddr = address(factory.hook());
        uint256 n = to.length;
        for (uint256 i; i < n; ++i) {
            address r = to[i];
            uint256 a = amounts[i];
            if (
                r == address(0) || r == DEAD || r == address(this) || r == address(factory)
                    || r == address(poolManager) || r == coin || r == hookAddr
            ) revert BadRecipient(r);
            if (IERC20(coin).balanceOf(r) == 0) revert NotHolder(r);
            if (inEth) {
                bool ok;
                // no returndata copy: a recipient cannot return-bomb the loop
                assembly {
                    ok := call(PAYOUT_GAS, r, a, 0, 0, 0, 0)
                }
                if (!ok) {
                    emit AirdropFailed(coin, thought, r, a);
                    continue;
                }
                paid += a;
            } else {
                IERC20(coin).safeTransfer(r, a);
            }
            emit Airdropped(coin, thought, r, a, inEth);
        }
    }

    /// @notice fund the mind's model. Credits only ever go to the fixed payee. Paused like every other
    /// operator action, so the guardian's pause also stops a stolen operator key from draining credits.
    function drawCredits(address coin, uint256 amount) external onlyOperator live(coin) nonReentrant {
        Book storage b = _books[coin];
        if (b.credits < amount) revert Insufficient();
        b.credits -= amount;
        (bool ok,) = creditsPayee.call{value: amount}("");
        if (!ok) revert EthTransfer();
        emit CreditsDrawn(coin, amount);
    }

    // ---------------------------------------------------------------- views

    function ethOf(address coin) external view returns (uint256) {
        return _books[coin].eth;
    }

    function creditsOf(address coin) external view returns (uint256) {
        return _books[coin].credits;
    }

    /// @notice true when the mind cannot act: paused, or its coin's liquidity was pulled
    function paused(address coin) external view returns (bool) {
        return pausedAll || _books[coin].paused || factory.pulled(coin);
    }

    /// @notice how much ETH the mind could still move right now. The contract says no past this.
    function spendRoom(address coin) external view returns (uint256 perAction, uint256 hourLeft, uint256 dayLeft) {
        Book storage b = _books[coin];
        Limits memory l = limits;
        uint256 eth = b.eth;
        perAction = eth * l.actionBps / BPS;
        hourLeft = _room(eth, _sum(b.hourM, HOUR_GRAN, HOUR_N), l.hourBps);
        dayLeft = _room(eth, _sum(b.dayM, DAY_GRAN, DAY_N), l.dayBps);
    }

    /// @notice ETH that can still go to holders this rolling hour (also bounded by spendRoom)
    function payoutRoom(address coin) external view returns (uint256) {
        Book storage b = _books[coin];
        uint256 h = _sum(b.hourM, HOUR_GRAN, HOUR_N);
        uint256 p = _sum(b.payM, HOUR_GRAN, HOUR_N);
        uint256 cap = (b.eth + h) * limits.payoutHourBps / BPS;
        return cap > p ? cap - p : 0;
    }

    /// @notice how much of a held token the mind could still sell or airdrop right now
    function heldRoom(address coin, address token)
        external
        view
        returns (uint256 perAction, uint256 hourLeft, uint256 dayLeft)
    {
        Limits memory l = limits;
        uint256 held = heldOf[coin][token];
        perAction = held * l.actionBps / BPS;
        hourLeft = _room(held, _sum(_heldHourM[coin][token], HOUR_GRAN, HOUR_N), l.hourBps);
        dayLeft = _room(held, _sum(_heldDayM[coin][token], DAY_GRAN, DAY_N), l.dayBps);
    }

    // ---------------------------------------------------------------- internals

    function _buy(address coin, address target, uint256 ethAmount, uint256 minOut)
        internal
        returns (uint256 out, uint256 used)
    {
        Book storage b = _books[coin];
        _checkEth(b, ethAmount);
        (out, used) = factory.swap{value: ethAmount}(
            target, true, ethAmount, minOut, _limit(target, true), address(this)
        );
        // partial fills at the impact cap refund the rest, only what was used counts
        _recordEth(b, used);
        b.eth -= used;
    }

    /// @dev impact limit from the block-start price. If earlier swaps this block already pushed the price
    /// past it, there is no room left and the action stops here with a clear error.
    function _limit(address token, bool isBuy) internal view returns (uint160 l) {
        l = factory.impactLimit(token, isBuy, limits.impactBps);
        (uint160 sp,,,) = poolManager.getSlot0(factory.poolKey(token).toId());
        if (isBuy ? l >= sp : l <= sp) revert OverImpact();
    }

    function _checkEth(Book storage b, uint256 amt) internal view {
        Limits memory l = limits;
        uint256 eth = b.eth;
        if (amt > eth) revert Insufficient();
        if (amt > eth * l.actionBps / BPS) revert OverActionLimit();
        uint256 h = _sum(b.hourM, HOUR_GRAN, HOUR_N);
        if (h + amt > (eth + h) * l.hourBps / BPS) revert OverHourLimit();
        uint256 d = _sum(b.dayM, DAY_GRAN, DAY_N);
        if (d + amt > (eth + d) * l.dayBps / BPS) revert OverDayLimit();
    }

    function _recordEth(Book storage b, uint256 amt) internal {
        _add(b.hourM, HOUR_GRAN, HOUR_N, amt);
        _add(b.dayM, DAY_GRAN, DAY_N, amt);
    }

    function _checkHeld(address coin, address token, uint256 amt) internal view {
        Limits memory l = limits;
        uint256 held = heldOf[coin][token];
        if (amt > held) revert Insufficient();
        // moving more than an action's share of holdings in one go is a dump, not a decision
        if (amt > held * l.actionBps / BPS) revert OverActionLimit();
        uint256 h = _sum(_heldHourM[coin][token], HOUR_GRAN, HOUR_N);
        if (h + amt > (held + h) * l.hourBps / BPS) revert OverHourLimit();
        uint256 d = _sum(_heldDayM[coin][token], DAY_GRAN, DAY_N);
        if (d + amt > (held + d) * l.dayBps / BPS) revert OverDayLimit();
    }

    function _recordHeld(address coin, address token, uint256 amt) internal {
        _add(_heldHourM[coin][token], HOUR_GRAN, HOUR_N, amt);
        _add(_heldDayM[coin][token], DAY_GRAN, DAY_N, amt);
    }

    function _room(uint256 bal, uint256 spent, uint16 bps) internal pure returns (uint256 r) {
        uint256 cap = (bal + spent) * bps / BPS;
        r = cap > spent ? cap - spent : 0;
        if (r > bal) r = bal;
    }

    /// @dev total recorded in the buckets still inside the window
    function _sum(mapping(uint256 => uint256) storage m, uint256 gran, uint256 n) internal view returns (uint256 t) {
        uint256 cur = block.timestamp / gran;
        for (uint256 i; i < n; i += 2) {
            uint256 w = m[i >> 1];
            if (w == 0) continue;
            uint256 lo = w & M128;
            if ((lo >> 96) + n > cur) t += lo & M96;
            if (i + 1 < n) {
                uint256 hi = w >> 128;
                if ((hi >> 96) + n > cur) t += hi & M96;
            }
        }
    }

    function _add(mapping(uint256 => uint256) storage m, uint256 gran, uint256 n, uint256 amt) internal {
        if (amt == 0) return;
        uint256 cur = block.timestamp / gran;
        uint256 pos = cur % n;
        uint256 slot = pos >> 1;
        uint256 w = m[slot];
        uint256 bkt = (pos & 1 == 0) ? w & M128 : w >> 128;
        uint256 a = (bkt >> 96 == cur) ? (bkt & M96) + amt : amt;
        if (a > M96) a = M96; // unreachable for real balances (2^96 wei ~ 7.9e10 ETH, supply is 1e27 coin)
        uint256 nb = (cur << 96) | a;
        w = (pos & 1 == 0) ? (w & ~M128) | nb : (w & M128) | (nb << 128);
        m[slot] = w;
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 800,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "v4-core/=lib/v4-core/src/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/solmate/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.