Skip to content

NexTechArchitect/nexus-protocol-v2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

12 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

On-Chain Perpetuals Infrastructure

Polkadot Hub Testnet ยท Non-Custodial ยท 50ร— Leverage


License Foundry Network Chain CCIP


A fully on-chain perpetuals exchange deployed on Polkadot Hub Testnet.
Mock Chainlink price feeds ยท Binance live prices ยท CCIP cross-chain margin ยท 50ร— leverage.




๐Ÿš€ Live App ย ยทย  ๐Ÿ’ป Source Code ย ยทย  ๐Ÿ“œ Docs ย ยทย  ๐Ÿšฐ Get Testnet PAS

Short.Demo.mp4

๐ŸŽฏ What Makes Nexus Different

Problem With Existing Protocols Nexus Solution
Oracle manipulation via thin markets MockAggregatorV3 with per-asset heartbeat staleness guards
Liquidity fragmented across chains CCIP cross-chain margin relay with nonce replay protection
Custodial bridges introduce counterparty risk All collateral lives in PerpsVault.sol โ€” non-custodial, on-chain
LP inflation attacks on first deposit MINIMUM_LIQUIDITY = 1000 shares permanently burned on genesis deposit
Dust sweep / precision drain scaledAmount % DECIMALS_SCALAR != 0 enforced on every withdrawal
Stale oracle prices Binance WebSocket drives live PnL; entry price saved locally at trade execution

๐Ÿ“‘ Table of Contents

  1. ๐Ÿ›๏ธ Architecture
  2. โœ… Deployed Contracts
  3. ๐Ÿงฉ Contract Reference
  4. ๐Ÿ’ป Frontend Stack
  5. ๐Ÿงช Test Suite & Coverage
  6. ๐Ÿ› ๏ธ Local Setup
  7. ๐Ÿ” Security Model

๐Ÿ›๏ธ Architecture

Five isolated protocol layers. A failure in cross-chain routing cannot affect vault solvency. The oracle layer is fully stateless with zero write access to core contracts.

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                        USER / DAPP                               โ”‚
โ”‚         RainbowKit ยท Wagmi v2 ยท Viem ยท Next.js 15 App Router     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                            โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                      TRADING ENGINE                              โ”‚
โ”‚   PositionManager.sol  ยท  PnLCalculator.sol  ยท  LiquidationEngineโ”‚
โ”‚   Market & limit orders ยท Isolated/Cross margin ยท Batch keepers  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
             โ”‚                                 โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”       โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚      VAULT LAYER        โ”‚       โ”‚        ORACLE LAYER            โ”‚
โ”‚   PerpsVault.sol        โ”‚       โ”‚   PriceOracle.sol              โ”‚
โ”‚   18-dec precision      โ”‚       โ”‚   MockAggregatorV3 (BTC+ETH)   โ”‚
โ”‚   LP share system       โ”‚       โ”‚   Heartbeat staleness guard    โ”‚
โ”‚   settleTrade / PnL     โ”‚       โ”‚   Binance WS live prices       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜       โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
             โ”‚
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                  CROSS-CHAIN LAYER  (CCIP)                      โ”‚
โ”‚   CrossChainRouter.sol โ”€โ”€ encodes & sends trade requests        โ”‚
โ”‚   MessageReceiver.sol  โ”€โ”€ decodes, deduplicates nonce, executes โ”‚
โ”‚   Source chain + sender whitelist ยท try/catch pipeline safety   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Core Design Invariants

1. No off-chain trust โ€” Price discovery, execution, liquidation, settlement โ€” all fully on-chain.

2. 18-decimal precision throughout โ€” DECIMALS_SCALAR = 10^(18 - tokenDecimals) normalizes USDC (6 dec) to 1e18 internally.

3. Vault solvency is an invariant โ€” 128 runs ร— 50 calls = 6,400 randomized state mutations, zero reverts.

4. Isolated margin by default โ€” Cross-margin mode uses _calculateGlobalPnL iterating all active positions.


โœ… Deployed Contracts

All contracts deployed on Polkadot Hub Testnet (Chain ID: 420420417).

Explorer: blockscout-passet-hub.parity-testnet.parity.io
RPC: services.polkadothub-rpc.com/testnet

Core Trading Engine

Contract Address
PositionManager 0xd16150d0B2a04ECb1Aa09f840556347D5251fB53
PerpsVault 0x9495fE47049a7aFe8180E9e8Aee743D533c67173
LiquidationEngine 0x01721d6502547faFD3049BE60b1485B12407f58B
PriceOracle 0x7C002F51B8D4F06275D43cFD1F15EcbFE7A52803
PriceKeeper 0x481EC593F7bD9aB4219a0d0A185C16F2687871C2

Oracle Feeds & Assets

Asset Address Notes
MockUSDC 0xDFdb18430C5C5C1EB4F9Abd69a78952f9BC3Afab 6-decimal collateral
MockWETH 0xE3579516aeB339A4a8624beadaE256619E77F61E Test asset
MockWBTC 0x20e9D3Ef17753EC0a0349eA7e26c8B8fd2B1A119 Test asset
ETH Feed 0xCbE91D0b302d4eD146eE0CFfbe0d23E93e655d94 MockAggregatorV3
BTC Feed 0xf3878A726cF855EDF11C8aCbA38bEBd817fa9F23 MockAggregatorV3

Cross-Chain (CCIP)

Contract Address
CrossChainRouter 0x8768d7470681a81caeA781285c9478dFDD7312e9
MessageReceiver 0xdcd169ca4Ab081C1B926Dc56430ADa8fE1E10A64

๐Ÿงฉ Contract Reference

Repository Structure

nexus-polka-perps/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ core/
โ”‚   โ”‚   โ”œโ”€โ”€ PositionManager.sol        # Trading engine: market/limit/liquidate/cross-chain
โ”‚   โ”‚   โ”œโ”€โ”€ PerpsVault.sol             # Collateral & LP vault (18-dec precision)
โ”‚   โ”‚   โ””โ”€โ”€ LiquidationEngine.sol      # Keeper-compatible batch liquidator
โ”‚   โ”œโ”€โ”€ math/
โ”‚   โ”‚   โ””โ”€โ”€ PnLCalculator.sol          # Pure library: PnL, liquidation health, overflow guards
โ”‚   โ”œโ”€โ”€ oracles/
โ”‚   โ”‚   โ””โ”€โ”€ PriceOracle.sol            # MockAggregatorV3 wrapper + heartbeat staleness
โ”‚   โ”œโ”€โ”€ mocks/
โ”‚   โ”‚   โ”œโ”€โ”€ MockAggregatorV3.sol       # Chainlink-compatible mock feed
โ”‚   โ”‚   โ”œโ”€โ”€ PriceKeeper.sol            # Permissioned price updater (60s cooldown)
โ”‚   โ”‚   โ”œโ”€โ”€ MockUSDC.sol
โ”‚   โ”‚   โ”œโ”€โ”€ MockWBTC.sol
โ”‚   โ”‚   โ””โ”€โ”€ MockWETH.sol
โ”‚   โ”œโ”€โ”€ cross-chain/
โ”‚   โ”‚   โ”œโ”€โ”€ CrossChainRouter.sol       # CCIP message sender + fee estimation
โ”‚   โ”‚   โ””โ”€โ”€ MessageReceiver.sol        # CCIP receiver + nonce dedup + try/catch execution
โ”‚   โ”œโ”€โ”€ account-abstraction/
โ”‚   โ”‚   โ”œโ”€โ”€ SmartAccount.sol           # ERC-4337: EIP-712 signing, nonce, batch execution
โ”‚   โ”‚   โ”œโ”€โ”€ AccountFactory.sol         # CREATE2 deterministic EIP-1167 clone factory
โ”‚   โ”‚   โ””โ”€โ”€ NexusPaymaster.sol         # Verifying paymaster, chain-ID bound
โ”‚   โ”œโ”€โ”€ interfaces/
โ”‚   โ”‚   โ”œโ”€โ”€ IPerpsCore.sol
โ”‚   โ”‚   โ”œโ”€โ”€ IPriceOracle.sol
โ”‚   โ”‚   โ”œโ”€โ”€ ICrossChain.sol
โ”‚   โ”‚   โ””โ”€โ”€ IEntryPoint.sol
โ”‚   โ””โ”€โ”€ errors/
โ”‚       โ””โ”€โ”€ PerpsErrors.sol            # Centralized custom error library
โ””โ”€โ”€ web3-app/
    โ””โ”€โ”€ src/
        โ”œโ”€โ”€ app/
        โ”‚   โ”œโ”€โ”€ trade/page.tsx         # Trading interface (Binance WS + lightweight-charts)
        โ”‚   โ”œโ”€โ”€ vaults/page.tsx        # LP vault interface
        โ”‚   โ”œโ”€โ”€ portfolio/page.tsx     # Position dashboard
        โ”‚   โ””โ”€โ”€ docs/page.tsx          # Protocol documentation
        โ”œโ”€โ”€ hooks/
        โ”‚   โ”œโ”€โ”€ useVaultOperations.ts
        โ”‚   โ”œโ”€โ”€ useLPOperations.ts
        โ”‚   โ”œโ”€โ”€ useVaultStats.ts
        โ”‚   โ””โ”€โ”€ usePortfolioData.ts
        โ””โ”€โ”€ constants/
            โ”œโ”€โ”€ contracts.ts           # All deployed addresses + ABIs
            โ””โ”€โ”€ abis/                  # Auto-generated ABI JSON files

Contract Deep-Dives

PositionManager.sol โ€” Trading Engine

Full position lifecycle: open โ†’ update โ†’ close โ†’ liquidate.

  • Market Orders โ€” openPosition() validates oracle price, locks collateral in vault, stores position at current mock Chainlink price
  • Limit Orders โ€” placeLimitOrder() locks collateral optimistically. Keeper calls executeLimitOrder() when price condition met
  • Cross-Chain Trades โ€” executeCrossChainTrade() gated by onlyCrossChainReceiver
  • Liquidations โ€” Isolated mode uses PnLCalculator.isLiquidatable(). Cross-margin computes totalEquity = vaultCollateral + globalPnL

PerpsVault.sol โ€” Collateral & Liquidity

Single contract holding all trader collateral and LP liquidity.

  • Dual accounting โ€” traderCollateral (free) and lockedCollateral (in positions) tracked separately
  • LP Shares โ€” First deposit burns MINIMUM_LIQUIDITY = 1000 permanently preventing inflation attacks
  • settleTrade() โ€” Atomically unlocks collateral โ†’ adjusts totalLiquidity for PnL โ†’ credits payout to trader
  • Dust prevention โ€” withdraw() enforces scaledAmount % DECIMALS_SCALAR == 0

PnLCalculator.sol โ€” Math Library

Pure Solidity library, zero state.

positionSize   = (collateral ร— leverage) / 1e18
PnL            = (priceDelta ร— positionSize) / entryPrice
isLiquidatable = equity โ‰ค maintenanceMargin
               = (collateral + PnL) โ‰ค (collateral ร— liquidationThresholdBps / 10000)

๐Ÿ’ป Frontend Stack

Next.js 15 App Router with zero backend dependency for read operations.

Layer Technology
Framework Next.js 15 (TypeScript, App Router)
Blockchain Wagmi v2 + Viem
Wallet UI RainbowKit (MetaMask, Bitget, OKX)
Queries TanStack Query v5
Charts lightweight-charts (Binance REST API klines)
Live Prices Binance WebSocket (wss://stream.binance.com)
Styling Tailwind CSS + Framer Motion
Network Polkadot Hub Testnet (Chain ID: 420420417)

Key Frontend Features

  • Live PnL โ€” Binance WebSocket prices drive real-time P&L display independent of on-chain oracle
  • Entry Price โ€” Saved locally at trade execution time, survives page refresh
  • Position Polling โ€” 2s refetch interval, aggressive retry after open/close
  • Lightweight Charts โ€” Fast candlestick chart via Binance REST API klines

๐Ÿงช Test Suite & Coverage

forge test        # 95 tests, ~3s
forge coverage    # coverage report
forge test -vvv   # verbose with traces

Invariant Tests (128 runs ร— 50 calls = 6,400 state mutations, 0 reverts):

โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ
โ”‚ Contract            โ”‚ Selector           โ”‚ Calls โ”‚ Reverts โ”‚ Discards โ”‚
โ•žโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ชโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ก
โ”‚ PositionHandler     โ”‚ changeOraclePrice  โ”‚ 1,541 โ”‚       0 โ”‚        0 โ”‚
โ”‚ PositionHandler     โ”‚ createTrader       โ”‚ 1,603 โ”‚       0 โ”‚        1 โ”‚
โ”‚ PositionHandler     โ”‚ openRandomPosition โ”‚ 1,659 โ”‚       0 โ”‚        0 โ”‚
โ”‚ PositionHandler     โ”‚ tryLiquidation     โ”‚ 1,598 โ”‚       0 โ”‚        0 โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
  • invariant_VaultIsSolvent โ€” totalLiquidity โ‰ฅ 0 holds across all mutations
  • invariant_InternalAccountingConsistent โ€” internal balances match ASSET.balanceOf(vault)
  • invariant_MaxActiveAssetsRespected โ€” no trader exceeds maxActiveAssets

๐Ÿ› ๏ธ Local Setup

Prerequisites

  • Foundry (forge, cast, anvil)
  • Node.js โ‰ฅ 18

Smart Contracts

git clone https://github.com/NexTechArchitect/nexus-polka-perps.git
cd nexus-polka-perps

# Install Foundry dependencies
forge install

# Run full test suite (95 tests)
forge test -vv

# Deploy to Polkadot Hub Testnet
cp .env.example .env
# Fill: PRIVATE_KEY

forge script script/deploy/01_DeployMocks.s.sol  --rpc-url polkadot-testnet --broadcast --legacy
forge script script/deploy/02_DeployOracle.s.sol --rpc-url polkadot-testnet --broadcast --legacy
forge script script/deploy/03_DeployVault.s.sol  --rpc-url polkadot-testnet --broadcast --legacy
forge script script/deploy/04_DeployCore.s.sol   --rpc-url polkadot-testnet --broadcast --legacy
forge script script/deploy/05_DeployCCIP.s.sol   --rpc-url polkadot-testnet --broadcast --legacy

Frontend

cd web3-app
npm install --legacy-peer-deps
npm run dev
# โ†’ http://localhost:3000

Network Config (foundry.toml)

[rpc_endpoints]
polkadot-testnet = "https://services.polkadothub-rpc.com/testnet"

[etherscan]
polkadot-testnet = { key = "no-key", url = "https://blockscout-passet-hub.parity-testnet.parity.io/api" }

Get Testnet Tokens

Token Faucet
PAS (gas) faucet.polkadot.io
USDC (collateral) Mint via MockUSDC.mint() or ask deployer

๐Ÿ” Security Model

Attack Vector Mitigation
Oracle price manipulation MockAggregatorV3 + block.timestamp - updatedAt > heartbeat staleness revert
Reentrancy ReentrancyGuard on all vault state-changing functions
LP share inflation attack MINIMUM_LIQUIDITY = 1000 permanently burned on genesis deposit
Dust sweep / precision drain scaledAmount % DECIMALS_SCALAR != 0 reverts on withdrawal
Cross-chain replay Per-trader nonce map in MessageReceiver
Unauthorized cross-chain calls onlyCrossChainReceiver + source chain whitelist + sender whitelist
Over-withdrawal during active position lockedCollateral tracking prevents withdrawing margin from open positions
Keeper reward rug pull rescueTokens() blocks PROTOCOL_ASSET from owner withdrawal
CCIP pipeline blocking try/catch in _ccipReceive โ€” failed trades emit TradeFailed, never block pipeline

โš ๏ธ No formal external security audit has been conducted. Deployed on Polkadot Hub testnet with testnet assets only. Do not use with real funds.


โš ๏ธ Testnet Disclaimer

Nexus Perps runs exclusively on Polkadot Hub Testnet (Chain ID: 420420417). All assets are testnet tokens with zero real-world value. Get PAS gas tokens from faucet.polkadot.io. This is not financial advice.


Built with โšก by NexTech Architect

Twitter GitHub

Built for the Polkadot Solidity Hackathon 2026

About

Nexus Protocol V2 is a decentralized perpetual exchange specifically built to leverage the scalability and interoperability of Polkadot Hub. It provides a seamless, institutional-grade trading experience with up to 50x leverage on BTC and ETH, fully on-chain

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors