Decentralized Perpetual Futures Trading with bBTC Collateral on Starknet
Trade perpetual futures using bBTC as collateral without bridging, KYC, or centralized exchanges. Experience gasless transactions with AVNU Paymaster and access 50+ markets via Extended Protocol.
- Native bBTC token integration (1:1 backed by Bitcoin via Threshold Network)
- Seamless deposit/withdraw functionality
- Minimum collateral: 1.0 bBTC (100000000 units, 8 decimals)
- Real-time balance tracking (available + locked collateral)
- No bridging required - trade directly on Starknet
- Production-ready AVNU Paymaster integration
- Pay gas fees with USDC, ETH, or STRK
- Injected wallet account pattern (no manual Account creation)
- SNIP-9 v2 compatible (execute_from_outside)
- Real-time gas token balance checking
- Automatic fee estimation with safety margins
- Zero ETH required for trading
- Extended Protocol integration via API
- BTC/USD, ETH/USD, STRK/USD, SOL/USD, AVAX/USD, and 45+ more
- Real-time price feeds via Pragma Oracle
- WebSocket support for live market data
- Market stats: last price, mark price, funding rate, open interest
- ArgentX - Full support, priority wallet
- Braavos v1.1.0 - SNIP-9 v2 compatible
- Xverse - Bitcoin + Starknet dual wallet integration
- Wallet connection via @starknet-io/get-starknet 4.0.8
- Bitcoin signature verification with Sats Connect 4.1.x
- 1x to 20x leverage (configurable)
- Long and short positions
- Position lifecycle: ACTIVE → CLOSED
- Real-time PnL calculation
- Collateral locking per position
- Liquidation health monitoring (80% threshold)
- Entry price tracking via Pragma Oracle
- Bitcoin ECDSA signature verification (secp256k1)
- Replay attack protection with nonce-based message hashing
- Pause mechanism for emergency stops (owner-only)
- Access control (owner-only admin functions)
- Input validation (minimum collateral, max leverage)
- Non-custodial - you control your funds
- Event emission for all critical operations
| Component | Address |
|---|---|
| Contract | 0x036ce338c12e315b7b888020469e675c011ca5b9f6c5b657c4e6c00f33c03be7 |
| bBTC Token | 0x0514f13dbfabf6ec1b73524ca47aa4d2b8d8d62b20c9ed6131566bc43d93d4fc |
| Network | Starknet Sepolia Testnet |
| Frontend | [Coming Soon] |
- Cairo 2.8.2 - Smart contract language
- Scarb 2.8.4 - Package manager
- Starknet Foundry 0.50.0 - Testing framework
- Next.js 13.5.1 - React framework
- TypeScript - Type safety
- Tailwind CSS 3.3.3 - Styling
- Starknet.js 7.6.4 - Blockchain interaction
- Zustand 5.0.8 - State management
- AVNU Paymaster - Gasless transactions (docs)
- Extended Protocol - Perpetuals trading (docs)
- Pragma Oracle - Price feeds (docs)
- Sats Connect 4.1.x - Xverse wallet integration
bitcoin_collateral_perps2/
├── src/ # Cairo smart contracts
│ ├── lib.cairo # Main contract (BitcoinCollateralPerps)
│ ├── utils/ # Utility modules
│ │ ├── signature_verifier.cairo # Bitcoin ECDSA verification
│ │ ├── oracle_adapter.cairo # Pragma Oracle integration
│ │ ├── math.cairo # Financial calculations
│ │ ├── extended_integration.cairo # Extended Protocol API
│ │ ├── extended_oracle.cairo # Oracle request handling
│ │ └── extended_api_gateway.cairo # API gateway with caching
│ ├── config/ # Configuration modules
│ │ ├── oracle_config.cairo # Oracle settings
│ │ └── extended_config.cairo # Extended Protocol config
│ └── tokens/ # Token interfaces
│ └── test_btc.cairo # ERC20 interface
├── tests/ # Smart contract tests
│ ├── test_comprehensive.cairo # Full test suite
│ └── test_simple.cairo # Basic tests
├── docs/ # Documentation
│ ├── ARCHITECTURE.md # System architecture (457 lines)
│ ├── API.md # API reference (563 lines)
│ ├── DEPLOYMENT.md # Deployment guide (474 lines)
│ └── TESTING.md # Testing guide (467 lines)
├── scripts/ # Deployment & utility scripts
├── deployments/ # Deployment records (gitignored)
├── Scarb.toml # Cairo project config
├── Scarb.lock # Dependency lock file
├── snfoundry.toml.example # Starknet Foundry config template
├── sncast.toml.example # sncast config template
├── .env.example # Environment variables template
├── SETUP.md # Setup guide
└── README.md # This file
- Node.js 18.0.0+
- Scarb 2.8.4
- Starknet Foundry 0.50.0
- Starknet Wallet (ArgentX, Braavos, or Xverse)
# 1. Clone repository
git clone <repository-url>
cd bitcoin_collateral_perps2
# 2. Setup environment
cp .env.example .env
cp frontend/.env.example frontend/.env.local
cp snfoundry.toml.example snfoundry.toml
cp sncast.toml.example sncast.toml
# 3. Edit with your API keys
nano .env
nano frontend/.env.local
nano snfoundry.toml
# 4. Install dependencies
npm install
cd frontend && npm install && cd ..
# 5. Build contracts
scarb build
# 6. Run tests
scarb test
# 7. Start frontend
cd frontend && npm run devBackend (.env):
STARKNET_ACCOUNT_ADDRESS=your_account_address
STARKNET_PRIVATE_KEY=your_private_key
EXTENDED_API_KEY=your_extended_api_key
AVNU_API_KEY=your_avnu_api_keyFrontend (frontend/.env.local):
NEXT_PUBLIC_CONTRACT_ADDRESS=0x036ce338c12e315b7b888020469e675c011ca5b9f6c5b657c4e6c00f33c03be7
NEXT_PUBLIC_RPC_URL=https://starknet-sepolia.public.blastapi.io/rpc/v0_7
NEXT_PUBLIC_EXTENDED_API_KEY=your_extended_api_key
NEXT_PUBLIC_AVNU_API_KEY=your_avnu_api_key- Click "Connect Wallet"
- Select ArgentX, Braavos, or Xverse
- Approve connection
// Approve bBTC
await bBTCContract.approve(CONTRACT_ADDRESS, amount);
// Deposit
await contract.deposit_btc_collateral(amount);await contract.open_perp_position(
'BTC/USD', // market
1000 * 1e8, // $1000 size
true, // long
10 // 10x leverage
);await contract.close_perp_position(positionId);await contract.withdraw_btc_collateral(amount);# Run all tests
scarb test
# Or using snforge directly
snforge test
# Run specific test
snforge test test_deposit_success
# Run with verbose output
snforge test -v
# Gas profiling
snforge test --gas-reportCollateral Management:
- ✅
test_deposit_success- Successful bBTC deposit - ✅
test_deposit_below_minimum- Reject deposits below minimum - ✅
test_withdraw_success- Successful withdrawal - ✅
test_withdraw_insufficient- Reject insufficient withdrawals
Position Management:
- ✅
test_open_position_success- Open position with valid collateral - ✅
test_open_position_insufficient_collateral- Reject insufficient collateral - ✅
test_close_position_success- Close position and release collateral - ✅
test_close_position_not_owner- Reject non-owner closure
Access Control:
- ✅
test_pause_contract_owner- Owner can pause - ✅
test_pause_contract_non_owner- Non-owner cannot pause - ✅
test_operations_when_paused- Operations fail when paused
Liquidation:
- ✅
test_check_liquidation_health- Health check calculations
tests/test_comprehensive.cairo- Full test suite with all scenariostests/test_simple.cairo- Basic functionality tests
- ARCHITECTURE.md - System architecture and design
- API.md - Complete API reference
- DEPLOYMENT.md - Deployment guide
- TESTING.md - Testing procedures
- SETUP.md - Detailed setup guide
// Collateral Management
fn deposit_btc_collateral(ref self: TContractState, amount: u256)
fn withdraw_btc_collateral(ref self: TContractState, amount: u256)
fn get_collateral_balance(self: @TContractState, user: ContractAddress) -> u256
// Position Management
fn open_perp_position(
ref self: TContractState,
market_id: felt252, // e.g., 'BTC/USD'
size: u256, // Position size in USD (8 decimals)
is_long: bool, // true = Long, false = Short
leverage: u8 // 1-20x
) -> felt252 // Returns position_id
fn close_perp_position(ref self: TContractState, position_id: felt252)
fn get_position(self: @TContractState, position_id: felt252) -> Position
fn check_liquidation_health(self: @TContractState, position_id: felt252) -> bool
// Admin Functions (Owner Only)
fn pause_contract(ref self: TContractState)
fn unpause_contract(ref self: TContractState)
fn set_extended_router(ref self: TContractState, router_address: ContractAddress)
fn set_oracle(ref self: TContractState, oracle_address: ContractAddress)
fn set_liquidation_threshold(ref self: TContractState, threshold: u256)
fn set_min_collateral(ref self: TContractState, min_collateral: u256)
fn set_max_leverage(ref self: TContractState, max_leverage: u8)
// View Functions
fn owner(self: @TContractState) -> ContractAddress
fn paused(self: @TContractState) -> bool
fn extended_oracle(self: @TContractState) -> ContractAddress
fn oracle(self: @TContractState) -> ContractAddress
fn liquidation_threshold(self: @TContractState) -> u256
fn min_collateral(self: @TContractState) -> u256
fn max_leverage(self: @TContractState) -> u8
fn position_counter(self: @TContractState) -> felt252
// Bitcoin Signature Verification
fn verify_bitcoin_signature(
self: @TContractState,
message_hash: u256,
signature_r: u256,
signature_s: u256,
expected_pubkey_x: u256
) -> bool
fn create_deposit_message_hash(
self: @TContractState,
user_address: ContractAddress,
amount: u256,
nonce: u64
) -> u256#[derive(Drop, Serde, starknet::Store)]
pub struct Position {
pub id: felt252,
pub owner: ContractAddress,
pub market_id: felt252,
pub size: u256,
pub collateral: u256,
pub entry_price: u256,
pub is_long: bool,
pub leverage: u8,
pub timestamp: u64,
pub is_active: bool,
pub realized_pnl: u256,
pub status: felt252,
pub extended_order_id: felt252,
pub oracle_request_id: felt252,
}
#[derive(Drop, Serde, starknet::Store)]
pub struct CollateralInfo {
pub total_deposited: u256,
pub available_collateral: u256,
pub locked_collateral: u256,
}#[derive(Drop, starknet::Event)]
pub enum Event {
CollateralDeposited: CollateralDeposited,
CollateralWithdrawn: CollateralWithdrawn,
PositionOpened: PositionOpened,
PositionClosed: PositionClosed,
ContractPaused: ContractPaused,
ContractUnpaused: ContractUnpaused,
}
#[derive(Drop, starknet::Event)]
pub struct CollateralDeposited {
pub user: ContractAddress,
pub amount: u256,
pub timestamp: u64,
}
#[derive(Drop, starknet::Event)]
pub struct PositionOpened {
pub position_id: felt252,
pub user: ContractAddress,
pub market_id: felt252,
pub size: u256,
pub is_long: bool,
pub leverage: u8,
}- bBTC collateral integration - Native bBTC token support
- AVNU Paymaster - Gasless transactions with USDC/ETH/STRK
- Extended Protocol - 50+ perpetual markets
- Multi-wallet support - ArgentX, Braavos v1.1.0, Xverse
- Pragma Oracle - Real-time price feeds
- Bitcoin ECDSA verification - secp256k1 signature verification
- Replay attack protection - Nonce-based message hashing
- Position management - Open/close with leverage 1-20x
- Liquidation monitoring - Health check with 80% threshold
- Event emission - All critical operations emit events
- Comprehensive testing - 12+ test cases covering all features
- Complete documentation - 1,961 lines across 4 docs files
- Frontend deployment - Next.js app with full UI
- WebSocket integration - Real-time market data streaming
- Position history - Track closed positions and PnL
- Gas optimization - Reduce transaction costs
- Mainnet deployment - Production launch on Starknet mainnet
- Cross-margin trading - Share collateral across positions
- Limit orders - Advanced order types
- Stop-loss/Take-profit - Automated risk management
- Funding rate mechanism - Long/short interest balancing
- Liquidation engine - Automated liquidation bot
- Mobile app - iOS/Android native apps
- Advanced analytics - Trading dashboard with charts
- Social trading - Copy trading and leaderboards
Contributions are welcome! Please read SETUP.md for development setup.
# Fork the repository
# Create feature branch
git checkout -b feature/amazing-feature
# Commit changes
git commit -m "feat: add amazing feature"
# Push to branch
git push origin feature/amazing-feature
# Open Pull RequestThis project is licensed under the MIT License - see the LICENSE file for details.
- Starknet Docs: https://docs.starknet.io/
- Cairo Book: https://book.cairo-lang.org/
- AVNU Paymaster: https://docs.avnu.fi/paymaster
- Extended Protocol: https://docs.extended.exchange/
- Pragma Oracle: https://docs.pragma.build/
This is experimental software deployed on Sepolia testnet.
- Use at your own risk - This software is provided "as is" without warranty
- Trading perpetual futures involves significant risk - You may lose all your funds
- Not audited - Smart contracts have not been professionally audited
- Testnet only - Do not use with real funds on mainnet
- For educational and testing purposes only
- No financial advice - This is not investment or financial advice
- Experimental features - AVNU Paymaster and Extended Protocol integrations are experimental
- Always verify contract addresses before interacting
- Never share your private keys or seed phrases
- Test with small amounts first
- Monitor your positions regularly
- Understand liquidation risks before opening leveraged positions
- Keep your wallet software updated
- Network: Starknet Sepolia Testnet
- Status: Alpha - Active Development
- Audit: Not audited
- Insurance: No insurance fund
- Support: Community support only
- Documentation: [./docs](Coming Soon)
- Twitter: https://x.com/BytrosX
Built with ❤️ on Starknet