Skip to content
Verified contractExactMIT

VaultBond

Address0x9f2e0600d43de1de6ec75991f18e0852cc37d3d7
Balance

0 ETH

 

Transactions

254

 

Compiler

solc 0.8.26

 

Same code

1 more 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,141,367
Creation transaction
0x6524b58034…f1be43e586

src/ohmvault/VaultBond.sol

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

import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";

/// ─────────────────────────────────────────────────────────────────────
///  VaultBond · buy OHMVAULT at a discount, from OHM that becomes the floor
///
///  You bond OHM. It goes into the locked floor (donateFloor on the hook:
///  protocol-owned LP that never exits). You are minted OHMVAULT at +20% vs
///  the market rate, vesting linearly over 24 hours. v1 numbers, unchanged.
///
///  What changed vs SEMI v1:
///   1. THE GATE DEFENDS CURRENT BACKING, NOT THE HIGH-WATER MARK.
///        marketOut = ohmIn · tokensPerOhm · 1.2                 (the deal)
///        fbrCap    = ohmIn / currentFbr                         (the guard)
///        tokenOut  = min(marketOut, fbrCap)
///      currentFbr is the live OHM-per-token backing. So every bond leaves
///      backing-per-token at least where it was: still accretive by
///      construction, but it no longer closes itself when bond-minted supply
///      pushes live backing under a stale mark (v1 on RHC: bonds dead until a
///      +137% pump). The ratchet's marks are for emissions only.
///   2. TWAP QUOTE. tokensPerOhm = min(10-minute TWAP, spot). The discount is
///      the same 20%; it is just measured against a price that one dump
///      cannot move. Honest bonders see the same number.
///   3. PARTIAL FILL + SKIM. The hook places what the ~8% own-swap bound allows
///      and refunds the rest. The leg it sells for tokens pays the pool's 5%
///      skim (~2.56% of the bond), which stays in the hook as fees. OHMVAULT is
///      minted only against OHM that reached the floor; the unplaced OHM goes
///      back to the bonder in the same tx.
///   4. The token-side surplus of the hook's compound stays in the hook and is
///      harvested 40/60 later: a documented treasury stream (see VaultHook).
///
///  No owner. No admin. Mints only through the frozen VaultMinter.
/// ─────────────────────────────────────────────────────────────────────

interface IVaultMinterB { function mint(address, uint256) external; }
interface IVaultHookB {
    function ohmReserve() external view returns (uint256);
    function tokenReserve() external view returns (uint256);
    function spotTokenPerOhm() external view returns (uint256);
    function twapTokenPerOhm() external view returns (uint256);
    function donateFloor(uint256) external returns (uint256 placed, uint256 refund);
    function donationNetBps() external pure returns (uint256);
}
interface IVaultRatchetB { function initialized() external view returns (bool); }
interface IVaultTokenB { function totalSupply() external view returns (uint256); }
interface IERC20B {
    function transfer(address, uint256) external returns (bool);
    function transferFrom(address, address, uint256) external returns (bool);
    function approve(address, uint256) external returns (bool);
    function balanceOf(address) external view returns (uint256);
}

contract VaultBond {
    uint256 public constant DISCOUNT_BPS = 2000;  // +20% vs market
    uint256 public constant VEST = 24 hours;
    uint256 private constant SCALE = 1e18;      // price scale (token per OHM)
    uint256 private constant FBR_SCALE = 1e36;  // backing scale, same as the ratchet (OHM has 9 dp)

    IERC20B public immutable token;
    IERC20B public immutable ohm;
    IVaultMinterB public immutable minter;
    IVaultHookB public immutable hook;
    IVaultRatchetB public immutable ratchet;

    struct Vest { uint256 total; uint256 claimed; uint64 start; uint64 end; }
    mapping(address => Vest) public vests;

    uint256 public totalBondedOhm;
    uint256 public totalMintedToken;

    event Bonded(address indexed who, uint256 ohmIn, uint256 ohmPlaced, uint256 tokenOut, uint64 vestEnd);
    event Claimed(address indexed who, uint256 amount);

    constructor(address _token, address _ohm, address _minter, address _hook, address _ratchet) {
        require(_token != address(0) && _ohm != address(0) && _minter != address(0) && _hook != address(0) && _ratchet != address(0), "zero");
        token = IERC20B(_token);
        ohm = IERC20B(_ohm);
        minter = IVaultMinterB(_minter);
        hook = IVaultHookB(_hook);
        ratchet = IVaultRatchetB(_ratchet);
    }

    /// the price the bond quotes against: the lower of 10-min TWAP and spot (token per OHM, 1e18)
    function quotePrice() public view returns (uint256) {
        uint256 spot = hook.spotTokenPerOhm();
        uint256 twap = hook.twapTokenPerOhm();
        return twap < spot ? twap : spot;
    }

    /// live OHM backing per token-wei, scaled by 1e36, before any bond
    function currentFbr() public view returns (uint256) {
        uint256 S = IVaultTokenB(address(token)).totalSupply();
        if (S == 0) return 0;
        return FullMath.mulDiv(hook.ohmReserve(), FBR_SCALE, S);
    }

    function _quote(uint256 ohmIn) internal view returns (uint256 tokenOut, bool gated) {
        uint256 p = quotePrice();
        uint256 R = hook.ohmReserve();
        uint256 S = IVaultTokenB(address(token)).totalSupply();
        if (p == 0 || R == 0 || S == 0 || ohmIn == 0) return (0, false);
        uint256 marketOut = (FullMath.mulDiv(ohmIn, p, SCALE) * (10_000 + DISCOUNT_BPS)) / 10_000;
        // ohmIn / live backing, straight from the reserves (no scaled intermediate to round),
        // less 1 ppm so the pool's own liquidity rounding can never tip a capped bond below par
        uint256 fbrCap = FullMath.mulDiv(ohmIn, S, R);
        fbrCap -= fbrCap / 1_000_000;
        gated = fbrCap < marketOut;
        tokenOut = gated ? fbrCap : marketOut;
    }

    /// bond `ohmIn` OHM for discounted, vesting OHMVAULT. `minTokenOut` protects against both
    /// the gate and a partial fill. Unplaced OHM is refunded in the same transaction.
    function bond(uint256 ohmIn, uint256 minTokenOut) external returns (uint256 tokenOut) {
        require(ohmIn > 0, "zero");
        require(ratchet.initialized(), "floor not live");
        require(hook.tokenReserve() > 0 && hook.ohmReserve() > 0, "no pool");

        (uint256 quoted, ) = _quote(ohmIn);     // price and gate fixed BEFORE the donation moves the pool
        require(quoted > 0, "zero out");

        require(ohm.transferFrom(msg.sender, address(this), ohmIn), "ohm in");
        require(ohm.approve(address(hook), ohmIn), "approve");
        (uint256 placed, uint256 refund) = hook.donateFloor(ohmIn);
        require(placed > 0, "nothing placed");
        if (refund > 0) require(ohm.transfer(msg.sender, refund), "refund");

        tokenOut = FullMath.mulDiv(quoted, placed, ohmIn);
        require(tokenOut > 0, "zero out");
        require(tokenOut >= minTokenOut, "slippage");

        minter.mint(address(this), tokenOut);
        totalBondedOhm += placed;
        totalMintedToken += tokenOut;
        _open(msg.sender, tokenOut);

        emit Bonded(msg.sender, ohmIn, placed, tokenOut, vests[msg.sender].end);
    }

    function claim() external returns (uint256 owed) {
        Vest storage v = vests[msg.sender];
        uint256 vestedNow = _vested(v);
        owed = vestedNow - v.claimed;
        require(owed > 0, "nothing vested");
        v.claimed = vestedNow;
        require(token.transfer(msg.sender, owed), "token out");
        emit Claimed(msg.sender, owed);
    }

    // ── views for the site ──
    function claimable(address u) external view returns (uint256) {
        Vest storage v = vests[u];
        return _vested(v) - v.claimed;
    }
    function locked(address u) external view returns (uint256) {
        Vest storage v = vests[u];
        return v.total - _vested(v);
    }
    /// preview of what `ohmIn` would mint right now (post-discount, post-gate, net of the 5% skim
    /// on the leg the hook sells, ~2.56% of the bond; before any partial fill)
    function quote(uint256 ohmIn) external view returns (uint256 tokenOut, bool gated) {
        (tokenOut, gated) = _quote(ohmIn);
        tokenOut = (tokenOut * hook.donationNetBps()) / 10_000;
    }

    function _open(address u, uint256 amt) internal {
        Vest storage v = vests[u];
        uint256 vestedNow = _vested(v);
        uint256 owed = vestedNow - v.claimed;
        if (owed > 0) {
            v.claimed = vestedNow;
            require(token.transfer(u, owed), "token out");
            emit Claimed(u, owed);
        }
        uint256 unvested = v.total - v.claimed;
        v.total = unvested + amt;
        v.claimed = 0;
        v.start = uint64(block.timestamp);
        v.end = uint64(block.timestamp + VEST);
    }

    function _vested(Vest storage v) internal view returns (uint256) {
        if (v.total == 0) return 0;
        if (block.timestamp >= v.end) return v.total;
        if (block.timestamp <= v.start) return 0;
        return (v.total * (block.timestamp - v.start)) / (v.end - v.start);
    }
}

lib/v4-core/src/libraries/FullMath.sol

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                assembly ("memory-safe") {
                    result := div(prod0, denominator)
                }
                return result;
            }

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

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly ("memory-safe") {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly ("memory-safe") {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly ("memory-safe") {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly ("memory-safe") {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly ("memory-safe") {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

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

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}
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.