perpX is a decentralized leveraged trading protocol that reimagines perpetual futures by introducing forced expiry and outcome-based settlement.
# perpX - Decentralized Perpetual Futures & Prediction Markets
## Overview
perpX is a next-generation decentralized trading platform built on Arbitrum Stylus that combines perpetual futures trading with prediction markets. By leveraging Rust-based WASM smart contracts, perpX delivers institutional-grade performance with the transparency and security of blockchain technology.
## Problem Statement
### The Current DeFi Trading Landscape is Broken
1. **High Latency & Gas Costs**: Traditional Solidity-based DEXs suffer from slow execution and expensive transactions, making them unsuitable for active traders.
2. **Limited Market Access**: Most DeFi platforms only offer spot trading or basic perpetuals, lacking sophisticated financial instruments.
3. **Centralization Risks**: Users are forced to choose between fast centralized exchanges (with custody risks) or slow decentralized alternatives.
4. **Poor Capital Efficiency**: Existing platforms require excessive collateral and offer limited leverage options.
5. **No Unified Platform**: Traders must use multiple platforms for perpetuals, predictions, and other derivatives—fragmenting liquidity and user experience.
## Solution
perpX solves these problems by building a unified trading platform on Arbitrum Stylus that offers:
### Lightning-Fast Execution
Rust/WASM smart contracts execute 10-100x faster than Solidity equivalents, enabling near-CEX performance with full decentralization.
### Unified Trading Experience
One platform for perpetual futures AND prediction markets—trade price movements or bet on real-world outcomes.
### Capital Efficient Design
- Up to 40x leverage on perpetuals
- Cross-margin support
- Efficient collateral management with USDC
### Trustless & Transparent
- All trades settled on-chain
- Pyth Network oracle integration for reliable price feeds
- Open-source smart contracts
## Features
### Perpetual Futures Trading
- **Multi-Asset Support**: Trade BTC, ETH, and ARB perpetuals
- **Flexible Timeframes**: 24-hour, 7-day, and 30-day markets
- **Leverage**: Up to 40x leverage with liquidation protection
- **Long & Short**: Profit from both rising and falling markets
### Prediction Markets
- **Outcome-Based Trading**: Bet on future events and outcomes
- **Time-Bound Markets**: Markets with defined expiry for clear settlement
- **Binary Outcomes**: Simple yes/no predictions with transparent payouts
### Risk Management
- **Collateral Vault**: Secure USDC collateral management
- **Liquidation Engine**: Automated position liquidation to protect the protocol
- **Insurance Fund**: Protocol-owned reserves to cover shortfalls
- **Position Manager**: Track and manage all open positions
### User Experience
- **Real-Time Prices**: CoinGecko integration for live market data
- **Portfolio Dashboard**: Track balances, positions, and P&L
- **One-Click Trading**: Streamlined order execution
- **Mobile Responsive**: Trade from any device
## Why Arbitrum Stylus?
### Performance
Stylus allows smart contracts written in Rust to compile to WASM, achieving:
- **10-100x faster execution** than EVM bytecode
- **Significantly lower gas costs** for complex computations
- **Memory-efficient operations** for order matching and risk calculations
### Security
- **Rust's memory safety** prevents entire classes of vulnerabilities
- **Type system** catches bugs at compile time
- **No reentrancy risks** with proper Rust patterns
### EVM Compatibility
- **Seamless interoperability** with existing Ethereum tooling
- **Same addresses and wallets** users already have
- **Composable** with other DeFi protocols on Arbitrum
### Developer Experience
- **Mature Rust ecosystem** with excellent libraries
- **Better testing tools** and debugging capabilities
- **Easier auditing** due to Rust's explicit error handling
## Tech Stack
### Smart Contracts (Stylus/Rust)
| Contract | Purpose |
|----------|---------|
| `OutcomeMarket` | Core trading logic for perpetuals and predictions |
| `CollateralVault` | Secure collateral deposits and withdrawals |
| `PositionManager` | Track and manage user positions |
| `PythPriceAdapter` | Oracle integration for price feeds |
| `LiquidationEngine` | Automated liquidation of underwater positions |
| `InsuranceFund` | Protocol reserves for loss coverage |
| `OrderBook` | Limit order management |
| `CrossMargin` | Cross-margining across positions |
### Frontend
- **Next.js 14** - React framework with App Router
- **TypeScript** - Type-safe development
- **Tailwind CSS** - Utility-first styling
- **shadcn/ui** - Modern component library
- **wagmi/viem** - Ethereum interactions
- **Reown (WalletConnect)** - Wallet connectivity
### Infrastructure
- **Arbitrum Sepolia** - Testnet deployment
- **Pyth Network** - Decentralized oracle for price feeds
- **CoinGecko API** - Real-time market data
- **Circle USDC** - Stablecoin collateral
## Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ Frontend (Next.js) │
├─────────────────────────────────────────────────────────────┤
│ Trading Panel │ Portfolio │ Markets │ Positions │
└────────┬────────┴──────┬──────┴─────┬─────┴────────┬────────┘
│ │ │ │
▼ ▼ ▼ ▼
┌─────────────────────────────────────────────────────────────┐
│ wagmi / viem │
└────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Arbitrum Stylus (WASM) │
├─────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │OutcomeMarket │ │ CollateralVault│ │PositionManager│ │
│ │ (Trading) │ │ (Deposits) │ │ (Positions) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
│ ┌──────┴─────────────────┴─────────────────┴───────┐ │
│ │ PythPriceAdapter (Oracle) │ │
│ └──────────────────────┬───────────────────────────┘ │
│ │ │
│ ┌──────────────┐ ┌────┴─────────┐ ┌──────────────┐ │
│ │LiquidationEng│ │InsuranceFund │ │ OrderBook │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Pyth Network Oracle │
└─────────────────────────────────────────────────────────────┘
```
## How It Works
### Opening a Position
1. User deposits USDC into CollateralVault
2. User selects market (BTC/ETH/ARB) and timeframe (24h/7d/30d)
3. User chooses direction (Long/Short) and leverage (1-40x)
4. Frontend fetches latest price from CoinGecko and updates PriceAdapter
5. OutcomeMarket validates parameters and locks collateral
6. PositionManager creates position record
7. User can monitor P&L in real-time
### Closing a Position
1. User clicks close on their position
2. Current price is fetched and submitted
3. P&L is calculated based on entry vs current price
4. Collateral is released (plus profit or minus loss)
5. Position is marked as closed
### Liquidation
1. LiquidationEngine monitors all positions
2. When position health drops below threshold, liquidation is triggered
3. Position is closed at market price
4. Remaining collateral goes to InsuranceFund
5. Liquidator receives reward
Smart Contracts (Rust/Stylus) - Built 8 production-ready contracts from scratch in Rust targeting Arbitrum Stylus: - OutcomeMarket - Core trading engine with long/short positions, leverage, and P&L calculations - CollateralVault - Secure deposit/withdrawal system with multi-token support - PositionManager - Position tracking and management - PythPriceAdapter - Oracle integration with staleness checks - LiquidationEngine - Automated liquidation system - InsuranceFund - Protocol reserve management - OrderBook - Limit order infrastructure - CrossMargin - Cross-margining capabilities - Deployed 9 market contracts on Arbitrum Sepolia: - BTC/USD (24h, 7d, 30d markets) - ETH/USD (24h, 7d, 30d markets) - ARB/USD (24h, 7d, 30d markets) Frontend Development - Built complete trading interface with Next.js 14 & TypeScript - Real-time price feeds via CoinGecko API - Wallet integration using Reown (WalletConnect) - Portfolio dashboard with P&L tracking - Position management UI - Responsive design for all devices Key Technical Achievements - Successfully compiled and deployed Rust WASM contracts to Stylus - Integrated Pyth Network oracle for decentralized price feeds - Implemented 2-step trading flow (price update → position open) - Built secure collateral locking/releasing mechanism - Created market authorization system for contract interactions Challenges Overcome - Debugged cross-contract calls between Stylus contracts - Resolved price staleness issues with configurable thresholds - Fixed decimal conversion between USDC (6 decimals) and USD values (18 decimals) - Optimized gas usage for Stylus contract deployment
N/A