Skip to content

psyto/princeps

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Princeps

Active development moved to psyto/rdk (2026-06-03). This repo is preserved as the public landing page for the 2026-06-01 launch announcement and the v0 lending demos referenced therein. The Princeps codebase now lives in the rdk monorepo under princeps/ (alongside the OpenHL ancestor and the shared rdk-* DeFi L1 primitives both apps consume).

The DeFi prime broker L1 on Reth.

Lending → options → structured products → institutional rails, on a single shared risk engine.

Princeps (Latin: "first, prime, principal") — pronounced PRIN-seps. The title Augustus adopted when founding the Roman Principate. Now: the prime broker stack for on-chain finance.


What it is

Princeps is an open-source, Reth-based L1 designed to be the DeFi-native counterpart of a TradFi prime broker. The kernel runs in two forms: as a public L1 deployment, and as an embeddable engine that third parties can lift into their own exchange or brokerage stack.

Where Hyperliquid reinvented perps by embedding the matching engine into the L1, and Tempo reinvented payments by embedding FX and auto-swap, Princeps reinvents the primitives that perps don't cover:

  • Lending — deterministic sub-second liquidations as state transitions (not keeper auctions), portfolio margin, native flash loans
  • Options — Black-Scholes / IV surfaces / Greeks as precompiles, auto-exercise at expiry block, vol surface as canonical state
  • Structured products — native vault/strategy composition over lending + options, continuous NAV, no keepers, native fee waterfalls
  • Institutional rails — KYC overlay for compliance-required tenants, native fund-admin primitives (NAV strip, attribution)

All four layers share one risk engine — so a strategy can sell a covered call, post the underlying as collateral, borrow against it, and rebalance — atomically, in a single block. That's the prime broker thesis.

Positioning

The L1 that's everything HL isn't. Princeps explicitly does not build perps; HL owns that. Princeps is the lending / options / structured-products / institutional-rails complement.

One-line pitch: "If HL is the on-chain CME, Princeps is the on-chain prime broker."

Three positions Princeps occupies that no existing project covers today:

  1. A DeFi-native unified prime brokerage engine, open-source. Commercial peers (Talos, Trumid, GFO-X) are closed-source institutional platforms; existing OSS matching engines cover only fragments. Princeps ships the first OSS reference of a unified cross-product risk engine — lending, perps, options, and structured products in one tree, callable via EVM precompiles. The kernel is reusable: third parties can embed the crates into their own exchange or prime brokerage stack.

  2. Lending + options + structured products on one L1 with a shared risk engine. Today these live in separate protocols across separate chains (Aave + Deribit + Pendle, or Drift + Derive + Sommelier). The prime broker thesis — atomic composability across products with one health number — has no L1-native incumbent. Caveat: if HyperEVM matures into a native multi-product DeFi layer, this position narrows.

  3. A Reth-based L1 specialized for DeFi trading. Tempo is Reth-based but payments-focused; Optimism, Base, and other Reth-using L2s are general-purpose. A Reth L1 purpose-built around the trading risk engine — funding, oracle, liquidation, cross-margin as state transitions — is, in practice, Princeps alone.

Roadmap

Version Scope Target
v0 Lending — single asset pair (USDC collateral, ETH borrow), deterministic liquidations, portfolio margin Q3 2026 testnet
Audit window ≥2 independent Web3 security audits of L1 kernel + lending precompiles; gates v1 mainnet, not v0 testnet Q1 2027
v1 Options — orderbook, vol surface, Greeks precompiles, cross-margin with lending; lending mainnet ships here Q2 2027
v2 Structured products — native vault composition, continuous NAV, Tempo settlement integration Q3 2027
v3 Institutional rails — KYC overlay (per-tenant opt-in), fund-admin primitives, decentralized sequencer H1 2028

The audit row is load-bearing: per ADR-008, the v0 → v1 transition is also the permissioned-validator-set → bonded-stake transition (ADR-009 forthcoming), and tokenomics design completion is a non-negotiable gate before any real money lands. v0 testnet itself can ship without an external audit because no real funds are at risk.

Architectural decisions (locked)

Seven foundational decisions, locked for the platform lifecycle:

ADR Decision Note
001 Consensus: Malachite (Informal Systems) BFT Instant finality, no reorgs
002 Sequencer: centralized v0–v1, decentralize at v3 Ship-fast, decentralize-later pattern
003 Oracle: validator-quorum push in EL Sub-second updates, no external oracle
004 Base unit: USD-stable (USDC default; USDT, Tempo-stable at v1+)
005 Settlement: standalone L1 v0–v1, Tempo settlement at v2
006 Identity: anon-default, KYC as Layer-3 per-tenant overlay at v3 Not chain-wide KYC
007 Token: none until real revenue Earliest consideration: post-v1
008 Pre-token validator policy: permissioned + legally bound until tokenomics ships Sunsets with ADR-009

Status

Princeps inherits a working Reth + Malachite kernel from openhl and extends it with the v0 lending kernel and the prime-broker portfolio engine. Fully functional as of 2026-06-03. 464 tests pass across 13 crates.

Built — kernel inherited from openhl (Stages 1–18a):

  • ✅ Consensus substrate (Reth + Malachite, 4-message bridge)
  • ✅ Two-validator devnet with real follower replication via ProposalAndParts
  • ✅ CLOB pure state machine
  • ✅ Custom EVM precompiles (CLOB read + place_order + fill sink + deposit + withdraw)
  • ✅ Funding state machine (per-block settlement applied to collateral)
  • ✅ Liquidation (margin math, insurance fund, multi-account scanner, ADL — full safety-net loop closed)
  • ✅ Oracle (median-of-medians + secp256k1-signed observations + publisher registry + cached aggregate persistence)
  • ✅ Vault primitive (share-based, ERC-4626-style)
  • ✅ Clearing (apply_fill state machine, bridge-owned account map, persistent across restarts)
  • ✅ Node coordinator + reth-devnet boot ceremony (persistent MDBX, validator key persistence, chain-spec loading, per-block integration tick)
  • ✅ Margin-aware withdraw with revert-safe precompile mutations (PrincepsRevertGuard)

Built — v0 lending kernel (Stages 19–22, shipped 2026-06-01):

  • princeps-lending crate — pure compute: market state, position state, kinked IRM, health factor compute, per-block interest accrual (61 tests across 5 modules)
  • ✅ Bridge integration — LiveRethEvmBridge owns BTreeMap<MarketId, Market> + BTreeMap<(AccountId, MarketId), Position> with with_*_mut accessors
  • ✅ Bridge mutation methods — lending_deposit_collateral / lending_borrow / lending_repay / lending_withdraw_collateral / lending_liquidate, with simulate-then-commit health gating
  • ✅ Per-block lending tick — lending_tick accrues interest across all registered markets; scan_lending_health flags HF < 1.0 positions
  • ✅ Six EVM precompiles at 0x0c1f0x0c24 — full lending lifecycle callable from any Solidity contract (see EVM precompiles below)
  • ✅ Unified perp+lending scan report — single liquidation surface across both products (Stage 22a)
  • ✅ Bad-debt absorption — bridge surfaces shortfall, PrincepsNode coordinator routes it into the InsuranceFund (Stage 22c, cross-layer)
  • ✅ Lending revert-guard — BridgeStateSnapshot extended to cover markets + positions for atomic precompile mutations

Built — v0 prime-broker portfolio engine (Stage 23, shipped 2026-06-03):

  • princeps-portfolio crate — unified cross-margin compute: one health number across lending collateral + lending debt + perp unrealized PnL + perp initial margin (14 tests)
  • ✅ Bridge unified-margin aggregator — LiveRethEvmBridge::compute_account_health joins per-account lending positions and perp state into a single PortfolioHealth
  • ✅ Portfolio-gated borrow/withdraw — borrow and withdraw_collateral now check portfolio free-equity (not just lending HF), so a losing perp shrinks lending capacity and vice versa
  • ✅ Cross-margin scenario test — same account, siloed view → liquidatable, unified portfolio view → healthy; the prime broker thesis demonstrated end-to-end

Built — v0 demo + observability (Stage 24, shipped 2026-06-03):

  • princeps lending-demo subcommand — runs Alice's canonical prime-broker scenario in ~1 second (deposit USDC → borrow ETH → open perp → market crash → siloed vs unified margin verdict)
  • princeps lending <subcommand> per-step CLI — init / deposit / borrow / repay / withdraw / health / scan / list against a local JSON state sandbox
  • princeps-lending-rpc-server — read-only HTTP JSON RPC for /lending/markets, /lending/positions, /lending/scan, /lending/health over an in-process bridge with 5 seeded accounts
  • princeps-liquidator-bot — sample liquidator (~200 lines) that seeds 5 accounts, raises ETH price, scans for underwater positions, liquidates most-underwater first, falls back to bad-debt absorption

Built — v0 lending genesis on the running node (Stage 24a, shipped 2026-06-03):

  • seed_v0_lending_markets / seed_v0_demo_accounts — fresh reth-devnet boots register the USDC/ETH market and seed 5 demo accounts (matching the liquidator-bot fixture) so the per-block hook fires against real lending state instead of an empty bridge
  • ✅ Lending prices wired into the per-block scan_unified (hardcoded (1, 1) for now; v1 will read from the oracle's lending feeds)

Built — multi-validator (N≥3) verified reproducibly (shipped 2026-06-03):

  • --validators JSON dial-list wiring (Stage 13l) confirmed N-agnostic; with_persistent_peers forwards peer multiaddrs into Malachite's libp2p config
  • validator-pubkey.hex sidecar written next to validator-key.json so external tooling can read pubkeys without parsing logs or reimplementing Ed25519
  • scripts/devnet-3.sh — one-command alice/bob/carol bring-up that wipes prior bridge/coordinator state, boots three reth-devnet processes in parallel against a shared validator set, and diffs the resulting coordinator snapshots to confirm byte-identical convergence

Next (remaining v0 work):

  • 🚧 Public testnet deploy — validator infra, monitoring, faucet

Architecture

bin/princeps
├── crates/
│   ├── types         # primitives: account/market/position IDs
│   ├── codec         # serialization (Reth ↔ Malachite)
│   ├── clob          # pure orderbook state machine
│   ├── funding       # funding rate state machine
│   ├── liquidation   # margin math + insurance fund + scanner + ADL
│   ├── oracle        # median-of-medians + signed observations
│   ├── vault         # share-based collateral pooling
│   ├── clearing      # settlement / clearing primitives
│   ├── lending       # market state, IRM, health factor, interest accrual (Stages 19-22)
│   ├── portfolio     # unified cross-margin compute: lending + perp → one health (Stage 23a)
│   ├── evm           # Reth EVM bridge + custom precompiles + portfolio aggregator
│   ├── consensus     # Malachite integration
│   └── node          # PrincepsNode coordinator (tick driver, bad-debt routing)

Pure / I-O split: state machines (types, codec, clob, funding, liquidation, oracle, vault, lending, portfolio) have no I/O — deterministic, microsecond unit tests. I/O boundary (evm, consensus, node) talks to the outside world.

Workspace defaults: edition 2024, resolver 3, rust 1.95+, unsafe_code = forbid, release LTO + abort + strip.

Pin policy: Reth v2.2.0, Malachite v0.5.0, alloy v1.5 / v2.0 — release-tag SHAs only, dedicated PR per bump.

Quickstart

# Build
cargo build --release

# >>> START HERE: cross-margin demo (Stage 24b) <<<
# Runs Alice's canonical prime-broker scenario in ~1 second:
# deposit USDC → borrow ETH → open perp → market crash → show siloed vs unified margin
cargo run --release -- lending-demo
# Try different crash prices:
cargo run --release -- lending-demo --eth-crash-price 85

# Sample liquidator bot (Stage 24e) — seeds 5 accounts, raises ETH price,
# scans for underwater positions, liquidates them in order of most-underwater,
# falls back to bad-debt absorption when collateral can't cover.
cargo run --release --bin princeps-liquidator-bot
cargo run --release --bin princeps-liquidator-bot -- --eth-price 3

# HTTP RPC server (Stage 24d) — read-only JSON endpoints over an in-process
# bridge with the same 5 seeded accounts. Then in another terminal:
#   curl http://localhost:8080/lending/markets
#   curl http://localhost:8080/lending/positions
#   curl 'http://localhost:8080/lending/scan?perp_mark=0&perp_im_bps=0&coll_price=1&debt_price=2'
#   curl 'http://localhost:8080/lending/health?account=1&perp_mark=0&perp_im_bps=0&coll_price=1&debt_price=2'
cargo run --release --bin princeps-lending-rpc-server

# Per-step lending CLI (Stage 24c) — hands-on lending against a local JSON
# state sandbox at $HOME/.princeps/lending-state.json. Each command persists
# its mutation; perfect for exploration without writing Rust.
cargo run --release --bin princeps -- lending init
cargo run --release --bin princeps -- lending deposit 1 1000
cargo run --release --bin princeps -- lending borrow 1 200 --eth-price 1
cargo run --release --bin princeps -- lending list
cargo run --release --bin princeps -- lending health 1 --eth-price 6   # LIQUIDATABLE
cargo run --release --bin princeps -- lending scan --eth-price 6
cargo run --release --bin princeps -- lending repay 1 100

# Single-validator devnet (in-memory bridge)
cargo run --release -- devnet 1

# Single-validator devnet with real Reth EVM
cargo run --release -- reth-devnet 1 --moniker dev0

# Multi-validator scaffolding
cargo run --release -- reth-devnet 1 \
  --chain-spec ./chain.json \
  --validators ./validators.json \
  --listen-addr /ip4/0.0.0.0/tcp/26656 \
  --rpc-bind 0.0.0.0:8545

Data and validator key default to $HOME/.princeps/data and $HOME/.princeps/validator_key.json (perms 0o600).

The lending-demo subcommand is the fastest way to see what Princeps does. It produces:

            View                       Free equity       Verdict
            Siloed (perp only)                -140       LIQUIDATABLE
            Unified (perp + lending)           360       HEALTHY

Same account, two ways of computing margin. Siloed → forced liquidation. Unified portfolio (the prime broker thesis) → position stays open because the lending collateral backs the perp position.

EVM precompiles

Princeps reserves the 0x0000...0c1* address range for custom precompiles. Any Solidity contract can call them via standard call / staticcall.

Address Precompile Stage
0x...0c1b clob_read_best_bid 9b
0x...0c1c clob_place_order 9c
0x...0c1d princeps_deposit (perp collateral in) 17c
0x...0c1e princeps_withdraw (perp collateral out, margin-aware) 17e+
0x...0c1f princeps_lending_deposit_collateral 21a
0x...0c20 princeps_lending_borrow 21b
0x...0c21 princeps_lending_repay 21c
0x...0c22 princeps_lending_withdraw_collateral 21d
0x...0c23 princeps_lending_health (staticcall-safe) 21e
0x...0c24 princeps_lending_liquidate 22b

ABI for lending precompiles: (uint64 account, uint32 market_id, uint128 amount [, uint128 collateral_price, uint128 debt_price]) returning uint256 (success indicator or computed value in low 16 bytes). The borrow/withdraw/health/liquidate precompiles require prices passed in calldata; v1 will switch to an installed oracle global. See crates/evm/src/precompiles/mod.rs for exact shapes per precompile.

Related projects

By the same author, separate independent projects worth knowing about:

  • openhl — open-source HL reference implementation. Princeps's code ancestor (Princeps is a fresh fork without shared git history; openhl continues as its own project).
  • rethlab — Reth and perp DEX learning lab. 19 courses on the Reth stack, REVM, and perp internals. Not Princeps-specific, but covers most of the foundations Princeps is built on.

License

Apache 2.0 — see LICENSE.

Contributing & embedding

Princeps is currently a solo build; external contribution model will be defined post-v0 ship.

The kernel is designed to be embeddable. The pure state machines — types, codec, clob, funding, liquidation, oracle, vault, lending, portfolio — have no I/O and can be lifted into any execution environment (a third-party L1, a CEX matching engine, a prime broker risk system). The I/O crates (evm, consensus, node) are the public L1 deployment; downstream users can replace them with their own integration layer. Apache 2.0 throughout.

Contact


Princeps is bootstrapped solo by Hiroyuki Saito. Open-source from day one. No token. No raise. Built on the openhl reference implementation.

About

The DeFi prime broker L1 on Reth. Lending → options → structured products → institutional rails.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors