Nexus Protocol
Technical Documentation · v1.0 · Chain ID 420420417
Nexus is a fully on-chain perpetuals exchange on Polkadot Hub Testnet. Trade BTC and ETH up to 50× leverage — no off-chain order books, no trusted operators.
Five layers: Vault for capital · Trading Engine for positions · Risk Engine for liquidations · Oracle for prices · Cross-Chain via CCIP.
Network
Polkadot Hub Testnet
Chain ID
420420417
RPC
polkadothub-rpc.com
Explorer
blockscout-passet-hub
Single-Vault
All LP liquidity and trader collateral in PerpsVault.
Open Keepers
Any address calls batchLiquidate and earns 10% reward.
Polkadot Native
Deployed on Polkadot Hub EVM-compatible parachain.
Live Prices
Oracle auto-updated every 2 min via Binance WebSocket.
18-Dec Math
DECIMALS_SCALAR normalises USDC (6 dec) to 1e18.
Cross-Chain
CrossChainRouter + MessageReceiver for full CCIP.
System Architecture
Five-layer composable design
Capital deposits into PerpsVault, locking on position open via PositionManager.PriceOracle validates freshness every call. PnLCalculator checks position health. Below liquidation threshold, LiquidationEngine is open to any caller in the world.
Vault Layer
PerpsVault.sol
└─ LP Shares
└─ Collateral Lock
└─ settleTrade
Trading Engine
PositionManager.sol
└─ ISOLATED / CROSS
└─ Market + Limit
└─ Cross-Chain
Risk Engine
LiquidationEngine.sol
└─ Batch (max 20)
└─ Keeper Rewards
└─ Rescue Guard
Oracle & Math
PriceOracle.sol
└─ PnLCalculator.sol
└─ MockAggregatorV3
└─ Heartbeat Guard
Cross-Chain
CrossChainRouter.sol
└─ MessageReceiver.sol
└─ CCIP Pipeline
└─ Nonce Dedup
Price Keeper
PriceKeeper.sol
└─ Binance feed
└─ Auto 2-min push
└─ 60s cooldown
Contract Addresses
Polkadot Hub Testnet · Chain ID 420420417
blockscout-passet-hub.parity-testnet.parity.io — all contracts verified on-chain.PerpsVault
The capital layer — all funds live here
PerpsVault.sol holds every dollar — LP liquidity and trader margin. Single vault, dual accounting, auditable solvency from one slot. LP funds cannot silently cover trader losses.
LP Liquidity Engine
LPs call addLiquidity(). Formula: shares = (amount × totalSupply) / totalAssets. First deposit permanently burns MINIMUM_LIQUIDITY (1,000) to address(0) — blocks share-price inflation attacks forever.
Trader Collateral
Traders call deposit(). USDC scaled to 18 dec via DECIMALS_SCALAR. All margin checks happen in PositionManager before any capital moves.
lockCollateral, unlockCollateral, settleTrade, transferByManager — all gated. No backdoor exists.Trade Settlement
settleTrade(trader, locked, pnl) atomically applies PnL and returns net payout. LP absorbs losses, pays profits — zero-sum, single transaction.
scaledAmount % DECIMALS_SCALAR != 0 reverts on every withdrawal path. Eliminates fractional-wei drain exploits from the 6→18 decimal boundary.PositionManager
Sole contract with vault write access
Every trader action routes here. Position struct: collateral, leverage, entryPrice, isLong, isOpen, isCrossChain, marginMode.
Margin Modes
ISOLATED
Each position's margin is ring-fenced. Only that position is at risk on liquidation.
CROSS
All free collateral shared across positions — higher leverage, cascade risk.
Market Orders
openPosition(token, collateral, leverage, isLong, mode) — queries oracle, validates leverage, locks collateral, writes Position struct — all atomic and nonReentrant.
Limit Orders
placeLimitOrder() locks full collateral immediately — no unfunded orders possible. Any caller executes at target price and earns 0.1% of collateral as keeper incentive.
Cross-Chain Execution
executeCrossChainTrade() gated to crossChainReceiver. If open fails after collateral arrives, full amount credited to trader's free balance — funds never silently lost.
LiquidationEngine
Open keeper model — any address, 10% reward
No privileged admin. Any address calls batchLiquidate() and earns 10% per successful liquidation. Competitive keeper market, no single point of failure.
Batch Processing
Keeper Rewards
Rewards forwarded atomically at batch end — no intermediate custodian.
rescueTokens() reverts unconditionally for PROTOCOL_ASSET — even a compromised owner cannot drain rewards.PriceOracle + PriceKeeper
Mock feeds auto-synced via Binance
PriceOracle.sol wraps MockAggregatorV3 for 18-decimal prices with staleness guards.PriceKeeper auto-pushes Binance prices on-chain every 2 minutes from the frontend — no server needed.
PnLCalculator
Pure library — no state, no ownership
Stateless pure library. Centralised arithmetic prevents rounding divergence between PositionManager and LiquidationEngine. All inputs validated before multiplication.
PerpsErrors
Centralised custom error registry
CrossChainRouter
Source chain — initiates trade flow
Encodes trade params + collateral into CCIP message, validates target chain allowlist, sends to MessageReceiver.
MessageReceiver
Executes on Polkadot Hub
Decodes payload → deposits USDC → calls executeCrossChainTrade. Sender allowlist keyed by (sourceChain, senderAddress).
Test Suite
95 tests · 0 failures · Foundry
Security Model
Defense-in-depth on every surface
Local Setup
Foundry + Next.js 16
Smart Contracts
Frontend
Network config
Frontend Stack
Next.js 16 · zero backend reads
Framework
Next.js 16 · App Router
Blockchain
Wagmi v2 · Viem
Wallet UI
RainbowKit · MetaMask · OKX
Charts
TradingView · Binance WS
Animations
Framer Motion · CSS
Network
Polkadot Hub (420420417)