Skip to main content

System Architecture

Sable is a full-stack DeFi application combining a Next.js frontend, Cairo smart contracts, and integrations with 8+ external protocols on StarkNet.

High-Level Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                            USER BROWSER                                │
│  ┌─────────────┐  ┌──────────────┐  ┌───────────┐  ┌───────────────┐  │
│  │ Argent       │  │ Braavos      │  │ WalletCo- │  │  Local Note   │  │
│  │ Wallet       │  │ Wallet       │  │ nnect     │  │  Storage      │  │
│  └──────┬───────┘  └──────┬───────┘  └─────┬─────┘  └───────┬───────┘  │
│         └──────────────────┴───────────────┬┘                │          │
│                                            │                 │          │
│  ┌─────────────────────────────────────────┴─────────────────┴───────┐  │
│  │                    NEXT.JS 16 FRONTEND (App Router)               │  │
│  │                                                                   │  │
│  │  Pages:  /  /vault/[id]  /privacy  /dca  /cdp  /stake  /bridge   │  │
│  │          /portfolio                                                │  │
│  │                                                                   │  │
│  │  ┌─────────────────────────────────────────────────────────────┐  │  │
│  │  │                    REACT HOOKS LAYER                        │  │  │
│  │  │                                                             │  │  │
│  │  │  use-vault-data    use-vault-contract   use-shielded-vault  │  │  │
│  │  │  use-dca           use-cdp              use-staking         │  │  │
│  │  │  use-bridge        use-private-swap                         │  │  │
│  │  └──────────────────────────┬──────────────────────────────────┘  │  │
│  │                             │                                     │  │
│  │  ┌──────────────────────────┴──────────────────────────────────┐  │  │
│  │  │                    LIB / API LAYER                          │  │  │
│  │  │                                                             │  │  │
│  │  │  api/vaults    api/vesu     api/avnu    api/price           │  │  │
│  │  │  api/onchain   api/oneclick api/defillama                   │  │  │
│  │  │  privacy/note  privacy/prover  privacy/merkle               │  │  │
│  │  │  constants     format       rpc         abi/                │  │  │
│  │  └──────────────────────────┬──────────────────────────────────┘  │  │
│  └─────────────────────────────┼─────────────────────────────────────┘  │
│                                │                                        │
│  ┌─────────────────────────────┴──────────────────────────────────────┐ │
│  │                 NEXT.JS API ROUTES (Server-Side)                   │ │
│  │  /api/curator  /api/relayer/*  /api/dca/*  /api/shielded-deposit  │ │
│  │  /api/staking  /api/execute-outside                                │ │
│  └─────────────────────────────┬──────────────────────────────────────┘ │
└────────────────────────────────┼────────────────────────────────────────┘

                    ┌────────────┴────────────┐
                    │    STARKNET MAINNET     │
                    │                         │
  ┌─────────────────┼─────────────────────────┼──────────────────────┐
  │                 │   SABLE CONTRACTS       │                      │
  │  ┌──────────┐  │  ┌──────────────────┐   │  ┌───────────────┐   │
  │  │ Sentinel │  │  │ Shielded Pool V4 │   │  │   DCA         │   │
  │  │ Citadel  │  │  │ (Groth16 ZK)     │   │  │   Contract    │   │
  │  │ Trident  │  │  ├──────────────────┤   │  ├───────────────┤   │
  │  │ Delta    │  │  │ Swap Pool        │   │  │   CDP         │   │
  │  │ Turbo    │  │  │ (Private Swaps)  │   │  │   Contract    │   │
  │  │ Apex     │  │  ├──────────────────┤   │  ├───────────────┤   │
  │  │          │  │  │ Stablecoin Vault │   │  │  Groth16      │   │
  │  │ (ERC4626)│  │  │ (Private USDC)   │   │  │  Verifier     │   │
  │  └────┬─────┘  │  └──────────────────┘   │  └───────────────┘   │
  │       │        │                          │                      │
  └───────┼────────┼──────────────────────────┼──────────────────────┘
          │        │                          │
  ┌───────┴────────┴──────────────────────────┴──────────────────────┐
  │                    EXTERNAL PROTOCOLS                            │
  │                                                                  │
  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────────┐ │
  │  │  Vesu    │  │  Ekubo   │  │  Endur   │  │  Nostra          │ │
  │  │ Lending  │  │ AMM/LP   │  │ Staking  │  │  CDP Lending     │ │
  │  └──────────┘  └──────────┘  └──────────┘  └──────────────────┘ │
  │  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────────┐ │
  │  │  AVNU   │  │  Pragma  │  │  Garaga  │  │ NEAR 1-Click     │ │
  │  │ DEX Agg │  │  Oracle  │  │ ZK Proof │  │ Bridge/Intents   │ │
  │  └──────────┘  └──────────┘  └──────────┘  └──────────────────┘ │
  └──────────────────────────────────────────────────────────────────┘

Data Flow

User interactions flow through multiple layers:
User Wallet ──► Frontend (React) ──► Hooks ──► StarkNet RPC ──► Smart Contracts
                     │                  │
                     │                  └──► External APIs (Vesu, AVNU, CoinGecko)

                     └──► API Routes (Server) ──► Relayer / Curator / Keeper

Example: Vault Deposit Flow

1. User clicks "Deposit 0.001 WBTC" on /vault/sentinel
2. Frontend calls use-vault-contract.ts hook
3. Hook constructs StarkNet transaction:
   - approve(WBTC, SENTINEL_ADDRESS, amount)
   - deposit(amount, receiver)
4. User signs with Argent X / Braavos
5. Transaction broadcast to StarkNet RPC
6. Sentinel vault contract:
   - Transfers WBTC from user
   - Mints share tokens to user
   - Emits Deposit event
7. Frontend polls for transaction receipt
8. UI updates with new balance

Frontend Stack

Core Technologies

LayerTechnologyVersionPurpose
FrameworkNext.js16.1.6App Router, RSC, API routes
UI LibraryReact19.2.3Component rendering
LanguageTypeScript5.xType safety
StylingTailwind CSS4.xUtility-first CSS
AnimationsMotion12.6.3Smooth transitions
ChartsRecharts2.15.3APY/TVL visualizations
StarkNet Clientstarknet.js8.1.2Contract interactions
Wallet Integration@starknet-react/core5.0.3Wallet providers

Key Dependencies

{
  "starknet": "^8.1.2",
  "@starknet-react/core": "^5.0.3",
  "snarkjs": "^0.7.6",
  "circomlibjs": "^0.1.7",
  "garaga": "^1.0.1",
  "recharts": "^2.15.3",
  "motion": "^12.6.3"
}

Application Structure

src/
├── app/                          # Next.js App Router
│   ├── page.tsx                  # Vault listing
│   ├── vault/[id]/page.tsx       # Vault detail
│   ├── privacy/page.tsx          # Shielded vaults
│   ├── dca/page.tsx              # Dollar-cost averaging
│   ├── cdp/page.tsx              # CDP management
│   ├── stake/page.tsx            # Direct staking
│   ├── bridge/page.tsx           # Cross-chain bridge
│   └── api/                      # Server-side endpoints
├── components/                   # React components
├── hooks/                        # Custom React hooks
├── lib/
│   ├── api/                      # External API clients
│   ├── privacy/                  # ZK proof generation
│   ├── abi/                      # Contract ABIs
│   └── constants.ts              # Addresses & config
└── providers/
    └── starknet.tsx              # Wallet providers

Smart Contract Stack

Technologies

ComponentTechnologyVersion
LanguageCairo2.14.0
CompilerScarb2.13.1
BlockchainStarkNetMainnet
StandardERC-4626Tokenized vaults
ZK VerifierGaraga1.0.1

Contract Inventory

All vault contracts implement the ERC-4626 tokenized vault standard:
ContractFileStrategyLOC
Sentinelsentinel.cairoPure Vesu PRIME lending~500
Citadelcitadel.cairoEndur staking + Vesu lending~600
Tridenttrident.cairo3x recursive staking loop~700
Delta Neutraldelta_neutral.cairoCollateral → borrow USDC → deploy~800
Turbobtcvault.cairoLeverage loop (deposit → borrow → swap → repeat)~900
Apexapex.cairo40% lending + 35% LP + 25% staking~1000
All vaults expose:
  • deposit(assets, receiver) -> shares
  • withdraw(assets, receiver, owner) -> shares
  • total_assets() -> uint256
  • convert_to_shares(assets) -> shares
  • convert_to_assets(shares) -> assets
Zero-knowledge proof contracts for shielded deposits/withdrawals:
ContractFileProof SystemStatus
Shielded Pool V4shielded_pool_v4.cairoGroth16 BN254 (7 public inputs)Current
Shielded Pool V3shielded_pool_v3.cairoGroth16 BN254 (6 public inputs)Legacy
Shielded Swap Poolshielded_swap_pool.cairoGroth16 BN254Current
Stablecoin Vaultstablecoin_vault.cairoGroth16 BN254Current
Verifier Addresses:
  • V4 Verifier: 0x03329c4d5c2e37dfd20d46c3c20be9230b2152c71947ead441c342d989d52ffa
  • V3 Verifier: 0x041011d7912b6759f2fe3cc66a1f746b81ec012c2774adabc77eecc299e0878d
ContractFilePurposeLOC
DCAdca.cairoRecurring orders with Mayer Multiple strategy~600
CDPcdp.cairoWBTC → USDC borrowing via Nostra~500

ERC-4626 Vault Mechanics

All vaults follow the ERC-4626 standard:
// Deposit WBTC, receive shares
fn deposit(assets: u256, receiver: ContractAddress) -> u256 {
    // Transfer WBTC from caller
    IERC20(wbtc).transferFrom(caller, vault, assets);
    
    // Calculate shares to mint
    let shares = convert_to_shares(assets);
    
    // Mint shares to receiver
    _mint(receiver, shares);
    
    shares
}

// Withdraw WBTC, burn shares
fn withdraw(assets: u256, receiver: ContractAddress, owner: ContractAddress) -> u256 {
    // Calculate shares to burn
    let shares = convert_to_shares(assets);
    
    // Burn shares from owner
    _burn(owner, shares);
    
    // Unwind strategy positions if needed
    _unwind_strategy(assets);
    
    // Transfer WBTC to receiver
    IERC20(wbtc).transfer(receiver, assets);
    
    shares
}

// Share price increases as yield accrues
fn convert_to_assets(shares: u256) -> u256 {
    (shares * total_assets()) / total_supply()
}

Protocol Integrations

Vesu V2 — Lending/Borrowing

Role: Primary yield source for all vaults Contract: 0x000d8d6dfec4d33bfb6895de9f3852143a17c6f92fd2a21da3d6924d34870160 Integration Points:
  • Supply WBTC to PRIME pool (Sentinel, Turbo)
  • Supply xWBTC to Re7 xBTC pool (Citadel)
  • Borrow USDC against WBTC collateral (Delta Neutral, Turbo)
  • Stake WBTC directly via /stake page
Data Flow:
Sable Vault ──► Vesu Singleton.supply(pool_id, WBTC, amount)
            ◄── vToken minted (interest-bearing)
            ──► Accrues APY from borrowers
            ──► Earns STRK from BTCFi Season (100M STRK)

AVNU — DEX Aggregation

Role: Optimal swap routing for DCA and vault strategies Contract: 0x04270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f Integration Points:
  • DCA execution (USDC/ETH/STRK → WBTC)
  • Turbo leverage loop (borrowed USDC → WBTC)
  • Private swap output (WBTC → ETH/USDC/STRK)
API Usage:
// Get quote
const quote = await fetch('https://starknet.api.avnu.fi/swap/v2/quotes', {
  params: {
    sellTokenAddress: TOKENS.USDC.address,
    buyTokenAddress: TOKENS.WBTC.address,
    sellAmount: '10000000', // 10 USDC
  }
});

// Build swap transaction
const build = await fetch('https://starknet.api.avnu.fi/swap/v2/build', {
  body: { quoteId: quote.quoteId, takerAddress: userAddress }
});

Ekubo — Concentrated Liquidity

Role: LP provision for Apex vault (35% allocation) Integration Points:
  • Provide liquidity to WBTC-ETH or WBTC-USDC pools
  • Earn trading fees from concentrated liquidity positions
  • Auto-compound fees back into LP positions

Endur — Liquid Staking

Role: Liquid staking yield for Citadel, Trident, and Apex vaults Integration Points:
  • Stake WBTC → receive xWBTC (liquid staking token)
  • xWBTC accrues staking yield automatically
  • Supply xWBTC to Vesu for dual yield (staking + lending)
Flow:
WBTC ──► Endur.stake() ──► xWBTC (1:1.05 ratio)
                         ──► Ratio increases over time
                         ──► Redeem xWBTC for more WBTC than deposited

Nostra — CDP Lending

Role: Backend for Sable CDP contract Contract: 0x073f6addc9339de9822cab4dac8c9431779c09077f02ba7bc36904ea342dd9eb Integration Points:
  • Deposit WBTC as collateral (iWBTC-c token)
  • Borrow USDC against collateral (dUSDC token)
  • Repay debt and withdraw collateral
Tokens:
  • iWBTC-c: 0x05b7d301fa769274f20e89222169c0fad4d846c366440afc160aafadd6f88f0c
  • dUSDC: 0x063d69ae657bd2f40337c39bf35a870ac27ddf91e6623c2f52529db4c1619a51

Pragma — Price Oracle

Role: Price feeds for DCA Mayer Multiple and CDP liquidation calculations Contract: 0x02a85bd616f912537c50a49a4076db02c00b29b2cdc8a197ce92ed1837fa875b Integration Points:
  • BTC/USD spot price
  • 200-day Time-Weighted Average Price (TWAP)
  • Mayer Multiple = spot_price / twap_200d

Garaga — ZK Verification

Role: On-chain Groth16 BN254 proof verification Integration Points:
  • Verify shielded deposit proofs
  • Verify shielded withdrawal proofs
  • Poseidon hash function for commitments/nullifiers
Verifier Contract (V4): 0x03329c4d5c2e37dfd20d46c3c20be9230b2152c71947ead441c342d989d52ffa Proof Structure:
Public Inputs (7):
- root: Merkle root
- nullifierHash: Prevents double-spend
- recipient: Withdrawal address
- relayer: Relayer address for fee
- fee: Relayer fee amount
- batchStart: Batch starting index
- batchSize: Number of deposits in batch

Private Inputs:
- secret: Random 31 bytes
- nullifier: Random 31 bytes
- pathElements: Merkle proof path
- pathIndices: Merkle proof indices

NEAR Intents / 1-Click — Cross-Chain Bridge

Role: Bridge assets to/from StarkNet Supported Chains: Solana, Ethereum, Base, Arbitrum, Polygon, Avalanche, NEAR Integration Points:
  • Bridge IN: External chain → StarkNet (receive STRK/WBTC/ETH)
  • Bridge OUT: StarkNet → External chain (send STRK, receive native tokens)
API Flow:
// 1. Get quote (dry run)
const quote = await fetch('1click-api/quote', {
  body: { sourceChain, destChain, amount, dryRun: true }
});

// 2. Create order
const order = await fetch('1click-api/quote', {
  body: { sourceChain, destChain, amount, dryRun: false }
});

// 3. User deposits to generated address
// 4. Poll status
const status = await fetch(`1click-api/order/${orderId}`);

Security Considerations

Smart Contract Security

  • All contracts compiled with Cairo 2.14.0 (stable)
  • ERC-4626 standard implementation reduces attack surface
  • Ownable pattern: only curator can call deploy_idle()
  • Upgradeable via UUPS pattern (owner can upgrade implementation)
  • Flash loan protection: reentrancy guards on deposit/withdraw

ZK Privacy Security

  • Groth16 proofs verified on-chain via Garaga (audited)
  • Poseidon hash function (StarkNet-native, efficient)
  • Nullifier prevents double-spend (stored on-chain)
  • Merkle tree commitments (depth 20 = ~1M deposits supported)
  • Notes stored locally in browser (losing note = losing funds)

Frontend Security

  • No private keys stored client-side
  • All transactions signed via wallet extension
  • Contract addresses hardcoded in constants.ts
  • RPC endpoints: Lava (free) or user-provided Alchemy
  • CORS protected API routes for curator/relayer operations

Performance Optimizations

Frontend

  • Next.js 16 App Router with React Server Components
  • Turbopack for instant hot reload in dev
  • Static generation for vault listing page
  • Dynamic imports for ZK proof WASM (~4MB)
  • 30-second cache on price API calls

Smart Contracts

  • Batch deposits (3 at a time) reduce Merkle tree update gas
  • Flash loans for atomic unwind of complex positions
  • Lazy deployment: idle funds not deployed until deploy_idle() called
  • Packed storage for gas efficiency

Monitoring & Analytics

On-Chain Data

  • All transactions visible on Voyager and Starkscan
  • Deployer account: 0x0007842590942b769a203cfcb07540299b86e22ba05b6708b516ec04ca044ef7 (408+ txs)
  • Tester account: 0x0362A762F25f0aa9C3935D4D11D5d5099262E4fF59f5D360d37BD157fBC3ABbc (98+ txs)

APY Calculation

APY is calculated from multiple sources:
// Example: Sentinel APY
const sentinelAPY = 
  vesuPrimeAPY +           // Base lending APY (from Vesu API)
  btcfiSTRKRewards +       // STRK rewards APY (100M STRK program)
  0;                       // No additional yield

// Example: Apex APY
const apexAPY =
  (0.40 * vesuLeverageAPY) +   // 40% allocation to leverage lending
  (0.35 * ekuboLPAPY) +         // 35% allocation to Ekubo LP
  (0.25 * endurStakingAPY);     // 25% allocation to Endur staking

Development Workflow

Local Development

# Install dependencies
npm install

# Run dev server (Turbopack)
npm run dev

# Build for production
npm run build
npm start

# Compile Cairo contracts
cd contracts
scarb build

Contract Deployment

# Declare + deploy new contract
node contracts/scripts/deploy.mjs

# Upgrade existing contract
node contracts/scripts/upgrade.mjs

Running Keeper Bot

# Execute due DCA orders
node scripts/dca_keeper.mjs

Additional Resources

Smart Contracts

Detailed documentation on each Cairo contract

API Reference

REST API endpoints for curator, relayer, and keeper operations

Privacy Deep Dive

How zero-knowledge proofs enable shielded transactions

GitHub Repository

View full source code and contribute

Build docs developers (and LLMs) love