Skip to content
Verified contractExactMIT

VaultBox2

Address0xe34a74705e5edd16fcd42455cf11d9a176bcc14a
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,146,287
Creation transaction
0xffa47de0a5…a111c71e7b

src/ohmvault/VaultBox2.sol

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

/// ─────────────────────────────────────────────────────────────────────
///  VaultBox2 · the private box, second generation
///
///  Same idea as VaultBox (a personal contract that is msg.sender for its owner against the
///  frozen VaultBond / VaultStaker, and pays out anywhere incl. a RAILGUN 0zk balance), plus:
///
///   STEALTH ENTRY.  createFor(owner, salt) deploys a box for ANY owner at a CREATE2 address the
///   owner can compute in advance. Tokens can be sent to that address before it exists (e.g. a
///   RAILGUN unshield), and bondHeld / stakeHeld act on whatever the box holds. No approvals.
///
///   GASLESS.  Every owner action has a signed twin (EIP-712). Anyone may submit it and is tipped
///   from the tokens being moved, so the owner key never needs ETH and never appears as a sender.
///
///   OPERATOR.  A hot key allowed to collect / restake / unstake, never to pay out.
///   OWNER ROTATION.  Two-step, so a lost key is recoverable while you still have it.
///   EXEC.  Owner-only arbitrary call, so nothing can ever be stuck in the box.
///
///  No admin anywhere. The factory only ever moves the caller's own tokens.
/// ─────────────────────────────────────────────────────────────────────

interface IERC20B2 {
    function balanceOf(address) external view returns (uint256);
    function transfer(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
    function approve(address, uint256) external returns (bool);
}
interface IVaultBondB2 {
    function bond(uint256 ohmIn, uint256 minTokenOut) external returns (uint256);
    function claim() external returns (uint256);
    function claimable(address) external view returns (uint256);
}
interface IVaultStakerB2 {
    function stake(uint256 amount) external;
    function unstake(uint256 amount) external;
    function withdraw() external returns (uint256);
    function claim() external returns (uint256);
    function earned(address) external view returns (uint256);
    function cooling(address) external view returns (uint256);
    function coolingEnds(address) external view returns (uint256);
}
struct TokenData2 { uint8 tokenType; address tokenAddress; uint256 tokenSubID; }
struct CommitmentPreimage2 { bytes32 npk; TokenData2 token; uint120 value; }
struct ShieldCiphertext2 { bytes32[3] encryptedBundle; bytes32 shieldKey; }
struct ShieldRequest2 { CommitmentPreimage2 preimage; ShieldCiphertext2 ciphertext; }
interface IRailgun2 { function shield(ShieldRequest2[] calldata requests) external; }

contract VaultBox2 {
    IERC20B2 public immutable token;      // OHMV
    IERC20B2 public immutable ohm;        // OHM v2
    IVaultBondB2 public immutable bondC;
    IVaultStakerB2 public immutable staker;
    IRailgun2 public immutable railgun;
    address public immutable factory;

    address public owner;
    address public pendingOwner;
    address public operator;
    uint256 public nonce;                 // EIP-712 replay protection, one sequence for all signed actions

    // EIP-712
    bytes32 private constant TYPE_BOND = keccak256("BondHeld(uint256 minOut,uint256 tip,uint256 nonce,uint256 deadline)");
    bytes32 private constant TYPE_STAKE = keccak256("StakeHeld(uint256 tip,uint256 nonce,uint256 deadline)");
    bytes32 private constant TYPE_UNSTAKE = keccak256("Unstake(uint256 amount,uint256 nonce,uint256 deadline)");
    bytes32 private constant TYPE_PAYOUT = keccak256("Payout(address to,uint256 amount,uint256 tip,uint256 nonce,uint256 deadline)");
    bytes32 private constant TYPE_PRIVATE = keccak256("PayoutPrivate(bytes32 npk,uint120 value,bytes32 bundle0,bytes32 bundle1,bytes32 bundle2,bytes32 shieldKey,uint256 tip,uint256 nonce,uint256 deadline)");
    bytes32 private constant DOMAIN_TYPE = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    event Bonded(uint256 ohmIn, uint256 tokenOut, uint256 refunded);
    event Staked(uint256 amount);
    event Unstaked(uint256 amount);
    event Paid(address indexed to, uint256 amount);
    event Shielded(bytes32 indexed npk, uint256 amount);
    event Tipped(address indexed relayer, address token, uint256 amount);
    event OperatorSet(address operator);
    event OwnershipStarted(address pendingOwner);
    event OwnershipTransferred(address oldOwner, address newOwner);

    constructor(address _token, address _ohm, address _bond, address _staker, address _railgun, address _factory) {
        token = IERC20B2(_token); ohm = IERC20B2(_ohm); bondC = IVaultBondB2(_bond);
        staker = IVaultStakerB2(_staker); railgun = IRailgun2(_railgun); factory = _factory;
        owner = address(0xdead);
    }
    function init(address _owner) external {
        require(msg.sender == factory, "factory only");
        require(owner == address(0), "initialized");
        require(_owner != address(0), "zero owner");
        owner = _owner;
    }

    modifier onlyOwner() { require(msg.sender == owner, "owner only"); _; }
    // the factory counts as a keeper: its bond()/stake() only ever move msg.sender's own tokens into msg.sender's own box
    modifier onlyKeeper() { require(msg.sender == owner || msg.sender == operator || msg.sender == factory, "owner or operator"); _; }

    // ── ownership ──
    function transferOwnership(address to) external onlyOwner { pendingOwner = to; emit OwnershipStarted(to); }
    function acceptOwnership() external { require(msg.sender == pendingOwner, "not pending"); emit OwnershipTransferred(owner, msg.sender); owner = msg.sender; pendingOwner = address(0); }
    function setOperator(address op) external onlyOwner { operator = op; emit OperatorSet(op); }

    // ── signatures ──
    function domainSeparator() public view returns (bytes32) {
        return keccak256(abi.encode(DOMAIN_TYPE, keccak256("OHMVAULT Box"), keccak256("2"), block.chainid, address(this)));
    }
    function _check(bytes32 structHash, uint256 deadline, bytes calldata sig) internal {
        require(block.timestamp <= deadline, "expired");
        require(sig.length == 65, "sig length");
        bytes32 r; bytes32 s; uint8 v;
        assembly { r := calldataload(sig.offset) s := calldataload(add(sig.offset, 32)) v := byte(0, calldataload(add(sig.offset, 64))) }
        require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "sig s");
        if (v < 27) v += 27;
        address who = ecrecover(keccak256(abi.encodePacked("\x19\x01", domainSeparator(), structHash)), v, r, s);
        require(who != address(0) && who == owner, "bad signature");
        nonce++;
    }
    function _tip(IERC20B2 t, uint256 amount) internal {
        if (amount > 0) { require(t.transfer(msg.sender, amount), "tip"); emit Tipped(msg.sender, address(t), amount); }
    }

    // ── bond ──
    /// bond every OHM the box holds (sent here by the factory, a wallet, or a RAILGUN unshield)
    function bondHeld(uint256 minOut) external onlyKeeper returns (uint256) { return _bondHeld(minOut); }
    function bondHeldBySig(uint256 minOut, uint256 tip, uint256 deadline, bytes calldata sig) external returns (uint256) {
        _check(keccak256(abi.encode(TYPE_BOND, minOut, tip, nonce, deadline)), deadline, sig);
        _tip(ohm, tip);
        return _bondHeld(minOut);
    }
    function _bondHeld(uint256 minOut) internal returns (uint256 out) {
        uint256 ohmIn = ohm.balanceOf(address(this));
        require(ohmIn > 0, "no OHM");
        require(ohm.approve(address(bondC), ohmIn), "approve");
        out = bondC.bond(ohmIn, minOut);
        uint256 left = ohm.balanceOf(address(this));          // partial fill: the refund stays in the box (owner decides)
        emit Bonded(ohmIn, out, left);
    }
    /// send any OHM the box holds back to the owner (a partial-fill refund in wallet mode)
    function refundOhm() external onlyKeeper returns (uint256 left) {
        left = ohm.balanceOf(address(this));
        if (left > 0) require(ohm.transfer(owner, left), "refund");
    }

    // ── stake ──
    /// stake every OHMV the box holds (claimed rewards, unlocked bond, a RAILGUN unshield, a plain transfer)
    function stakeHeld() external onlyKeeper returns (uint256) { return _stakeHeld(); }
    function stakeHeldBySig(uint256 tip, uint256 deadline, bytes calldata sig) external returns (uint256) {
        _check(keccak256(abi.encode(TYPE_STAKE, tip, nonce, deadline)), deadline, sig);
        _tip(token, tip);
        return _stakeHeld();
    }
    function _stakeHeld() internal returns (uint256 amt) {
        amt = token.balanceOf(address(this));
        require(amt > 0, "no OHMV");
        require(token.approve(address(staker), amt), "approve");
        staker.stake(amt);
        emit Staked(amt);
    }
    /// collect what is ready, then stake all of it: compounding in one call
    function compound() external onlyKeeper returns (uint256) { _collect(); return _stakeHeld(); }

    function unstake(uint256 amount) external onlyKeeper { staker.unstake(amount); emit Unstaked(amount); }
    function unstakeBySig(uint256 amount, uint256 deadline, bytes calldata sig) external {
        _check(keccak256(abi.encode(TYPE_UNSTAKE, amount, nonce, deadline)), deadline, sig);
        staker.unstake(amount); emit Unstaked(amount);
    }

    // ── collect & pay out ──
    function _collect() internal returns (uint256 bal) {
        if (bondC.claimable(address(this)) > 0) bondC.claim();
        if (staker.earned(address(this)) > 0) staker.claim();
        if (staker.cooling(address(this)) > 0 && block.timestamp >= staker.coolingEnds(address(this))) staker.withdraw();
        bal = token.balanceOf(address(this));
    }
    function collect() external onlyKeeper returns (uint256) { return _collect(); }

    function payout(address to, uint256 amount) external onlyOwner returns (uint256) { return _payout(to, amount); }
    function payoutBySig(address to, uint256 amount, uint256 tip, uint256 deadline, bytes calldata sig) external returns (uint256) {
        _check(keccak256(abi.encode(TYPE_PAYOUT, to, amount, tip, nonce, deadline)), deadline, sig);
        _collect(); _tip(token, tip);
        return _payout(to, amount);
    }
    function _payout(address to, uint256 amount) internal returns (uint256 sent) {
        require(to != address(0), "zero to");
        uint256 bal = _collect();
        sent = amount == 0 ? bal : amount;
        require(sent > 0 && sent <= bal, "amount");
        require(token.transfer(to, sent), "transfer");
        emit Paid(to, sent);
    }

    function payoutPrivate(ShieldRequest2 calldata req) external onlyOwner returns (uint256) { return _shield(req); }
    function payoutPrivateBySig(ShieldRequest2 calldata req, uint256 tip, uint256 deadline, bytes calldata sig) external returns (uint256) {
        bytes32 h = keccak256(abi.encode(TYPE_PRIVATE, req.preimage.npk, req.preimage.value,
            req.ciphertext.encryptedBundle[0], req.ciphertext.encryptedBundle[1], req.ciphertext.encryptedBundle[2], req.ciphertext.shieldKey, tip, nonce, deadline));
        _check(h, deadline, sig);
        _collect(); _tip(token, tip);
        return _shield(req);
    }
    function _shield(ShieldRequest2 calldata req) internal returns (uint256 sent) {
        TokenData2 calldata t = req.preimage.token;
        require(t.tokenType == 0 && t.tokenAddress == address(token) && t.tokenSubID == 0, "not OHMV");
        sent = req.preimage.value;
        uint256 bal = _collect();
        require(sent > 0 && sent <= bal, "amount");
        require(token.approve(address(railgun), sent), "approve");
        ShieldRequest2[] memory reqs = new ShieldRequest2[](1);
        reqs[0] = req;
        railgun.shield(reqs);
        require(token.balanceOf(address(this)) == bal - sent, "shield pulled a different amount");
        emit Shielded(req.preimage.npk, sent);
    }

    // ── escape hatch ──
    function exec(address target, uint256 value, bytes calldata data) external onlyOwner returns (bytes memory ret) {
        bool ok; (ok, ret) = target.call{ value: value }(data);
        require(ok, "exec failed");
    }
    receive() external payable {}
}

contract VaultBoxFactory2 {
    address public immutable implementation;
    IERC20B2 public immutable token;
    IERC20B2 public immutable ohm;
    mapping(address => address) public boxOf;          // the wallet-mode box (salt 0)
    mapping(address => bool) public isBox;             // every box this factory made

    event BoxCreated(address indexed owner, address box, bytes32 salt);

    constructor(address _token, address _ohm, address _bond, address _staker, address _railgun) {
        token = IERC20B2(_token); ohm = IERC20B2(_ohm);
        implementation = address(new VaultBox2(_token, _ohm, _bond, _staker, _railgun, address(this)));
    }

    function _salt(address owner, bytes32 salt) internal pure returns (bytes32) { return keccak256(abi.encode(owner, salt)); }
    function _cloneCode() internal view returns (bytes memory) {
        return abi.encodePacked(hex"3d602d80600a3d3981f3363d3d373d3d3d363d73", implementation, hex"5af43d82803e903d91602b57fd5bf3");
    }
    /// where a box for (owner, salt) lives, or will live. Send tokens here before it exists if you like.
    function predictFor(address owner, bytes32 salt) public view returns (address) {
        bytes32 h = keccak256(abi.encodePacked(bytes1(0xff), address(this), _salt(owner, salt), keccak256(_cloneCode())));
        return address(uint160(uint256(h)));
    }
    function predict(address owner) external view returns (address) { return predictFor(owner, bytes32(0)); }

    /// anyone may create a box FOR an owner (a relayer, a friend, the owner). Only that owner can ever use it.
    function createFor(address owner, bytes32 salt) public returns (address box) {
        require(owner != address(0), "zero owner");
        box = predictFor(owner, salt);
        if (box.code.length > 0) return box;
        bytes memory code = _cloneCode(); bytes32 s = _salt(owner, salt);
        assembly { box := create2(0, add(code, 0x20), mload(code), s) }
        require(box != address(0), "create2");
        VaultBox2(payable(box)).init(owner);
        isBox[box] = true;
        if (salt == bytes32(0)) boxOf[owner] = box;
        emit BoxCreated(owner, box, salt);
    }
    function getOrCreate() public returns (address) { return createFor(msg.sender, bytes32(0)); }

    /// wallet mode, as in v1: move my own tokens into my box and act
    function bond(uint256 ohmIn, uint256 minTokenOut) external returns (uint256) {
        address box = getOrCreate();
        require(ohm.transferFrom(msg.sender, box, ohmIn), "ohm in");
        uint256 out = VaultBox2(payable(box)).bondHeld(minTokenOut);
        VaultBox2(payable(box)).refundOhm();                 // partial fill: unplaced OHM goes straight back to the wallet
        return out;
    }
    function stake(uint256 amount) external returns (uint256) {
        address box = getOrCreate();
        require(token.transferFrom(msg.sender, box, amount), "ohmv in");
        return VaultBox2(payable(box)).stakeHeld();
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-core/",
    "forge-std/=lib/forge-std/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "@openzeppelin/contracts/=lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "v4-core/=lib/v4-core/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.