mirror of
https://github.com/luxfi/docs.git
synced 2026-09-24 00:25:32 +00:00
feat(docs): add 22 project docs — 437 pages total
New sections (86 new pages): - standard: AMM, lending, perps, liquid, governance, identity, NFT AMM, options, 39 precompiles, deployment addresses (12 pages) - operator: K8s CRDs, deployment, reconciliation states (4 pages) - zapdb: encrypted KV store, ChaCha20-Poly1305 (3 pages) - zap: native messaging protocol (2 pages) - safe: multi-sig wallet (3 pages) - liquid: LETH, LBTC, LUSD, xLUX vault (4 pages) - staking: validator, delegation, liquid staking (5 pages) - compliance: KYC/AML, sanctions, surveillance, FINRA/MiFID II (6 pages) - warp: cross-chain BLS messaging (4 pages) - teleport: burn-mint token transfers (3 pages) - corona: post-quantum lattice threshold (3 pages) - threshold: core crypto interfaces and registry (4 pages) - oracle: data feeds, VRF, consumer contracts (3 pages) - iam: auth, RBAC, SSO/SAML (4 pages) - precompile: PQ crypto, DeFi, ZK precompiles (5 pages) - crypto: ECDSA, Ed25519, BLS, ML-DSA, Kyber (4 pages) - adx: CTV ad exchange, OpenRTB, ZK auctions (4 pages) - ledger: hardware wallet, APDU protocol (4 pages) - faucet: testnet token dispenser (3 pages) - gpu: CUDA/Metal kernels (3 pages) - exchange-sdk: matching engine, AVL order book (3 pages)
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
---
|
||||
title: ADX API
|
||||
description: REST API for auction management, bid submission, and campaign operations
|
||||
icon: Server
|
||||
---
|
||||
|
||||
ADX nodes expose HTTP (port 8000) and RPC (port 9000) APIs.
|
||||
|
||||
## Node Operations
|
||||
|
||||
```
|
||||
GET /health # Returns 200 when node is healthy
|
||||
GET /info # Node ID, version, peers, uptime
|
||||
GET /metrics # Prometheus-format metrics
|
||||
```
|
||||
|
||||
## Auction Operations
|
||||
|
||||
### Create Auction
|
||||
|
||||
```
|
||||
POST /auction/create
|
||||
|
||||
{"slot_id":"slot-1","reserve":1000,"duration_ms":100,"format":"video"}
|
||||
```
|
||||
|
||||
### Submit Bid
|
||||
|
||||
```
|
||||
POST /auction/bid
|
||||
|
||||
{"auction_id":"auc-abc123","bid":1500,"advertiser":"adv-1","creative_id":"cr-xyz"}
|
||||
```
|
||||
|
||||
### Auction Status
|
||||
|
||||
```
|
||||
GET /auction/{auction_id}/status
|
||||
|
||||
{"auction_id":"auc-abc123","status":"settled","winner":"adv-1",
|
||||
"settlement_price":1200,"proof":"0xabcdef...","attestation":"0x123..."}
|
||||
```
|
||||
|
||||
## Budget Management
|
||||
|
||||
### Fund Budget
|
||||
|
||||
```
|
||||
POST /budget/fund
|
||||
|
||||
{"advertiser":"adv-1","amount":1000000}
|
||||
```
|
||||
|
||||
### Check Balance
|
||||
|
||||
```
|
||||
GET /budget/{advertiser}
|
||||
|
||||
{"advertiser":"adv-1","balance":985000,"spent_today":15000,"daily_cap":50000}
|
||||
```
|
||||
|
||||
## Campaign Management
|
||||
|
||||
### Create Campaign
|
||||
|
||||
```
|
||||
POST /campaign/create
|
||||
|
||||
{"advertiser":"adv-1","name":"Q1 CTV","budget":500000,
|
||||
"daily_cap":25000,"frequency_cap":3,
|
||||
"targeting":{"geo":["US","CA"],"device":["ctv","mobile"]}}
|
||||
```
|
||||
|
||||
### List Campaigns
|
||||
|
||||
```
|
||||
GET /campaign/list?advertiser=adv-1
|
||||
```
|
||||
@@ -0,0 +1,49 @@
|
||||
---
|
||||
title: Bidding & Auctions
|
||||
description: OpenRTB integration, second-price auctions, and bid optimization
|
||||
icon: Gavel
|
||||
---
|
||||
|
||||
Lux ADX implements decentralized auctions with OpenRTB compatibility and TEE-sealed bidding.
|
||||
|
||||
## Auction Types
|
||||
|
||||
| Type | Mechanism | Use Case |
|
||||
|------|-----------|----------|
|
||||
| Second-price sealed | Winner pays second-highest bid | Standard display/CTV |
|
||||
| First-price | Winner pays own bid | Programmatic guaranteed |
|
||||
| Private | ZK-verified, bids never revealed | Privacy-sensitive |
|
||||
|
||||
## OpenRTB Integration
|
||||
|
||||
ADX supports OpenRTB 2.5 and 3.0 formats. Bid requests include impression specs, device info, and floor prices. Responses carry VAST 4.x ad markup for CTV.
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "req-abc123",
|
||||
"imp": [{"id": "1", "video": {"mimes": ["video/mp4"], "w": 1920, "h": 1080}, "bidfloor": 10.00}],
|
||||
"device": {"devicetype": 3}
|
||||
}
|
||||
```
|
||||
|
||||
## TEE Auction Flow
|
||||
|
||||
1. Bids encrypted with HPKE before submission
|
||||
2. TEE enclave (SGX/SEV/Nitro) decrypts and evaluates
|
||||
3. Second-price auction executed inside hardware enclave
|
||||
4. Winner commitment and audit transcript generated
|
||||
5. Result signed with TEE attestation
|
||||
|
||||
No party can see bid values before settlement.
|
||||
|
||||
## Budget Management
|
||||
|
||||
Budgets tracked in the settlement layer with real-time spend monitoring. Daily and per-impression caps enforced at the node level.
|
||||
|
||||
## Frequency Capping
|
||||
|
||||
Verkle trees provide O(1) proofs for frequency cap verification across millions of users. Each impression is recorded as a leaf, and proofs are verified before accepting bids for the same user-campaign pair.
|
||||
|
||||
## VAST 4.x Support
|
||||
|
||||
VAST 4.0/4.1/4.2 ad tags for CTV: linear video (pre/mid/post-roll), companion ads, verification scripts (OM SDK), and interactive end cards.
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: Lux ADX
|
||||
description: Decentralized CTV ad exchange with TEE auctions and ZK privacy
|
||||
index: true
|
||||
icon: Megaphone
|
||||
---
|
||||
|
||||
Lux ADX (`github.com/luxfi/adx`) is a high-performance decentralized ad exchange for Connected TV (CTV) and digital advertising, built with Byzantine-resilient consensus, TEE-based sealed auctions, and zero-knowledge privacy.
|
||||
|
||||
## Performance Targets
|
||||
|
||||
| Metric | Target |
|
||||
|--------|--------|
|
||||
| Impressions | 100M+/day |
|
||||
| Auction latency | Sub-100ms |
|
||||
| Consensus finality | Under 10s |
|
||||
| Proof generation | Under 500ms |
|
||||
| Network throughput | 10,000+ RPS |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Publisher ──► ADX Node ──► TEE Enclave (sealed auction)
|
||||
│ │
|
||||
Blocklace DAG HPKE-encrypted bids
|
||||
(consensus) ZK proof of correctness
|
||||
│ │
|
||||
Verkle Tree DA Layer
|
||||
(freq caps) (EIP-4844 / Celestia)
|
||||
```
|
||||
|
||||
## Core Components
|
||||
|
||||
| Component | Directory | Purpose |
|
||||
|-----------|-----------|---------|
|
||||
| Blocklace | `blocklace/` | Byzantine-repelling DAG consensus |
|
||||
| TEE | `tee/` | Sealed auctions in SGX/SEV/Nitro enclaves |
|
||||
| Halo2 ZK | `zk/` | Zero-knowledge bid validity proofs |
|
||||
| Verkle Trees | `verkle/` | O(1) frequency cap verification |
|
||||
| HPKE | `crypto/` | Hybrid Public Key Encryption for bid sealing |
|
||||
| DA Layer | `da/` | Data availability (local, EIP-4844, Celestia, IPFS) |
|
||||
| Settlement | `settlement/` | Budget management and payment settlement |
|
||||
|
||||
## Auction Flow
|
||||
|
||||
1. Bids encrypted with HPKE and submitted to ADX nodes
|
||||
2. Sealed auction created inside TEE enclave
|
||||
3. Bids decrypted and second-price auction executed in hardware
|
||||
4. Winner commitment and audit transcript generated
|
||||
5. ZK proof of auction correctness published
|
||||
6. Result with TEE attestation returned to participants
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# Build and start 5-node local network
|
||||
make run-local
|
||||
|
||||
# Check node health
|
||||
curl http://localhost:8000/health
|
||||
|
||||
# Run all tests
|
||||
make test
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Getting Started---","index","---Features---","bidding","privacy","---API Reference---","api"]}
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Privacy & ZK Auctions
|
||||
description: Zero-knowledge proofs for private auctions and bid confidentiality
|
||||
icon: EyeOff
|
||||
---
|
||||
|
||||
Lux ADX uses ZK proofs and TEE to ensure auction integrity without revealing bid values or targeting data.
|
||||
|
||||
## Privacy Architecture
|
||||
|
||||
```
|
||||
Advertiser ──► HPKE Encrypt ──► ADX Node ──► TEE Enclave
|
||||
│
|
||||
ZK Proof (no values revealed)
|
||||
│
|
||||
DA Layer (proof stored)
|
||||
```
|
||||
|
||||
## HPKE Bid Encryption
|
||||
|
||||
Bids sealed with Hybrid Public Key Encryption. Only the TEE enclave holds the decryption key.
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| KEM | DHKEM(X25519) |
|
||||
| KDF | HKDF-SHA256 |
|
||||
| AEAD | AES-128-GCM |
|
||||
|
||||
## Halo2 ZK Proofs
|
||||
|
||||
After each auction, a proof attests that the winner had the highest bid, the price equals the second-highest bid, all bids met the floor, and no bids were fabricated.
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Proof system | Halo2 (no trusted setup) |
|
||||
| Generation | Under 500ms |
|
||||
| Verification | Under 10ms |
|
||||
| Size | ~1 KB |
|
||||
|
||||
## TEE Attestation
|
||||
|
||||
| Backend | Attestation Type |
|
||||
|---------|-----------------|
|
||||
| Intel SGX | DCAP remote attestation |
|
||||
| AMD SEV | SEV-SNP attestation report |
|
||||
| AWS Nitro | Nitro Enclave document |
|
||||
|
||||
## Data Availability
|
||||
|
||||
Proofs stored on the DA layer for auditability: local (dev), EIP-4844 (on-chain), Celestia (modular DA), or IPFS (archival).
|
||||
|
||||
## Attack Resilience
|
||||
|
||||
| Attack | Defense |
|
||||
|--------|---------|
|
||||
| Bid snooping | HPKE encryption + TEE isolation |
|
||||
| Bid manipulation | ZK proof of correctness |
|
||||
| Replay | Nonce tracking per bid |
|
||||
| Byzantine nodes | Blocklace equivocation detection |
|
||||
| Front-running | TEE time-based sealing |
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
title: Compliance API
|
||||
description: Go interfaces for identity verification, screening, and monitoring
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
The compliance module (`github.com/luxfi/compliance`) exposes Go interfaces. All services are thread-safe with `sync.RWMutex`.
|
||||
|
||||
## IDV Provider Interface
|
||||
|
||||
```go
|
||||
type Provider interface {
|
||||
Name() string
|
||||
InitiateVerification(ctx context.Context, req VerificationRequest) (VerificationResponse, error)
|
||||
CheckStatus(ctx context.Context, verificationID string) (VerificationStatus, error)
|
||||
ParseWebhook(r *http.Request) (WebhookEvent, error)
|
||||
}
|
||||
|
||||
// Get a provider by name
|
||||
provider, err := idv.GetProvider("jumio", config)
|
||||
```
|
||||
|
||||
Supported providers: `jumio`, `onfido`, `plaid`.
|
||||
|
||||
## KYC Service
|
||||
|
||||
```go
|
||||
type Service struct {
|
||||
// Multi-provider KYC lifecycle
|
||||
}
|
||||
|
||||
func (s *Service) InitiateKYC(app *Application, provider string) (string, error)
|
||||
func (s *Service) HandleWebhook(provider string, r *http.Request) error
|
||||
func (s *Service) GetApplication(id string) (*Application, error)
|
||||
func (s *Service) ListApplications(status string) ([]*Application, error)
|
||||
func (s *Service) GetStats() Stats
|
||||
```
|
||||
|
||||
## AML Screening Service
|
||||
|
||||
```go
|
||||
type ScreeningService struct {
|
||||
// Screens against OFAC, EU, UK, PEP, adverse media
|
||||
}
|
||||
|
||||
func (s *ScreeningService) Screen(ctx context.Context, req ScreeningRequest) (*ScreeningResult, error)
|
||||
func (s *ScreeningService) BatchScreen(ctx context.Context, reqs []ScreeningRequest) ([]*ScreeningResult, error)
|
||||
```
|
||||
|
||||
`ScreeningResult` contains match type (exact, fuzzy, partial), risk level (low, medium, high, critical), and matched list details.
|
||||
|
||||
## Transaction Monitoring
|
||||
|
||||
```go
|
||||
type MonitoringService struct {
|
||||
// Real-time transaction monitoring rules engine
|
||||
}
|
||||
|
||||
func (m *MonitoringService) Monitor(ctx context.Context, tx Transaction) (*Alert, error)
|
||||
func (m *MonitoringService) GetAlert(id string) (*Alert, error)
|
||||
func (m *MonitoringService) UpdateAlert(id string, status AlertStatus) error
|
||||
func (m *MonitoringService) GenerateSAR(alertID string) (*SAR, error)
|
||||
```
|
||||
|
||||
Alert statuses: `open`, `investigating`, `escalated`, `closed`, `filed`.
|
||||
|
||||
## Payment Compliance
|
||||
|
||||
```go
|
||||
type ComplianceEngine struct {
|
||||
// Validates payments against jurisdiction rules
|
||||
}
|
||||
|
||||
func (e *ComplianceEngine) ValidatePayin(ctx context.Context, payment Payment) error
|
||||
func (e *ComplianceEngine) ValidatePayout(ctx context.Context, payment Payment) error
|
||||
func (e *ComplianceEngine) CheckTravelRule(ctx context.Context, transfer Transfer) (*TravelRuleResult, error)
|
||||
```
|
||||
|
||||
## Stablecoin Compliance
|
||||
|
||||
```go
|
||||
type StablecoinEngine struct {
|
||||
// Token allowlists, address risk, mint/burn compliance
|
||||
}
|
||||
|
||||
func (e *StablecoinEngine) ValidateToken(token string) error
|
||||
func (e *StablecoinEngine) CheckAddressRisk(ctx context.Context, address string) (RiskLevel, error)
|
||||
func (e *StablecoinEngine) ValidateMint(ctx context.Context, req MintRequest) error
|
||||
func (e *StablecoinEngine) ValidateBurn(ctx context.Context, req BurnRequest) error
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Compliance Framework
|
||||
description: KYC/AML, sanctions screening, and regulatory reporting for Lux financial services
|
||||
icon: ShieldCheck
|
||||
---
|
||||
|
||||
The Lux compliance stack (`github.com/luxfi/compliance`) provides identity verification, sanctions screening, transaction monitoring, and regulatory reporting. It is used by the CEX (ATS) and Broker services.
|
||||
|
||||
## Regulatory Coverage
|
||||
|
||||
| Framework | Scope |
|
||||
|-----------|-------|
|
||||
| **FinCEN BSA** | CIP, CTR ($10k threshold), SAR filing |
|
||||
| **SEC** | ATS-N filing, CAT reporting, Reg D accredited investor |
|
||||
| **FINRA** | Rule 5310 best execution, OATS reporting |
|
||||
| **MiFID II** | Best execution, transaction reporting (EU) |
|
||||
| **FCA 5AMLD** | CDD/EDD, HM Treasury sanctions (UK) |
|
||||
| **IOMFSA** | AML/CFT Code 2019, source of wealth/funds (Isle of Man) |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
User ──► IDV Provider (Jumio/Onfido/Plaid)
|
||||
│
|
||||
Webhook ──► KYC Service ──► Application Store
|
||||
│
|
||||
AML Screening ──► OFAC/UN/EU/PEP
|
||||
│
|
||||
Monitoring ──► Alerts ──► SAR Filing
|
||||
```
|
||||
|
||||
## Packages
|
||||
|
||||
| Package | Purpose |
|
||||
|---------|---------|
|
||||
| `pkg/idv` | Identity verification providers (Jumio, Onfido, Plaid) |
|
||||
| `pkg/kyc` | KYC orchestration, application lifecycle |
|
||||
| `pkg/aml` | Sanctions screening, transaction monitoring |
|
||||
| `pkg/regulatory` | Multi-jurisdiction rules (US, UK, IoM) |
|
||||
| `pkg/payments` | Travel Rule, CTR detection, stablecoin compliance |
|
||||
| `pkg/entity` | Regulated entity types (ATS, BD, TA, MSB) |
|
||||
| `pkg/webhook` | Unified webhook handler with idempotency |
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Language**: Go (standard library only, zero external dependencies)
|
||||
- **Thread Safety**: All services use `sync.RWMutex`
|
||||
- **Test Coverage**: 168 tests across 7 packages, all pass with `-race`
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: KYC Verification
|
||||
description: Three-tier KYC with multi-provider identity verification and ongoing monitoring
|
||||
icon: UserCheck
|
||||
---
|
||||
|
||||
The KYC service (`pkg/kyc`) orchestrates identity verification through multiple providers with a tiered verification model.
|
||||
|
||||
## KYC Tiers
|
||||
|
||||
| Tier | Requirements | Limits | Use Cases |
|
||||
|------|-------------|--------|-----------|
|
||||
| **L1 - Basic** | Name, email, phone | $1,000/day | Retail trading |
|
||||
| **L2 - Standard** | Government ID, selfie, address proof | $25,000/day | Standard accounts |
|
||||
| **L3 - Enhanced** | Source of funds, employment, financial profile | Unlimited | Institutional, high-value |
|
||||
|
||||
## IDV Providers
|
||||
|
||||
The `pkg/idv` package supports three identity verification providers through a unified `Provider` interface:
|
||||
|
||||
| Provider | API Version | Capabilities |
|
||||
|----------|-------------|-------------|
|
||||
| **Jumio** | v4 | Document scan, liveness, AML |
|
||||
| **Onfido** | v3.6 | Applicant checks, SDK token |
|
||||
| **Plaid** | Identity Verification | Session-based verification |
|
||||
|
||||
All providers implement `InitiateVerification()`, `CheckStatus()`, and `ParseWebhook()`.
|
||||
|
||||
## Application Lifecycle
|
||||
|
||||
```
|
||||
draft ──► pending ──► pending_kyc ──► approved
|
||||
│ │
|
||||
▼ ▼
|
||||
rejected ongoing monitoring
|
||||
```
|
||||
|
||||
KYC status tracks separately: `not_started` then `pending` then `verified` or `failed`.
|
||||
|
||||
## Webhook Handling
|
||||
|
||||
Each provider sends verification results via webhooks. The `pkg/webhook` package provides:
|
||||
|
||||
- **HMAC-SHA256 signature validation** per provider
|
||||
- **Idempotency tracking** to deduplicate events
|
||||
- **Retry with configurable max attempts**
|
||||
- **Dead letter queue** for failed deliveries
|
||||
|
||||
```
|
||||
Provider Webhook ──► Signature Validation ──► Idempotency Check
|
||||
│
|
||||
KYC Status Update
|
||||
```
|
||||
|
||||
## Application Data Model
|
||||
|
||||
L3 applications collect comprehensive information:
|
||||
|
||||
- Identity (name, DOB, nationality, tax ID)
|
||||
- Address (residential, with proof of address)
|
||||
- Employment and financial profile
|
||||
- Disclosures (PEP status, legal history)
|
||||
- Account preferences (trading objectives, risk tolerance)
|
||||
- Documents (government ID, proof of address, source of funds)
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","kyc","sanctions","surveillance","reporting","api"]}
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: Regulatory Reporting
|
||||
description: FINRA OATS, CAT, ATS-N, MiFID II transaction reports, and SAR filing
|
||||
icon: FileText
|
||||
---
|
||||
|
||||
The compliance stack generates regulatory reports required by US, EU, and UK financial authorities.
|
||||
|
||||
## US Reporting
|
||||
|
||||
| Report | Authority | Frequency | Description |
|
||||
|--------|-----------|-----------|-------------|
|
||||
| **OATS** | FINRA | Real-time | Order Audit Trail System -- every order event |
|
||||
| **CAT** | SEC/FINRA | T+1 | Consolidated Audit Trail -- all order lifecycle events |
|
||||
| **ATS-N** | SEC | Quarterly | Form ATS-N -- ATS operations and conflicts disclosure |
|
||||
| **CTR** | FinCEN | Per event | Currency Transaction Report for transactions over $10,000 |
|
||||
| **SAR** | FinCEN | Per event | Suspicious Activity Report within 30 days of detection |
|
||||
|
||||
## EU/UK Reporting
|
||||
|
||||
| Report | Authority | Frequency | Description |
|
||||
|--------|-----------|-----------|-------------|
|
||||
| **MiFID II Transaction** | ESMA/NCA | T+1 | Transaction reports for all executed orders |
|
||||
| **FCA Reports** | FCA | Periodic | UK regulatory returns under 5AMLD |
|
||||
|
||||
## CTR Filing
|
||||
|
||||
Currency Transaction Reports are triggered automatically when a single transaction or aggregate daily transactions exceed $10,000:
|
||||
|
||||
```
|
||||
Transaction ──► Amount Check ──► Over $10,000?
|
||||
│
|
||||
┌──────┴──────┐
|
||||
▼ ▼
|
||||
File CTR No action
|
||||
(FinCEN)
|
||||
```
|
||||
|
||||
The `pkg/payments` package detects CTR threshold crossings for both single transactions and daily aggregates.
|
||||
|
||||
## SAR Filing
|
||||
|
||||
Suspicious Activity Reports are filed when the surveillance system escalates an alert:
|
||||
|
||||
- Filing deadline: 30 calendar days from detection
|
||||
- No notification to the subject (tipping off is prohibited)
|
||||
- Retention: 5 years from filing date
|
||||
|
||||
## Travel Rule (FATF Rec 16)
|
||||
|
||||
For transfers exceeding $3,000, originator and beneficiary information must accompany the transaction:
|
||||
|
||||
| Field | Required |
|
||||
|-------|----------|
|
||||
| Originator name | Yes |
|
||||
| Originator account | Yes |
|
||||
| Originator address or national ID | Yes |
|
||||
| Beneficiary name | Yes |
|
||||
| Beneficiary account | Yes |
|
||||
|
||||
## Entity Types
|
||||
|
||||
The `pkg/entity` package defines compliance requirements per regulated entity type:
|
||||
|
||||
| Entity | Registration | Net Capital |
|
||||
|--------|-------------|-------------|
|
||||
| **ATS** | SEC Reg ATS, Form ATS-N | $250,000 |
|
||||
| **Broker-Dealer** | SEC/FINRA/SIPC, Rule 15c3-1 | $250,000 |
|
||||
| **Transfer Agent** | SEC Rule 17Ad, Form TA-1/TA-2 | -- |
|
||||
| **MSB** | FinCEN registration, state MTLs | Varies by state |
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: Sanctions Screening
|
||||
description: OFAC, UN, EU sanctions lists, PEP detection, and enhanced due diligence
|
||||
icon: ShieldAlert
|
||||
---
|
||||
|
||||
The AML screening service (`pkg/aml`) checks individuals and entities against global sanctions lists and politically exposed persons databases.
|
||||
|
||||
## Sanctions Lists
|
||||
|
||||
| List | Source | Coverage |
|
||||
|------|--------|----------|
|
||||
| **OFAC SDN** | US Treasury | Specially Designated Nationals |
|
||||
| **EU Consolidated** | European Union | EU sanctions targets |
|
||||
| **UK HMT** | HM Treasury | UK financial sanctions |
|
||||
| **UN Security Council** | United Nations | Global sanctions |
|
||||
| **PEP Database** | Multi-source | Politically exposed persons |
|
||||
| **Adverse Media** | Multi-source | Negative news screening |
|
||||
|
||||
## Matching
|
||||
|
||||
The screening service uses three matching strategies:
|
||||
|
||||
| Match Type | Method | Threshold |
|
||||
|------------|--------|-----------|
|
||||
| **Exact** | String equality | 100% |
|
||||
| **Fuzzy** | Levenshtein distance | Configurable similarity |
|
||||
| **Partial** | Substring and token matching | Name component overlap |
|
||||
|
||||
## Risk Scoring
|
||||
|
||||
Each screening result receives a risk level:
|
||||
|
||||
| Risk Level | Action Required |
|
||||
|------------|----------------|
|
||||
| **Low** | Auto-approve, periodic rescreening |
|
||||
| **Medium** | Manual review within 24 hours |
|
||||
| **High** | Escalate to compliance officer |
|
||||
| **Critical** | Block immediately, file SAR |
|
||||
|
||||
## PEP Detection
|
||||
|
||||
Politically exposed persons (current and former government officials, their family members, and close associates) trigger enhanced due diligence requirements:
|
||||
|
||||
- Source of wealth verification
|
||||
- Source of funds documentation
|
||||
- Senior management approval for onboarding
|
||||
- Enhanced ongoing monitoring (quarterly review)
|
||||
|
||||
## EDD Process
|
||||
|
||||
Enhanced Due Diligence is required for:
|
||||
|
||||
- PEP matches
|
||||
- High-risk jurisdictions
|
||||
- Complex ownership structures
|
||||
- Unusual transaction patterns
|
||||
|
||||
```
|
||||
Screening Hit ──► Risk Assessment ──► EDD Required?
|
||||
│
|
||||
┌───────────────────┤
|
||||
▼ ▼
|
||||
Standard CDD Enhanced CDD
|
||||
(periodic) (source of funds,
|
||||
senior approval)
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: Trade Surveillance
|
||||
description: Real-time detection of wash trading, spoofing, layering, and structuring
|
||||
icon: Eye
|
||||
---
|
||||
|
||||
The monitoring service (`pkg/aml.MonitoringService`) runs a rules engine for real-time transaction monitoring and market surveillance.
|
||||
|
||||
## Detection Rules
|
||||
|
||||
| Pattern | Description | Rule Type |
|
||||
|---------|-------------|-----------|
|
||||
| **Wash Trading** | Self-dealing or coordinated trades to inflate volume | Velocity + geographic |
|
||||
| **Spoofing** | Placing orders with intent to cancel before execution | Velocity |
|
||||
| **Layering** | Multiple orders at different prices to create false depth | Velocity + daily aggregate |
|
||||
| **Structuring** | Breaking transactions to avoid CTR threshold ($10,000) | Structuring |
|
||||
| **Front-Running** | Trading ahead of known pending orders | Velocity |
|
||||
|
||||
## Rule Types
|
||||
|
||||
The engine supports five rule categories:
|
||||
|
||||
| Rule Type | Trigger |
|
||||
|-----------|---------|
|
||||
| `single_amount` | Single transaction exceeds threshold |
|
||||
| `daily_aggregate` | Cumulative daily amount exceeds threshold |
|
||||
| `velocity` | Transaction count within time window exceeds limit |
|
||||
| `geographic` | Transactions from high-risk jurisdictions |
|
||||
| `structuring` | Multiple transactions just below reporting threshold |
|
||||
|
||||
## Alert Lifecycle
|
||||
|
||||
```
|
||||
Transaction ──► Rules Engine ──► Alert Generated
|
||||
│
|
||||
┌──────────┼──────────┐
|
||||
▼ ▼ ▼
|
||||
open investigating escalated
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
closed closed filed (SAR)
|
||||
```
|
||||
|
||||
## SAR Generation
|
||||
|
||||
When an alert is escalated and confirmed, the system generates a Suspicious Activity Report:
|
||||
|
||||
- **Filing entity**: MSB, broker-dealer, or ATS registration
|
||||
- **Subject information**: From KYC application data
|
||||
- **Narrative**: Auto-generated from alert details and transaction history
|
||||
- **Supporting documentation**: Transaction logs, screening results
|
||||
|
||||
## Structuring Detection
|
||||
|
||||
Structuring detection identifies attempts to break transactions into amounts below the $10,000 Currency Transaction Report threshold:
|
||||
|
||||
- Multiple transactions between $8,000 and $9,999 within 24 hours
|
||||
- Transactions from the same originator across multiple accounts
|
||||
- Rapid sequential deposits just below threshold
|
||||
@@ -0,0 +1,128 @@
|
||||
---
|
||||
title: Corona API Reference
|
||||
description: Go API for key generation, threshold signing, and verification
|
||||
icon: Code
|
||||
---
|
||||
|
||||
## Core Package (sign)
|
||||
|
||||
### Party
|
||||
|
||||
```go
|
||||
type Party struct {
|
||||
ID int
|
||||
Ring *ring.Ring
|
||||
SkShare structs.Vector[ring.Poly]
|
||||
Seed map[int][][]byte
|
||||
MACKeys map[int][]byte
|
||||
// ... internal state
|
||||
}
|
||||
|
||||
func NewParty(id int, r, r_xi, r_nu *ring.Ring, sampler *ring.UniformSampler) *Party
|
||||
```
|
||||
|
||||
### Gen (Key Generation)
|
||||
|
||||
```go
|
||||
func Gen(
|
||||
r *ring.Ring,
|
||||
r_xi *ring.Ring,
|
||||
uniformSampler *ring.UniformSampler,
|
||||
trustedDealerKey []byte,
|
||||
lagrangeCoefficients structs.Vector[ring.Poly],
|
||||
) (
|
||||
A structs.Matrix[ring.Poly], // Public matrix
|
||||
skShares map[int]structs.Vector[ring.Poly], // Per-party secret shares
|
||||
seeds map[int][][]byte, // Per-party PRF seeds
|
||||
macKeys map[int]map[int][]byte, // Pairwise MAC keys
|
||||
bTilde structs.Vector[ring.Poly], // Rounded public key
|
||||
)
|
||||
```
|
||||
|
||||
### SignRound1
|
||||
|
||||
```go
|
||||
func (p *Party) SignRound1(sessionID int, prfKey []byte, signers []int) *Round1Data
|
||||
```
|
||||
|
||||
Generates nonce commitments for the signing session. Must be called by each participating party.
|
||||
|
||||
### SignRound2
|
||||
|
||||
```go
|
||||
func (p *Party) SignRound2(
|
||||
sessionID int,
|
||||
message string,
|
||||
prfKey []byte,
|
||||
signers []int,
|
||||
round1Data map[int]*Round1Data,
|
||||
) (*Round2Data, error)
|
||||
```
|
||||
|
||||
Computes the party's signature share using the collected Round 1 data.
|
||||
|
||||
### Verify
|
||||
|
||||
```go
|
||||
func Verify(
|
||||
groupKey *GroupKey,
|
||||
message string,
|
||||
sig *Signature,
|
||||
) bool
|
||||
```
|
||||
|
||||
Verifies a threshold signature against the group public key.
|
||||
|
||||
## Threshold Package (threshold)
|
||||
|
||||
The `threshold/` subpackage implements the `crypto/threshold.Scheme` interface.
|
||||
|
||||
### Types
|
||||
|
||||
```go
|
||||
type GroupKey struct {
|
||||
A structs.Matrix[ring.Poly]
|
||||
BTilde structs.Vector[ring.Poly]
|
||||
Params *Params
|
||||
}
|
||||
|
||||
type KeyShare struct {
|
||||
Index int
|
||||
SkShare structs.Vector[ring.Poly]
|
||||
Seeds map[int][][]byte
|
||||
MACKeys map[int][]byte
|
||||
Lambda ring.Poly
|
||||
GroupKey *GroupKey
|
||||
}
|
||||
|
||||
type Signer struct { /* wraps Party */ }
|
||||
|
||||
type Signature struct {
|
||||
Z []structs.Vector[ring.Poly]
|
||||
H structs.Vector[ring.Poly]
|
||||
}
|
||||
```
|
||||
|
||||
### Signer Methods
|
||||
|
||||
```go
|
||||
func (s *Signer) Round1(sessionID int, prfKey []byte, signers []int) *Round1Data
|
||||
func (s *Signer) Round2(sessionID int, message string, prfKey []byte, signers []int, r1 map[int]*Round1Data) (*Round2Data, error)
|
||||
func (s *Signer) Finalize(r2 map[int]*Round2Data) (*Signature, error)
|
||||
```
|
||||
|
||||
## CLI Runner
|
||||
|
||||
```bash
|
||||
# Run locally with 3 parties, 1 iteration
|
||||
go run main.go l 1 3
|
||||
|
||||
# Run party 0 in distributed mode with 5 parties
|
||||
go run main.go 0 1 5
|
||||
```
|
||||
|
||||
| Argument | Description |
|
||||
|----------|-------------|
|
||||
| `id` | Party ID (0-based) or `l` for local mode |
|
||||
| `iters` | Number of iterations for benchmarking |
|
||||
| `parties` | Total number of signing parties |
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: Corona
|
||||
description: Post-quantum threshold signatures from Module-LWE with 2-round signing
|
||||
icon: Shield
|
||||
---
|
||||
|
||||
Corona (`github.com/luxfi/corona`) implements a practical post-quantum threshold signature scheme based on the Module Learning-With-Errors (Module-LWE) problem. It is described in [eprint.iacr.org/2024/1113](https://eprint.iacr.org/2024/1113).
|
||||
|
||||
## Security Properties
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Security basis | Module-LWE (lattice) |
|
||||
| Post-quantum security | 128-bit |
|
||||
| Signing rounds | 2 |
|
||||
| Threshold model | t-of-n (configurable) |
|
||||
| Key generation | Trusted dealer with Shamir secret sharing |
|
||||
|
||||
## Comparison with Classical Schemes
|
||||
|
||||
| Scheme | Quantum-safe | Rounds | Aggregatable | Basis |
|
||||
|--------|-------------|--------|--------------|-------|
|
||||
| Corona | Yes | 2 | No | Module-LWE |
|
||||
| FROST | No | 2 | No | Discrete log |
|
||||
| BLS | No | 1 | Yes | Bilinear pairing |
|
||||
| CGGMP21 | No | Multi | No | ECDSA |
|
||||
|
||||
Corona is the only post-quantum option. It provides comparable round complexity to FROST while offering security against quantum adversaries.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
corona/
|
||||
├── sign/ # Core signing protocol (Gen, SignRound1, SignRound2, Verify)
|
||||
├── primitives/ # Shamir secret sharing, hash, MAC, PRF
|
||||
├── utils/ # NTT/Montgomery conversions, matrix/vector ops
|
||||
├── threshold/ # threshold.Scheme interface implementation
|
||||
├── networking/ # TCP peer-to-peer message transport
|
||||
└── main.go # CLI runner for benchmarking
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
Corona uses a 48-bit NTT-friendly prime and discrete Gaussian sampling:
|
||||
|
||||
| Parameter | Value | Description |
|
||||
|-----------|-------|-------------|
|
||||
| M | 8 | Public matrix rows |
|
||||
| N | 7 | Secret vector dimension |
|
||||
| Q | 2^48 + 0x4A01 | Ring modulus (NTT-friendly) |
|
||||
| Kappa | 23 | Challenge weight |
|
||||
| Key size | 256 bits | Seed and MAC key size |
|
||||
| Threshold | Configurable | Default: full-threshold (n-of-n) |
|
||||
|
||||
## Use in Lux
|
||||
|
||||
Corona is used alongside BLS in Lux Quasar consensus. BLS provides fast 1-round classical signatures for block finality at 500ms intervals. Corona provides post-quantum security via 3-second quantum bundles that anchor groups of BLS-signed blocks with lattice-based threshold signatures.
|
||||
|
||||
```
|
||||
BLS: [B1]--[B2]--[B3]--[B4]--[B5]--[B6]--...
|
||||
500ms finality per block
|
||||
|
||||
Corona: [─────────QB1: Merkle(B1..B6)─────────]
|
||||
3-second quantum bundle, async 2-round signing
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Overview---","index","---Protocol---","protocol","---API Reference---","api"]}
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
title: Signing Protocol
|
||||
description: Key generation, 2-round threshold signing, and verification
|
||||
icon: Key
|
||||
---
|
||||
|
||||
## Key Generation (Gen)
|
||||
|
||||
Key generation is performed by a trusted dealer. The dealer generates the public parameters and distributes secret key shares to each party via Shamir secret sharing.
|
||||
|
||||
1. Sample a public matrix **A** from the ring
|
||||
2. Sample a secret vector **s** from a discrete Gaussian distribution
|
||||
3. Compute **b = A*s + e** (with Gaussian error **e**)
|
||||
4. Round **b** to produce the public parameter **b-tilde**
|
||||
5. Split **s** into shares via `ShamirSecretSharing` with Lagrange coefficients
|
||||
6. Distribute per-party seeds and MAC keys for authenticated communication
|
||||
|
||||
The output is a set of `KeyShare` values (one per party) and a `GroupKey` containing **A** and **b-tilde**.
|
||||
|
||||
## Round 1: Nonce Generation
|
||||
|
||||
Each signing party generates commitments using PRF-derived randomness.
|
||||
|
||||
```go
|
||||
round1Data := signer.Round1(sessionID, prfKey, signerIndices)
|
||||
```
|
||||
|
||||
Each party:
|
||||
|
||||
1. Derives per-session randomness from the PRF key and session ID
|
||||
2. Samples masking vectors from the appropriate distributions
|
||||
3. Computes commitment values
|
||||
4. Broadcasts `Round1Data` to all other signing parties
|
||||
|
||||
## Round 2: Signature Share
|
||||
|
||||
After receiving all Round 1 data, each party computes its signature share.
|
||||
|
||||
```go
|
||||
round2Data, err := signer.Round2(sessionID, message, prfKey, signerIndices, round1Data)
|
||||
```
|
||||
|
||||
Each party:
|
||||
|
||||
1. Computes the challenge hash **c** from the message and all Round 1 commitments
|
||||
2. Combines its secret share with the challenge and masking values
|
||||
3. Verifies MACs from other parties to detect malicious behavior
|
||||
4. Produces a partial signature vector **z_i**
|
||||
|
||||
## Finalization
|
||||
|
||||
The combiner collects all Round 2 data and produces the final signature.
|
||||
|
||||
```go
|
||||
signature, err := signer.Finalize(round2Data)
|
||||
```
|
||||
|
||||
The combiner:
|
||||
|
||||
1. Aggregates all partial signature vectors
|
||||
2. Checks the norm bound on the combined signature
|
||||
3. Returns the final `Signature` containing vectors **z** and **h**
|
||||
|
||||
## Verification
|
||||
|
||||
Verification checks the signature against the group key without knowing any secret shares.
|
||||
|
||||
```go
|
||||
valid := corona.Verify(groupKey, message, signature)
|
||||
```
|
||||
|
||||
The verifier:
|
||||
|
||||
1. Recomputes the challenge **c** from the message and signature components
|
||||
2. Checks **A*z = b-tilde*c + h** (mod rounding)
|
||||
3. Verifies that the signature norm is within the acceptance bound
|
||||
4. Returns true if all checks pass
|
||||
|
||||
## Security Guarantees
|
||||
|
||||
| Threat | Protection |
|
||||
|--------|-----------|
|
||||
| Quantum computer | Module-LWE hardness (128-bit PQ security) |
|
||||
| Malicious signer | MAC-authenticated messages between parties |
|
||||
| Replay | Session ID binding prevents cross-session reuse |
|
||||
| Forgery | Norm bounds and challenge binding prevent existential forgery |
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
title: Crypto API
|
||||
description: Go package API reference for Lux cryptographic primitives
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
All packages live under `github.com/luxfi/crypto`.
|
||||
|
||||
## Package Index
|
||||
|
||||
| Package | Purpose |
|
||||
|---------|---------|
|
||||
| `bls` | BLS12-381 aggregatable signatures |
|
||||
| `secp256k1` | ECDSA (Ethereum-compatible) |
|
||||
| `secp256r1` | P-256 ECDSA (RIP-7212) |
|
||||
| `mldsa` | ML-DSA post-quantum signatures (FIPS 204) |
|
||||
| `mlkem` | ML-KEM key encapsulation (FIPS 203) |
|
||||
| `slhdsa` | SLH-DSA hash-based signatures (FIPS 205) |
|
||||
| `ring` | Ring signatures (LSAG, lattice) |
|
||||
| `ecies` | Hybrid encryption |
|
||||
| `signer` | Hybrid BLS + Corona consensus signing |
|
||||
| `gpu` | GPU-accelerated ZK operations |
|
||||
| `threshold` | Unified t-of-n signing interface |
|
||||
|
||||
## Common Patterns
|
||||
|
||||
```go
|
||||
// Key generation
|
||||
privKey, err := secp256k1.GenerateKey()
|
||||
pubKey, privKey, err := mldsa.GenerateKey()
|
||||
secretKey, err := bls.NewSecretKey()
|
||||
|
||||
// Sign and verify
|
||||
sig, err := mldsa.Sign(privKey, message)
|
||||
ok := mldsa.Verify(pubKey, message, sig)
|
||||
```
|
||||
|
||||
## Threshold Signing
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/threshold"
|
||||
|
||||
scheme, _ := threshold.GetScheme(threshold.SchemeBLS)
|
||||
dealer, _ := scheme.NewTrustedDealer(threshold.DealerConfig{
|
||||
Threshold: 2, TotalParties: 5,
|
||||
})
|
||||
shares, groupKey, _ := dealer.GenerateShares(ctx)
|
||||
|
||||
signer, _ := scheme.NewSigner(shares[0])
|
||||
share, _ := signer.SignShare(ctx, message, participants, nil)
|
||||
|
||||
aggregator, _ := scheme.NewAggregator(groupKey)
|
||||
signature, _ := aggregator.Aggregate(ctx, message, sigShares, nil)
|
||||
```
|
||||
|
||||
## Security Levels
|
||||
|
||||
| Algorithm | Classical | Quantum | NIST Level |
|
||||
|-----------|-----------|---------|------------|
|
||||
| secp256k1 | 128-bit | Broken | -- |
|
||||
| BLS12-381 | 128-bit | Broken | -- |
|
||||
| ML-DSA-65 | 192-bit | 192-bit | Level 3 |
|
||||
| ML-KEM-768 | 192-bit | 192-bit | Level 3 |
|
||||
| SLH-DSA-128f | 128-bit | 128-bit | Level 1 |
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
make test # Run all tests
|
||||
make bench # Benchmarks
|
||||
CGO_ENABLED=1 go build -tags gpu ./... # With GPU acceleration
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: Encryption & Key Encapsulation
|
||||
description: AES-GCM, ChaCha20-Poly1305, ECIES, ML-KEM (Kyber), and HPKE
|
||||
icon: Lock
|
||||
---
|
||||
|
||||
Symmetric encryption, hybrid encryption, and post-quantum key encapsulation for securing data at rest and in transit.
|
||||
|
||||
## Symmetric Encryption
|
||||
|
||||
| Algorithm | Key Size | Nonce | Tag | Notes |
|
||||
|-----------|----------|-------|-----|-------|
|
||||
| AES-256-GCM | 256-bit | 96-bit | 128-bit | Standard AEAD, hardware-accelerated |
|
||||
| ChaCha20-Poly1305 | 256-bit | 96-bit | 128-bit | Software-optimized AEAD |
|
||||
|
||||
## Hybrid Encryption (ECIES)
|
||||
|
||||
Combines ECDH key agreement with AES-GCM symmetric encryption.
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/ecies"
|
||||
|
||||
ciphertext, err := ecies.Encrypt(recipientPubKey, plaintext)
|
||||
plaintext, err := ecies.Decrypt(recipientPrivKey, ciphertext)
|
||||
```
|
||||
|
||||
## ML-KEM (FIPS 203)
|
||||
|
||||
Post-quantum key encapsulation based on lattice problems.
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/mlkem"
|
||||
|
||||
pub, priv, err := mlkem.GenerateKey()
|
||||
ciphertext, sharedSecret, err := mlkem.Encapsulate(pub)
|
||||
sharedSecret, err := mlkem.Decapsulate(priv, ciphertext)
|
||||
```
|
||||
|
||||
| Parameter Set | Security | Ciphertext | Shared Secret |
|
||||
|---------------|----------|------------|---------------|
|
||||
| ML-KEM-512 | NIST Level 1 | 768 bytes | 32 bytes |
|
||||
| ML-KEM-768 | NIST Level 3 | 1,088 bytes | 32 bytes |
|
||||
| ML-KEM-1024 | NIST Level 5 | 1,568 bytes | 32 bytes |
|
||||
|
||||
## Hash Functions
|
||||
|
||||
| Package | Algorithms |
|
||||
|---------|------------|
|
||||
| `hash/` | SHA-256, SHA-512 |
|
||||
| `blake2b/` | BLAKE2b-256, BLAKE2b-512 |
|
||||
| `hashing/` | Keccak-256 (Ethereum-compatible) |
|
||||
|
||||
## GPU Acceleration
|
||||
|
||||
The `gpu/` package auto-routes to GPU for large batches:
|
||||
|
||||
| Operation | GPU Threshold |
|
||||
|-----------|---------------|
|
||||
| Poseidon2 batch hash | 64+ elements |
|
||||
| Merkle tree | 128+ leaves |
|
||||
| Multi-scalar multiplication | 256+ points |
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Lux Crypto
|
||||
description: Cryptographic primitives including post-quantum signatures, BLS, and key encapsulation
|
||||
index: true
|
||||
icon: KeyRound
|
||||
---
|
||||
|
||||
Lux Crypto (`github.com/luxfi/crypto`) is the core cryptographic library for the Lux blockchain, implementing classical, post-quantum, and threshold cryptographic primitives.
|
||||
|
||||
## Algorithm Overview
|
||||
|
||||
| Package | Algorithm | Security | Quantum Safe | Use Case |
|
||||
|---------|-----------|----------|-------------|----------|
|
||||
| `bls/` | BLS12-381 | 128-bit | No | Consensus aggregation |
|
||||
| `secp256k1/` | ECDSA | 128-bit | No | Ethereum-compatible signing |
|
||||
| `secp256r1/` | P-256 ECDSA | 128-bit | No | RIP-7212 verification |
|
||||
| `mldsa/` | ML-DSA-65 (FIPS 204) | 192-bit | Yes | Post-quantum signatures |
|
||||
| `mlkem/` | ML-KEM-768 (FIPS 203) | 192-bit | Yes | Key encapsulation |
|
||||
| `slhdsa/` | SLH-DSA (FIPS 205) | 128-bit | Yes | Hash-based signatures |
|
||||
| `lamport/` | Lamport OTS | 256-bit | Yes | One-time signatures |
|
||||
| `ring/` | LSAG / Lattice | Varies | Lattice variant | Anonymous signing |
|
||||
|
||||
## Consensus Cryptography (Quasar)
|
||||
|
||||
Lux consensus uses a hybrid BLS + Corona signing scheme:
|
||||
|
||||
```
|
||||
Classical Layer: BLS12-381 (aggregatable, 1-round)
|
||||
+
|
||||
Post-Quantum Layer: Corona (lattice threshold, 2-round)
|
||||
```
|
||||
|
||||
| Package | Role | Notes |
|
||||
|---------|------|-------|
|
||||
| `signer/` | Hybrid BLS + Corona | Production consensus signing |
|
||||
| `bls/` | Classical aggregatable signatures | Fast single-round aggregation |
|
||||
|
||||
## Key Packages
|
||||
|
||||
- **`hash/`** -- SHA-256, SHA-512, BLAKE2b, Keccak-256, SHAKE
|
||||
- **`ecies/`** -- Hybrid encryption (ECDH + AES-GCM)
|
||||
- **`kzg4844/`** -- KZG polynomial commitments (EIP-4844)
|
||||
- **`ipa/`** -- Inner product arguments (Verkle trees)
|
||||
- **`cb58/`** -- Base58Check encoding for Lux addresses
|
||||
- **`rlp/`** -- Recursive Length Prefix encoding
|
||||
- **`gpu/`** -- GPU-accelerated ZK operations (Metal/CUDA)
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
go get github.com/luxfi/crypto
|
||||
|
||||
# Run tests
|
||||
make test
|
||||
|
||||
# Benchmarks
|
||||
make bench
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Getting Started---","index","---Algorithms---","signatures","encryption","---API Reference---","api"]}
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
title: Signature Algorithms
|
||||
description: ECDSA, Ed25519, BLS12-381, ML-DSA, and ring signature implementations
|
||||
icon: PenTool
|
||||
---
|
||||
|
||||
Classical and post-quantum signature algorithms for the Lux blockchain.
|
||||
|
||||
## Classical Signatures
|
||||
|
||||
### ECDSA (secp256k1)
|
||||
|
||||
Ethereum-compatible signatures for transaction signing on all EVM chains.
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/secp256k1"
|
||||
|
||||
privKey, err := secp256k1.GenerateKey()
|
||||
sig, err := secp256k1.Sign(hash[:], privKey)
|
||||
pubKey, err := secp256k1.RecoverPubkey(hash[:], sig)
|
||||
```
|
||||
|
||||
### BLS12-381
|
||||
|
||||
Aggregatable signatures for Lux consensus. Multiple signatures combine into one.
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/bls"
|
||||
|
||||
sk, err := bls.NewSecretKey()
|
||||
pk := bls.PublicFromSecretKey(sk)
|
||||
sig := bls.Sign(sk, msg)
|
||||
ok := bls.Verify(pk, sig, msg)
|
||||
|
||||
aggSig := bls.AggregateSignatures(sigs)
|
||||
ok := bls.AggregateVerify(aggSig, pks, msgs)
|
||||
```
|
||||
|
||||
## Post-Quantum Signatures
|
||||
|
||||
### ML-DSA-65 (FIPS 204)
|
||||
|
||||
Lattice-based signatures with 192-bit security (NIST Level 3).
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/mldsa"
|
||||
|
||||
pub, priv, err := mldsa.GenerateKey()
|
||||
sig, err := mldsa.Sign(priv, msg)
|
||||
ok := mldsa.Verify(pub, msg, sig)
|
||||
```
|
||||
|
||||
| Property | ML-DSA-65 | SLH-DSA-128f |
|
||||
|----------|-----------|-------------|
|
||||
| Public key | 1,952 bytes | 32 bytes |
|
||||
| Signature | 3,309 bytes | 17,088 bytes |
|
||||
| Security | NIST Level 3 | NIST Level 1 |
|
||||
| Basis | Lattice | Hash-only |
|
||||
|
||||
## Ring Signatures
|
||||
|
||||
Anonymous group signatures where the verifier cannot identify the signer.
|
||||
|
||||
| Scheme | Security | Key Type |
|
||||
|--------|----------|----------|
|
||||
| LSAG | Classical | secp256k1 |
|
||||
| LatticeLSAG | Post-quantum | ML-DSA-65 |
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/crypto/ring"
|
||||
|
||||
signer, _ := ring.NewSigner(ring.LSAG)
|
||||
sig, _ := signer.Sign(message, ringMembers, signerIndex)
|
||||
ok := sig.Verify(message, ringMembers)
|
||||
|
||||
// Double-spend detection
|
||||
store := ring.NewMemoryKeyImageStore()
|
||||
err := ring.VerifyAndRecord(sig, message, ringMembers, store)
|
||||
```
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
title: API Reference
|
||||
description: TypeScript API for order book, orders, trades, and candles
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## Book
|
||||
|
||||
```typescript
|
||||
class Book {
|
||||
id: string // UUID
|
||||
name: string // e.g. "BTC-USD"
|
||||
askSize: number // number of ask orders
|
||||
bidSize: number // number of bid orders
|
||||
spread: Decimal // current ask - bid
|
||||
displaySpread: Decimal // cached after settle
|
||||
meanPrice: Decimal // (ask + bid) / 2
|
||||
lastPrice: Decimal // last trade fill price
|
||||
orderBook: OrderBook // { asks: [price, qty][], bids: [price, qty][] }
|
||||
|
||||
addOrder(order: Order): boolean
|
||||
cancelOrder(order: Order): boolean
|
||||
nearestAsk(): Order | undefined
|
||||
nearestBid(): Order | undefined
|
||||
settle(): Trade[]
|
||||
start(fn: (book: Book, trades: Trade[]) => void): ExecutionContext
|
||||
}
|
||||
```
|
||||
|
||||
## Order
|
||||
|
||||
```typescript
|
||||
class Order {
|
||||
id: string // UUID (auto-generated)
|
||||
seqId: number // monotonic sequence number
|
||||
externalId: string // caller-provided ID
|
||||
side: OrderSide // 'ask' | 'bid'
|
||||
type: OrderType // 'limit' | 'market'
|
||||
status: OrderStatus // lifecycle state
|
||||
price: Decimal // order price (0 for market orders)
|
||||
quantity: Decimal // order size
|
||||
fillQuantity: Decimal // amount filled
|
||||
createdAt: number // unix timestamp
|
||||
|
||||
constructor(
|
||||
externalId: string,
|
||||
side: OrderSide,
|
||||
type: OrderType,
|
||||
quantity: number | string | Decimal,
|
||||
price: number | string | Decimal
|
||||
)
|
||||
|
||||
clone(): Order
|
||||
}
|
||||
```
|
||||
|
||||
## Trade
|
||||
|
||||
```typescript
|
||||
class Trade {
|
||||
id: string // UUID
|
||||
fillPrice: Decimal // execution price
|
||||
fillQuantity: Decimal // execution quantity
|
||||
newOrders: Order[] // remainder orders from partial fills
|
||||
matchedOrders: Order[] // the bid/ask pair that matched
|
||||
rejectedOrders: Order[] // orders that could not be re-queued
|
||||
executedAt: number // unix timestamp
|
||||
}
|
||||
```
|
||||
|
||||
## Candle
|
||||
|
||||
```typescript
|
||||
class Candle {
|
||||
openTime: number
|
||||
closeTime: number
|
||||
interval: CandleInterval
|
||||
open: Decimal
|
||||
high: Decimal
|
||||
low: Decimal
|
||||
close: Decimal
|
||||
volume: Decimal // price * quantity sum
|
||||
quoteAssetVolume: Decimal // quantity sum
|
||||
trades: number // trade count
|
||||
|
||||
addTrade(trade: Trade): Candle
|
||||
export(): any[] // [openTime, closeTime, O, H, L, C, vol, quoteVol, trades]
|
||||
}
|
||||
|
||||
enum CandleInterval {
|
||||
ONE_MINUTE = '1 minute',
|
||||
ONE_HOUR = '1 hour',
|
||||
ONE_DAY = '1 day',
|
||||
ONE_WEEK = '1 week',
|
||||
}
|
||||
```
|
||||
|
||||
## Servers
|
||||
|
||||
```typescript
|
||||
// Create Express HTTP server for order management
|
||||
import { createHttp } from '@hanzo/matching-engine'
|
||||
|
||||
// Create Socket.IO server for real-time streaming
|
||||
import { createSocketIO } from '@hanzo/matching-engine'
|
||||
```
|
||||
|
||||
Both servers wrap a `Book` instance and expose order submission, cancellation, and order book queries over their respective protocols.
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Exchange SDK
|
||||
description: TypeScript matching engine with AVL-tree order book
|
||||
icon: ArrowLeftRight
|
||||
---
|
||||
|
||||
`@hanzo/matching-engine` is a TypeScript SDK for building exchange applications. It provides a spec-compliant order matching engine with an AVL-tree order book, OHLCV candlestick generation, and WebSocket streaming.
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Description |
|
||||
|---------|-------------|
|
||||
| **Order Book** | AVL-tree price levels with Fibonacci heap priority queues |
|
||||
| **Order Types** | Limit and market orders with partial fill support |
|
||||
| **Matching** | Price-time priority matching with automatic settlement |
|
||||
| **Candlesticks** | OHLCV candle generation (1m, 1h, 1d, 1w intervals) |
|
||||
| **WebSocket** | Real-time order book and trade streaming via Socket.IO |
|
||||
| **HTTP Server** | Express-based REST API for order management |
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @hanzo/matching-engine
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```typescript
|
||||
import { Book, Order } from '@hanzo/matching-engine'
|
||||
import { OrderSide, OrderType } from '@hanzo/matching-engine/Order'
|
||||
|
||||
const book = new Book('BTC-USD')
|
||||
|
||||
// Add a limit bid
|
||||
book.addOrder(new Order('ext-1', OrderSide.BID, OrderType.LIMIT, 1.5, '50000'))
|
||||
|
||||
// Add a limit ask
|
||||
book.addOrder(new Order('ext-2', OrderSide.ASK, OrderType.LIMIT, 1.0, '49900'))
|
||||
|
||||
// Settle overlapping orders
|
||||
const trades = book.settle()
|
||||
console.log(`Executed ${trades.length} trades`)
|
||||
console.log(`Spread: ${book.spread}`)
|
||||
```
|
||||
|
||||
## Exports
|
||||
|
||||
```typescript
|
||||
export { Book } // Order book with matching engine
|
||||
export { Order } // Order model
|
||||
export { Trade } // Trade execution result
|
||||
export { Candle } // OHLCV candlestick
|
||||
export { createHttp } // Express HTTP server
|
||||
export { createSocketIO } // WebSocket server
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","orderbook","api"]}
|
||||
@@ -0,0 +1,85 @@
|
||||
---
|
||||
title: Order Book
|
||||
description: AVL-tree order book with Fibonacci heap price-time priority
|
||||
icon: BookOpen
|
||||
---
|
||||
|
||||
## Data Structure
|
||||
|
||||
The order book uses two layers of data structures for efficient matching:
|
||||
|
||||
| Structure | Purpose |
|
||||
|-----------|---------|
|
||||
| **Fibonacci Heap** | Priority queue for bids (max-heap) and asks (min-heap) |
|
||||
| **AVL Tree** | Sorted price levels for O(log n) order book rendering |
|
||||
| **Map** | Active order tracking for O(1) cancellation |
|
||||
|
||||
Bids are sorted highest-price-first. Asks are sorted lowest-price-first. Ties at the same price are broken by insertion order (FIFO).
|
||||
|
||||
## Order Types
|
||||
|
||||
| Type | Behavior |
|
||||
|------|----------|
|
||||
| **Limit** | Rests in the book at the specified price until matched or cancelled |
|
||||
| **Market** | Fills immediately against the best opposing order. Rejected if no liquidity |
|
||||
|
||||
## Order Lifecycle
|
||||
|
||||
| Status | Description |
|
||||
|--------|-------------|
|
||||
| `unfilled` | Resting in the book (default) |
|
||||
| `filled` | Fully matched |
|
||||
| `partially-filled` | Partially matched, remainder re-queued |
|
||||
| `remainder` | New order created from a partial fill |
|
||||
| `cancelled` | Removed from the book |
|
||||
|
||||
## Matching Algorithm
|
||||
|
||||
The `settle()` method runs the matching loop:
|
||||
|
||||
1. Pop the best bid and best ask from their heaps.
|
||||
2. If both are limits and the spread is positive, stop (no overlap).
|
||||
3. If one is a market order, or the spread is zero/negative, execute a trade.
|
||||
4. Fill quantity is the minimum of the two order quantities.
|
||||
5. Fill price is the price of the older (earlier `seqId`) order.
|
||||
6. If quantities differ, the remainder is re-queued as a new order.
|
||||
7. Repeat until no more overlapping orders exist.
|
||||
|
||||
## Spread and Pricing
|
||||
|
||||
```typescript
|
||||
book.spread // ask - bid (live, skips cancelled orders)
|
||||
book.displaySpread // cached after last settle
|
||||
book.meanPrice // (ask + bid) / 2, cached after last settle
|
||||
book.lastPrice // fill price of most recent trade
|
||||
```
|
||||
|
||||
## Continuous Execution
|
||||
|
||||
Run the matching engine in a loop using `requestAnimationFrame`:
|
||||
|
||||
```typescript
|
||||
const ctx = book.start((book, trades) => {
|
||||
// Called each frame with new trades
|
||||
console.log(`${trades.length} new trades`)
|
||||
})
|
||||
|
||||
// Stop later
|
||||
ctx.stop()
|
||||
```
|
||||
|
||||
## Candlestick Generation
|
||||
|
||||
Convert trades into OHLCV candles:
|
||||
|
||||
```typescript
|
||||
import { Candle, CandleInterval } from '@hanzo/matching-engine/Candle'
|
||||
|
||||
const candles = new CandleAVL(CandleInterval.ONE_HOUR)
|
||||
candles.tradesToCandles(trades)
|
||||
|
||||
const slice = candles.timeSlice(startTime, endTime, 100)
|
||||
const ohlcv = slice.map(c => c.export())
|
||||
```
|
||||
|
||||
Intervals: `1 minute`, `1 hour`, `1 day`, `1 week`.
|
||||
@@ -0,0 +1,100 @@
|
||||
---
|
||||
title: API Reference
|
||||
description: Faucet REST API endpoints and rate limit configuration
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## Endpoints
|
||||
|
||||
All endpoints are prefixed with `/api`.
|
||||
|
||||
### POST /api/sendToken
|
||||
|
||||
Send test tokens to an address.
|
||||
|
||||
**Request Body:**
|
||||
|
||||
```json
|
||||
{
|
||||
"address": "0x...",
|
||||
"chain": "C",
|
||||
"erc20": "USDCC",
|
||||
"captcha": "recaptcha-response"
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|-------|------|----------|-------------|
|
||||
| `address` | string | Yes | Recipient wallet address |
|
||||
| `chain` | string | Yes | Chain ID (e.g., `C`, `WAGMI`) |
|
||||
| `erc20` | string | No | ERC-20 token ID (omit for native token) |
|
||||
| `captcha` | string | Yes | reCAPTCHA response token |
|
||||
|
||||
**Response (200):**
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Transaction successful",
|
||||
"txHash": "0xabc..."
|
||||
}
|
||||
```
|
||||
|
||||
**Response (400/429):**
|
||||
|
||||
```json
|
||||
{
|
||||
"message": "Rate limit exceeded. Try again in 1440 minutes."
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/getChainConfigs
|
||||
|
||||
Returns all supported chains and tokens with their configuration.
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"configs": [
|
||||
{
|
||||
"ID": "C",
|
||||
"NAME": "Testnet (C-Chain)",
|
||||
"TOKEN": "LUX",
|
||||
"DRIP_AMOUNT": 2,
|
||||
"CHAINID": 43113
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/faucetAddress
|
||||
|
||||
Returns the faucet wallet address for a chain.
|
||||
|
||||
**Query:** `?chain=C`
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"address": "0x..."
|
||||
}
|
||||
```
|
||||
|
||||
### GET /api/getBalance
|
||||
|
||||
Returns the faucet balance for a chain or token.
|
||||
|
||||
**Query:** `?chain=C` or `?chain=C&erc20=USDCC`
|
||||
|
||||
**Response:**
|
||||
|
||||
```json
|
||||
{
|
||||
"balance": "1000000000000000000"
|
||||
}
|
||||
```
|
||||
|
||||
### GET /health
|
||||
|
||||
Health check endpoint. Returns `200` with body `Server healthy`.
|
||||
@@ -0,0 +1,44 @@
|
||||
---
|
||||
title: Testnet Faucet
|
||||
description: Get test LUX tokens for development on Lux testnets
|
||||
icon: Droplets
|
||||
---
|
||||
|
||||
The Lux Faucet dispenses test tokens on Lux testnets for development and testing. It supports multiple EVM chains and ERC-20 tokens with per-address and per-IP rate limiting.
|
||||
|
||||
## Supported Networks
|
||||
|
||||
| Network | Token | Drip Amount | Chain ID |
|
||||
|---------|-------|-------------|----------|
|
||||
| **Testnet (C-Chain)** | LUX | 2 LUX | 43113 |
|
||||
| **Subnet Testnets** | Various | 2 tokens | Per-chain |
|
||||
|
||||
## Rate Limits
|
||||
|
||||
| Scope | Limit | Window |
|
||||
|-------|-------|--------|
|
||||
| **Per Address** | 1 request | 24 hours |
|
||||
| **Per IP** | 1 request per chain | 24 hours |
|
||||
| **Global** | 40 requests | 1 minute |
|
||||
|
||||
Rate limits apply independently per chain and per token. A single address can request tokens from multiple chains within the same window.
|
||||
|
||||
## Architecture
|
||||
|
||||
| Component | Technology | Port |
|
||||
|-----------|-----------|------|
|
||||
| **Backend** | Express + TypeScript | 8000 |
|
||||
| **Frontend** | React / Next.js | 3000 |
|
||||
| **Contracts** | Solidity + Foundry | -- |
|
||||
|
||||
The backend manages funded wallets per chain, signs and sends transactions, and enforces rate limits. CAPTCHA verification (reCAPTCHA v2/v3) prevents abuse.
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Description |
|
||||
|---------|-------------|
|
||||
| **Multi-Chain** | Supports C-Chain and subnet EVM chains |
|
||||
| **ERC-20 Tokens** | Drips USDC, WLUX, and other test tokens |
|
||||
| **Rate Limiting** | Per-address, per-IP, and global limits |
|
||||
| **CAPTCHA** | reCAPTCHA verification to prevent bots |
|
||||
| **Balance Monitoring** | Auto-recalibrates drip amounts based on faucet balance |
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","usage","api"]}
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: Usage
|
||||
description: Get test tokens via the web UI or REST API
|
||||
icon: MousePointer
|
||||
---
|
||||
|
||||
## Web UI
|
||||
|
||||
1. Navigate to the faucet web application.
|
||||
2. Select the target chain (C-Chain, or a subnet testnet).
|
||||
3. Optionally select an ERC-20 token instead of the native token.
|
||||
4. Paste your wallet address.
|
||||
5. Complete the CAPTCHA verification.
|
||||
6. Click **Request Tokens** and wait for the transaction hash.
|
||||
|
||||
The UI shows the faucet balance and your remaining rate limit window.
|
||||
|
||||
## API Request
|
||||
|
||||
Send tokens programmatically via the REST API:
|
||||
|
||||
```bash
|
||||
curl -X POST https://faucet.lux.network/api/sendToken \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"address": "0xYourAddress",
|
||||
"chain": "C",
|
||||
"captcha": "captcha-response-token"
|
||||
}'
|
||||
```
|
||||
|
||||
### Request ERC-20 Tokens
|
||||
|
||||
Include the `erc20` field to request a specific token:
|
||||
|
||||
```bash
|
||||
curl -X POST https://faucet.lux.network/api/sendToken \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"address": "0xYourAddress",
|
||||
"chain": "C",
|
||||
"erc20": "USDCC",
|
||||
"captcha": "captcha-response-token"
|
||||
}'
|
||||
```
|
||||
|
||||
## Check Faucet Balance
|
||||
|
||||
```bash
|
||||
# Native token balance
|
||||
curl "https://faucet.lux.network/api/getBalance?chain=C"
|
||||
|
||||
# ERC-20 token balance
|
||||
curl "https://faucet.lux.network/api/getBalance?chain=C&erc20=USDCC"
|
||||
```
|
||||
|
||||
## Get Faucet Address
|
||||
|
||||
```bash
|
||||
curl "https://faucet.lux.network/api/faucetAddress?chain=C"
|
||||
```
|
||||
|
||||
Use this to check the faucet wallet balance on-chain or to send funds back to the faucet.
|
||||
|
||||
## Rate Limit Behavior
|
||||
|
||||
When rate-limited, the API returns HTTP 429 with a message indicating the remaining cooldown. The default window is 1440 minutes (24 hours) per address per chain.
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
title: API Reference
|
||||
description: Go API and C FFI interface for GPU acceleration
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## Context Management
|
||||
|
||||
```go
|
||||
// Set the compute backend (Auto, CPU, Metal, CUDA, WebGPU)
|
||||
func SetBackend(backend Backend)
|
||||
|
||||
// Get the current backend
|
||||
func GetBackend() Backend
|
||||
|
||||
// Get device info (name, vendor, memory, compute units)
|
||||
func GetDevice() Device
|
||||
|
||||
// Get runtime info string
|
||||
func Info() string
|
||||
|
||||
// Wait for all pending GPU operations to complete
|
||||
func Synchronize()
|
||||
```
|
||||
|
||||
## Array Type
|
||||
|
||||
```go
|
||||
type Array struct {
|
||||
// opaque - use methods below
|
||||
}
|
||||
|
||||
func (a *Array) Shape() []int // dimensions
|
||||
func (a *Array) Dtype() Dtype // element type
|
||||
func (a *Array) Size() int // total element count
|
||||
func (a *Array) Data() []float32 // read back to CPU (CPU backend only)
|
||||
```
|
||||
|
||||
## Device Type
|
||||
|
||||
```go
|
||||
type Device struct {
|
||||
Type Backend
|
||||
Index int
|
||||
Name string
|
||||
Vendor string
|
||||
MemoryTotal uint64
|
||||
MemoryAvail uint64
|
||||
IsDiscrete bool
|
||||
IsUnified bool
|
||||
ComputeUnits int
|
||||
MaxWorkgroup int
|
||||
}
|
||||
```
|
||||
|
||||
## Error Values
|
||||
|
||||
```go
|
||||
var (
|
||||
ErrNoGPU // no GPU available
|
||||
ErrInvalidBackend // invalid backend selection
|
||||
ErrOutOfMemory // GPU out of memory
|
||||
ErrKernelFailed // kernel execution failed
|
||||
ErrNotSupported // operation not supported on backend
|
||||
)
|
||||
```
|
||||
|
||||
## C FFI Interface
|
||||
|
||||
The CGO bridge uses `lux_gpu_c_api.h` which wraps the `luxcpp/gpu` C API.
|
||||
|
||||
### Build Flags
|
||||
|
||||
```bash
|
||||
CGO_CFLAGS="-I/path/to/luxcpp/gpu/include"
|
||||
CGO_LDFLAGS="-L/path/to/luxcpp/gpu/build -llux-gpu"
|
||||
CGO_ENABLED=1 go build ./...
|
||||
```
|
||||
|
||||
### File Structure
|
||||
|
||||
| File | Build Tag | Purpose |
|
||||
|------|-----------|---------|
|
||||
| `types.go` | none | Type definitions, errors |
|
||||
| `gpu.go` | `!cgo` | Pure Go/CPU implementation |
|
||||
| `gpu_c.go` | `cgo` | GPU acceleration via CGO |
|
||||
| `zk_c.go` | `cgo` | ZK operations via CGO |
|
||||
| `metal.go` | `darwin` | Metal backend bridge |
|
||||
|
||||
Without CGO, the package compiles to a pure Go CPU-only implementation with the same API surface.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Lux GPU
|
||||
description: Go bindings for cross-platform GPU acceleration
|
||||
icon: Cpu
|
||||
---
|
||||
|
||||
Go bindings for `luxcpp/gpu`, providing GPU-accelerated array operations for crypto, ZK, and ML workloads. Used by `github.com/luxfi/accel` for high-level blockchain acceleration.
|
||||
|
||||
## Backend Support
|
||||
|
||||
| Backend | Platform | Dependencies | Priority |
|
||||
|---------|----------|--------------|----------|
|
||||
| **CUDA** | Linux/Windows | CUDA Toolkit | 1 (highest) |
|
||||
| **Metal** | macOS arm64 | Metal.framework | 2 |
|
||||
| **WebGPU** | All | Dawn | 3 |
|
||||
| **CPU** | All | None | 4 (fallback) |
|
||||
|
||||
Backend is auto-detected at runtime in priority order. Override with `LUX_GPU_BACKEND` env var (`cuda`, `metal`, `webgpu`, `cpu`).
|
||||
|
||||
## Build Modes
|
||||
|
||||
| Mode | Command | GPU Support |
|
||||
|------|---------|-------------|
|
||||
| **CPU only** | `CGO_ENABLED=0 go build ./...` | No (pure Go fallback) |
|
||||
| **GPU enabled** | `CGO_ENABLED=1 go build ./...` | Yes (requires luxcpp/gpu) |
|
||||
|
||||
## Data Types
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| `Float32` | 32-bit float (default) |
|
||||
| `Float16` | 16-bit float |
|
||||
| `BFloat16` | Brain float 16 |
|
||||
| `Int32` / `Int64` | Signed integers |
|
||||
| `Uint32` / `Uint64` | Unsigned integers |
|
||||
| `Bool` | Boolean |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/gpu"
|
||||
|
||||
a := gpu.Ones([]int{1024, 1024}, gpu.Float32)
|
||||
b := gpu.Random([]int{1024, 1024}, gpu.Float32)
|
||||
c := gpu.MatMul(a, b)
|
||||
gpu.Synchronize()
|
||||
fmt.Println(gpu.Info())
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
title: Kernels
|
||||
description: Available GPU kernels for crypto, ZK, and ML operations
|
||||
icon: Layers
|
||||
---
|
||||
|
||||
## Array Creation
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `Zeros(shape, dtype)` | Zero-filled array |
|
||||
| `Ones(shape, dtype)` | One-filled array |
|
||||
| `Full(shape, dtype, value)` | Constant-filled array |
|
||||
| `Random(shape, dtype)` | Random values in [0, 1) |
|
||||
| `Arange(start, stop, step)` | Sequential values |
|
||||
| `FromSlice(data, shape, dtype)` | Create from Go slice |
|
||||
|
||||
## Arithmetic Operations
|
||||
|
||||
Element-wise operations that dispatch to the active GPU backend.
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `Add(a, b)` | Element-wise addition |
|
||||
| `Sub(a, b)` | Element-wise subtraction |
|
||||
| `Mul(a, b)` | Element-wise multiplication |
|
||||
| `Div(a, b)` | Element-wise division |
|
||||
| `Maximum(a, b)` | Element-wise maximum |
|
||||
|
||||
## Matrix Operations
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `MatMul(a, b)` | Matrix multiplication |
|
||||
| `Transpose(a)` | 2D matrix transpose |
|
||||
|
||||
## Unary Operations
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `Neg(a)` | Negate |
|
||||
| `Abs(a)` | Absolute value |
|
||||
| `Sqrt(a)` | Square root |
|
||||
| `Exp(a)` | Exponential |
|
||||
| `Log(a)` | Natural logarithm |
|
||||
|
||||
## Activation Functions
|
||||
|
||||
Used in ML inference workloads.
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `Tanh(a)` | Hyperbolic tangent |
|
||||
| `Sigmoid(a)` | Sigmoid activation |
|
||||
| `ReLU(a)` | Rectified linear unit |
|
||||
| `GELU(a)` | Gaussian error linear unit |
|
||||
|
||||
## Reductions
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `Sum(a, axes...)` | Sum elements along axes |
|
||||
| `Mean(a, axes...)` | Mean along axes |
|
||||
|
||||
## Utilities
|
||||
|
||||
| Function | Description |
|
||||
|----------|-------------|
|
||||
| `Copy(a)` | Deep copy array |
|
||||
| `Eval(arrays...)` | Force lazy evaluation |
|
||||
| `Synchronize()` | Wait for all GPU operations |
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","kernels","api"]}
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
title: IAM API
|
||||
description: REST API endpoints for user management, authentication, and authorization
|
||||
icon: Server
|
||||
---
|
||||
|
||||
All endpoints are served from `https://hanzo.id/api/`. Authentication required via Bearer token or session cookie.
|
||||
|
||||
## Authentication
|
||||
|
||||
### OAuth Token Exchange
|
||||
|
||||
```
|
||||
POST /api/login/oauth/access_token
|
||||
|
||||
grant_type=authorization_code&code={code}&redirect_uri={uri}
|
||||
&client_id={id}&client_secret={secret}
|
||||
```
|
||||
|
||||
### Refresh Token
|
||||
|
||||
```
|
||||
POST /api/login/oauth/refresh_token
|
||||
|
||||
grant_type=refresh_token&refresh_token={token}&client_id={id}
|
||||
```
|
||||
|
||||
### OIDC Discovery
|
||||
|
||||
```
|
||||
GET /.well-known/openid-configuration
|
||||
```
|
||||
|
||||
## User Management
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/api/get-account` | GET | Current user (requires auth) |
|
||||
| `/api/get-user?id={org}/{name}` | GET | Get user by ID |
|
||||
| `/api/update-user` | POST | Update user profile |
|
||||
| `/api/get-users?owner={org}` | GET | List users in org |
|
||||
|
||||
## Organization Management
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/api/get-organizations` | GET | List organizations |
|
||||
| `/api/get-organization?id={name}` | GET | Get organization |
|
||||
|
||||
## Application Management
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/api/get-applications?owner={org}` | GET | List applications |
|
||||
| `/api/get-application?id={org}/{app}` | GET | Get application |
|
||||
|
||||
## Roles and Permissions
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/api/get-roles?owner={org}` | GET | List roles |
|
||||
| `/api/get-permissions?owner={org}` | GET | List permissions |
|
||||
|
||||
Assign roles by updating the user object:
|
||||
|
||||
```json
|
||||
{
|
||||
"owner": "org",
|
||||
"name": "username",
|
||||
"roles": [{"owner": "org", "name": "admin"}]
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API keys, OAuth2, OIDC, SSO, and SAML authentication methods
|
||||
icon: LogIn
|
||||
---
|
||||
|
||||
Lux IAM supports multiple authentication protocols. All services authenticate through the central provider at **hanzo.id**.
|
||||
|
||||
## OAuth 2.0 / OIDC
|
||||
|
||||
The primary method for web and mobile applications using Authorization Code + PKCE.
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|----------|---------|
|
||||
| `/login/oauth/authorize` | Authorization |
|
||||
| `/api/login/oauth/access_token` | Token exchange |
|
||||
| `/.well-known/openid-configuration` | OIDC discovery |
|
||||
| `/api/userinfo` | User info |
|
||||
| `/api/logout` | Session logout |
|
||||
|
||||
### Token Format
|
||||
|
||||
Access tokens are JWTs with the `owner` claim identifying the organization:
|
||||
|
||||
```json
|
||||
{
|
||||
"sub": "user-id",
|
||||
"iss": "https://hanzo.id",
|
||||
"aud": "your-client-id",
|
||||
"owner": "org-name",
|
||||
"exp": 1700000000
|
||||
}
|
||||
```
|
||||
|
||||
## SAML 2.0
|
||||
|
||||
For enterprise SSO with Okta, Azure AD, or Google Workspace.
|
||||
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| Entity ID | `https://hanzo.id/api/saml/metadata` |
|
||||
| ACS URL | `https://hanzo.id/api/saml/acs` |
|
||||
| SLO URL | `https://hanzo.id/api/saml/slo` |
|
||||
|
||||
## API Keys
|
||||
|
||||
For machine-to-machine authentication:
|
||||
|
||||
```bash
|
||||
curl -H "Authorization: Bearer lux_key_abc123..." \
|
||||
https://api.lux.network/v1/resource
|
||||
```
|
||||
|
||||
## Social Login
|
||||
|
||||
| Provider | Protocol |
|
||||
|----------|----------|
|
||||
| Google | OIDC |
|
||||
| GitHub | OAuth 2.0 |
|
||||
| Apple | OIDC |
|
||||
| Microsoft | OIDC |
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
title: Authorization
|
||||
description: Role-based access control, permissions, and policy enforcement
|
||||
icon: ShieldCheck
|
||||
---
|
||||
|
||||
Lux IAM provides RBAC with fine-grained permissions and policy enforcement across all ecosystem services.
|
||||
|
||||
## RBAC Model
|
||||
|
||||
```
|
||||
Organization ──► User ──► Role ──► Permission (resource:action)
|
||||
```
|
||||
|
||||
### Built-in Roles
|
||||
|
||||
| Role | Permissions |
|
||||
|------|-------------|
|
||||
| `admin` | Full access to all resources |
|
||||
| `editor` | Read/write on assigned resources |
|
||||
| `viewer` | Read-only access |
|
||||
| `developer` | API access and key management |
|
||||
|
||||
### Permission Format
|
||||
|
||||
Permissions follow `resource:action` pattern: `users:read`, `keys:create`, `billing:write`.
|
||||
|
||||
## Policy Enforcement
|
||||
|
||||
Every API request is evaluated:
|
||||
|
||||
```
|
||||
Request ──► Gateway ──► JWT ──► org from "owner" ──► Check Permissions ──► Allow/Deny
|
||||
```
|
||||
|
||||
| Rule Type | Description |
|
||||
|-----------|-------------|
|
||||
| Allow | Explicitly grants access |
|
||||
| Deny | Takes precedence over Allow |
|
||||
| Condition | Time-based, IP-based, or resource-scoped |
|
||||
|
||||
## Multi-Tenancy
|
||||
|
||||
All database queries scoped to organization. Cross-org access requires explicit federation. Audit logs are per-organization.
|
||||
|
||||
## Billing Integration
|
||||
|
||||
IAM tracks credit balances for metered services:
|
||||
|
||||
```
|
||||
Commerce (add credits) ──► IAM (source of truth) ──► Cloud (debit on usage)
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
title: Lux IAM
|
||||
description: Identity and access management with OAuth2, OIDC, SAML, and RBAC
|
||||
index: true
|
||||
icon: Shield
|
||||
---
|
||||
|
||||
Lux IAM (`github.com/luxfi/iam`) is the unified authentication and authorization provider for the Lux ecosystem, hosted at **hanzo.id**. It supports OAuth 2.0, OpenID Connect, SAML 2.0, and CAS protocols.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Lux IAM (hanzo.id) │
|
||||
│ ┌──────────┬───────────┬──────────────────┐ │
|
||||
│ │ Go (Beego)│ React UI │ OAuth2/OIDC │ │
|
||||
│ └─────┬────┴─────┬─────┴───────┬─────────┘ │
|
||||
│ │ │ │ │
|
||||
│ ┌─────▼──┐ ┌────▼───┐ ┌─────▼──────┐ │
|
||||
│ │Postgres│ │ Redis │ │ User Store │ │
|
||||
│ └────────┘ └────────┘ └────────────┘ │
|
||||
└──────────────────────────────────────────────┘
|
||||
↑ ↑ ↑
|
||||
hanzo.app cloud.hanzo.ai commerce
|
||||
```
|
||||
|
||||
## Auth Methods
|
||||
|
||||
| Method | Protocol | Use Case |
|
||||
|--------|----------|----------|
|
||||
| OAuth 2.0 | Authorization Code + PKCE | Web and mobile apps |
|
||||
| OIDC | OpenID Connect 1.0 | SSO and identity federation |
|
||||
| SAML | SAML 2.0 | Enterprise SSO |
|
||||
| CAS | CAS 3.0 | Legacy system integration |
|
||||
| API Keys | Bearer token | Machine-to-machine |
|
||||
|
||||
## Authentication Flow
|
||||
|
||||
1. User visits a Lux application (e.g. hanzo.app)
|
||||
2. Redirected to hanzo.id for OAuth login
|
||||
3. User authenticates (password, social, SAML)
|
||||
4. Redirected back with authorization code
|
||||
5. Application exchanges code for access token
|
||||
6. Token validated via IAM on each request
|
||||
|
||||
## SDKs
|
||||
|
||||
```go
|
||||
// Go
|
||||
import "github.com/iam/iam-go-sdk/iamsdk"
|
||||
|
||||
iamsdk.InitConfig("https://hanzo.id", clientID, clientSecret,
|
||||
certName, orgName, appName)
|
||||
```
|
||||
|
||||
```javascript
|
||||
// JavaScript
|
||||
import { SDK } from 'iam-js-sdk'
|
||||
|
||||
const sdk = new SDK({
|
||||
serverUrl: 'https://hanzo.id',
|
||||
clientId: 'your-client-id',
|
||||
appName: 'your-app',
|
||||
organizationName: 'your-org',
|
||||
})
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Getting Started---","index","---Identity---","authentication","authorization","---API Reference---","api"]}
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
title: API Reference
|
||||
description: APDU commands and Go client API for Ledger integration
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## APDU Protocol
|
||||
|
||||
The Ledger app uses CLA `0x80` with the following instruction set:
|
||||
|
||||
| INS | Code | Description |
|
||||
|-----|------|-------------|
|
||||
| `GET_VERSION` | `0x00` | Get app version info |
|
||||
| `WALLET_ID` | `0x01` | Get wallet identifier |
|
||||
| `GET_ADDR` | `0x02` | Derive address from path |
|
||||
| `GET_EXTENDED_PUBLIC_KEY` | `0x03` | Get extended public key |
|
||||
| `SIGN_HASH` | `0x04` | Sign a 32-byte hash |
|
||||
| `SIGN` | `0x05` | Sign a full transaction |
|
||||
| `SIGN_MSG` | `0x06` | Sign an arbitrary message |
|
||||
|
||||
## Transport
|
||||
|
||||
Messages are sent as 64-byte HID packets. Multi-packet messages use sequence numbers with `TAG_APDU (0x05)` framing. The Go client handles packet chunking automatically via `WrapCommandAPDU` and `UnwrapResponseAPDU`.
|
||||
|
||||
## Go API
|
||||
|
||||
### Connection
|
||||
|
||||
```go
|
||||
// Connect and verify app version
|
||||
func FindLedgerLuxApp() (*LedgerLux, error)
|
||||
func NewLedger() (*LedgerLux, error)
|
||||
|
||||
// Close connection
|
||||
func (l *LedgerLux) Close() error
|
||||
func (l *LedgerLux) Disconnect() error
|
||||
```
|
||||
|
||||
### Query
|
||||
|
||||
```go
|
||||
// App version (AppMode, Major, Minor, Patch)
|
||||
func (l *LedgerLux) GetVersion() (*VersionInfo, error)
|
||||
|
||||
// Derive address from BIP-44 path
|
||||
func (l *LedgerLux) GetPubKey(path string, show bool, hrp string, chainid string) (*ResponseAddr, error)
|
||||
|
||||
// keychain.Ledger interface
|
||||
func (l *LedgerLux) Address(hrp string, index uint32) (ids.ShortID, error)
|
||||
func (l *LedgerLux) GetAddresses(indices []uint32) ([]ids.ShortID, error)
|
||||
```
|
||||
|
||||
### Signing
|
||||
|
||||
```go
|
||||
// Sign hash with single key (keychain.Ledger interface)
|
||||
func (l *LedgerLux) SignHash(hash []byte, index uint32) ([]byte, error)
|
||||
func (l *LedgerLux) Sign(message []byte, index uint32) ([]byte, error)
|
||||
|
||||
// Sign hash with multiple keys (keychain.Ledger interface)
|
||||
func (l *LedgerLux) SignTransaction(hash []byte, indices []uint32) ([][]byte, error)
|
||||
|
||||
// Full control: custom paths, change paths
|
||||
func (l *LedgerLux) SignFull(pathPrefix string, signingPaths []string, message []byte, changePaths []string) (*ResponseSign, error)
|
||||
func (l *LedgerLux) SignHashFull(pathPrefix string, signingPaths []string, hash []byte) (*ResponseSign, error)
|
||||
```
|
||||
|
||||
### Verification
|
||||
|
||||
```go
|
||||
// Verify ECDSA signature (64-byte R||S format)
|
||||
func VerifySignature(pubkey, hash, signature []byte) bool
|
||||
```
|
||||
|
||||
## Response Types
|
||||
|
||||
```go
|
||||
type VersionInfo struct {
|
||||
AppMode uint8
|
||||
Major uint8
|
||||
Minor uint8
|
||||
Patch uint8
|
||||
}
|
||||
|
||||
type ResponseAddr struct {
|
||||
PublicKey []byte // compressed public key
|
||||
Hash []byte // 20-byte address hash
|
||||
Address string // bech32 encoded
|
||||
}
|
||||
|
||||
type ResponseSign struct {
|
||||
Hash []byte
|
||||
Signature map[string][]byte // path -> signature
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: Ledger Hardware Wallet
|
||||
description: Lux app for Ledger hardware wallets with P/X/C chain signing
|
||||
icon: Shield
|
||||
---
|
||||
|
||||
Go client library and Ledger app for signing Lux transactions on hardware wallets. Communicates via APDU protocol over USB HID.
|
||||
|
||||
## Supported Devices
|
||||
|
||||
| Device | Status | Connection |
|
||||
|--------|--------|------------|
|
||||
| **Ledger Nano S** | Supported | USB HID |
|
||||
| **Ledger Nano X** | Supported | USB HID |
|
||||
| **Ledger Nano S Plus** | Supported | USB HID |
|
||||
|
||||
## Chain Support
|
||||
|
||||
| Chain | Derivation Path | Address Format |
|
||||
|-------|----------------|----------------|
|
||||
| **P-Chain** | `m/44'/60'/0'/n'` | Bech32 (`P-lux1...`) |
|
||||
| **X-Chain** | `m/44'/60'/0'/n'` | Bech32 (`X-lux1...`) |
|
||||
| **C-Chain** | `m/44'/60'/0'/n'` | Hex (`0x...`) |
|
||||
|
||||
All chains share the `m/44'/60'/0'` root path with hardened child indices.
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Description |
|
||||
|---------|-------------|
|
||||
| **BIP-44 Derivation** | Ethereum-compatible HD key paths |
|
||||
| **Transaction Signing** | Full transaction and hash signing |
|
||||
| **Message Signing** | Arbitrary message signatures |
|
||||
| **Multi-Signature** | Batch signing across multiple paths |
|
||||
| **On-Device Display** | Address verification on Ledger screen |
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
go get github.com/luxfi/ledger
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/ledger"
|
||||
|
||||
app, err := ledger.FindLedgerLuxApp()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer app.Close()
|
||||
|
||||
version, err := app.GetVersion()
|
||||
fmt.Printf("Lux Ledger App v%s\n", version)
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Installation
|
||||
description: Install the Lux app on Ledger hardware wallets
|
||||
icon: Download
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Ledger Nano S, Nano S Plus, or Nano X
|
||||
- Ledger Live installed on your computer
|
||||
- USB cable for connecting the device
|
||||
|
||||
## Install the Lux App
|
||||
|
||||
1. Open **Ledger Live** and navigate to the **Manager** tab.
|
||||
2. Connect and unlock your Ledger device.
|
||||
3. Allow the manager on your device when prompted.
|
||||
4. Search for **Lux** in the app catalog.
|
||||
5. Click **Install** and wait for the download to complete.
|
||||
6. The Lux app icon appears on your device when ready.
|
||||
|
||||
## Go Client Library
|
||||
|
||||
Install the Go client for programmatic interaction:
|
||||
|
||||
```bash
|
||||
go get github.com/luxfi/ledger
|
||||
```
|
||||
|
||||
The library requires a physical Ledger device with the Lux app open. It communicates over USB HID using the APDU transport protocol.
|
||||
|
||||
## Verify Installation
|
||||
|
||||
Open the Lux app on your Ledger, then run:
|
||||
|
||||
```go
|
||||
app, err := ledger.FindLedgerLuxApp()
|
||||
if err != nil {
|
||||
log.Fatal("Is the Lux app open?", err)
|
||||
}
|
||||
defer app.Close()
|
||||
|
||||
version, err := app.GetVersion()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
fmt.Printf("App version: %s\n", version)
|
||||
```
|
||||
|
||||
The library validates the app version on connection and returns a `VersionRequiredError` if the installed app is too old.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Problem | Solution |
|
||||
|---------|----------|
|
||||
| `CLA not supported` | Open the Lux app on your Ledger before connecting |
|
||||
| Device not found | Check USB connection, try a different port |
|
||||
| Version error | Update the Lux app via Ledger Live |
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","installation","usage","api"]}
|
||||
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: Usage
|
||||
description: Connect to Ledger, derive addresses, and sign transactions
|
||||
icon: Pen
|
||||
---
|
||||
|
||||
## Connect to Ledger
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/ledger"
|
||||
|
||||
app, err := ledger.NewLedger()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer app.Disconnect()
|
||||
```
|
||||
|
||||
`NewLedger()` and `FindLedgerLuxApp()` are equivalent. Both open a connection, verify the app version, and return a `LedgerLux` instance.
|
||||
|
||||
## Address Derivation
|
||||
|
||||
Lux uses derivation root `m/44'/60'/0'` with hardened child indices.
|
||||
|
||||
### Single Address
|
||||
|
||||
```go
|
||||
// Get address at index 0 (path: m/44'/60'/0'/0')
|
||||
addr, err := app.Address("lux", 0)
|
||||
```
|
||||
|
||||
### Multiple Addresses
|
||||
|
||||
```go
|
||||
indices := []uint32{0, 1, 2, 3, 4}
|
||||
addresses, err := app.GetAddresses(indices)
|
||||
```
|
||||
|
||||
### With On-Device Display
|
||||
|
||||
Use `GetPubKey` directly to show the address on the Ledger screen for verification:
|
||||
|
||||
```go
|
||||
resp, err := app.GetPubKey("m/44'/60'/0'/0'", true, "lux", "")
|
||||
// resp.PublicKey - compressed public key
|
||||
// resp.Hash - 20-byte address hash
|
||||
// resp.Address - bech32 encoded address
|
||||
```
|
||||
|
||||
## Sign Transactions
|
||||
|
||||
### Sign a Transaction Hash
|
||||
|
||||
```go
|
||||
hash := sha256.Sum256(unsignedTxBytes)
|
||||
sig, err := app.SignHash(hash[:], 0) // sign with key at index 0
|
||||
```
|
||||
|
||||
### Sign with Multiple Keys
|
||||
|
||||
```go
|
||||
indices := []uint32{0, 1, 2}
|
||||
sigs, err := app.SignTransaction(txHash, indices)
|
||||
// sigs[i] corresponds to indices[i]
|
||||
```
|
||||
|
||||
### Sign Raw Message
|
||||
|
||||
```go
|
||||
sig, err := app.Sign(messageBytes, 0)
|
||||
```
|
||||
|
||||
## Verify Signatures
|
||||
|
||||
```go
|
||||
valid := ledger.VerifySignature(pubkey, messageHash, signature)
|
||||
```
|
||||
|
||||
The signature must be 64 bytes in `[R || S]` format. The public key can be compressed (33 bytes) or uncompressed (65 bytes). Malleable signatures (high-S) are rejected.
|
||||
|
||||
## Wallet SDK Integration
|
||||
|
||||
The `LedgerLux` type implements the `keychain.Ledger` interface from `github.com/luxfi/wallet`, making it compatible with the Lux wallet SDK for building and signing multi-chain transactions.
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
title: Contract Interfaces
|
||||
description: Solidity interfaces for the Liquid Protocol contracts
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## LiquidToken (LETH, LBTC, LUSD)
|
||||
|
||||
Base contract for all yield-bearing bridge tokens. Extends `LRC20` with `AccessControl`, `ReentrancyGuard`, and `IERC3156FlashLender`.
|
||||
|
||||
```solidity
|
||||
// Minting (whitelisted only)
|
||||
function mint(address recipient, uint256 amount) external;
|
||||
function burn(uint256 amount) external;
|
||||
function burnFrom(address account, uint256 amount) external;
|
||||
|
||||
// Whitelist management (ADMIN_ROLE)
|
||||
function setWhitelist(address minter, bool state) external;
|
||||
function removeWhitelist(address minter) external;
|
||||
function setPaused(address minter, bool state) external;
|
||||
|
||||
// Flash loans (ERC-3156)
|
||||
function maxFlashLoan(address token) external view returns (uint256);
|
||||
function flashFee(address token, uint256 amount) external view returns (uint256);
|
||||
function flashLoan(
|
||||
IERC3156FlashBorrower receiver,
|
||||
address token,
|
||||
uint256 amount,
|
||||
bytes calldata data
|
||||
) external returns (bool);
|
||||
|
||||
// Configuration (ADMIN_ROLE)
|
||||
function setFlashFee(uint256 newFee) external;
|
||||
function setMaxFlashLoan(uint256 amount) external;
|
||||
function setFeeRecipient(address recipient) external;
|
||||
```
|
||||
|
||||
## LiquidLUX (xLUX)
|
||||
|
||||
Master yield vault. Extends `ERC20`, `ERC20Permit`, `ERC20Votes`, `ReentrancyGuard`, `AccessControl`, `Pausable`.
|
||||
|
||||
```solidity
|
||||
// User actions
|
||||
function deposit(uint256 amount) external returns (uint256 shares);
|
||||
function withdraw(uint256 shares) external returns (uint256 amount);
|
||||
|
||||
// Fee reception (authorized distributors only)
|
||||
function receiveFees(uint256 amount, bytes32 feeType) external;
|
||||
function depositValidatorRewards(uint256 amount) external;
|
||||
|
||||
// Views
|
||||
function totalAssets() external view returns (uint256);
|
||||
function convertToShares(uint256 assets) external view returns (uint256);
|
||||
function convertToAssets(uint256 shares) external view returns (uint256);
|
||||
function exchangeRate() external view returns (uint256);
|
||||
function reconcile() external view returns (
|
||||
uint256 expectedBalance, uint256 actualBalance, int256 discrepancy
|
||||
);
|
||||
function getFeeBreakdown() external view returns (
|
||||
uint256 dex, uint256 bridge, uint256 lending, uint256 perps,
|
||||
uint256 liquid, uint256 nft, uint256 validator, uint256 other
|
||||
);
|
||||
|
||||
// Governance (GOVERNANCE_ROLE / Timelock)
|
||||
function setTreasury(address treasury) external;
|
||||
function setPerfFeeBps(uint256 bps) external;
|
||||
function applySlashing(uint256 amount) external;
|
||||
```
|
||||
|
||||
## IYieldAdapter
|
||||
|
||||
Interface for strategy adapters that connect yield sources to the protocol.
|
||||
|
||||
```solidity
|
||||
interface IYieldAdapter {
|
||||
function deposit(uint256 amount) external returns (uint256 shares);
|
||||
function withdraw(uint256 shares) external returns (uint256 amount);
|
||||
function totalAssets() external view returns (uint256);
|
||||
function isShariahCompliant() external view returns (bool);
|
||||
}
|
||||
```
|
||||
|
||||
## Deployed Addresses
|
||||
|
||||
| Contract | C-Chain Mainnet | C-Chain Testnet |
|
||||
|----------|----------------|-----------------|
|
||||
| LETH | `0x60E0a8167FC13dE89348978860466C9ceC24B9ba` | `0x9378b62fc172d2a4f715d7ecf49de0362f1bb702` |
|
||||
| LBTC | `0x1E48D32a4F5e9f08DB9aE4959163300FaF8A6C8e` | `0x7fc4f8a926e47fa3587c0d7658c00e7489e67916` |
|
||||
| LUSD | -- | `0x413e4a820635702ec199bc5b62dcbca1749851bf` |
|
||||
| xLUX | -- | `0x00947bbdc619974b0eddaf103b981f3273a3e8da` |
|
||||
@@ -0,0 +1,40 @@
|
||||
---
|
||||
title: Liquid Protocol
|
||||
description: Yield-bearing bridge tokens and the xLUX master vault
|
||||
icon: Droplets
|
||||
---
|
||||
|
||||
Liquid Protocol provides yield-bearing wrapped assets on Lux Network. Users hold bridge tokens (LETH, LBTC, LUSD) that accrue value from bridge fees, or stake LUX into the xLUX vault to earn protocol-wide revenue.
|
||||
|
||||
## Token Overview
|
||||
|
||||
| Token | Underlying | Yield Source | Contract |
|
||||
|-------|-----------|--------------|----------|
|
||||
| **LETH** | ETH | Bridge fees, lending | `LiquidToken` (ERC-3156) |
|
||||
| **LBTC** | BTC | Bridge fees | `LiquidToken` (ERC-3156) |
|
||||
| **LUSD** | USDC/USDT | Bridge fees, stablecoin pools | `LiquidToken` (ERC-3156) |
|
||||
| **xLUX** | LUX | All protocol fees + validator rewards | `LiquidLUX` (ERC-4626) |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Bridge Tokens (LETH, LBTC, LUSD) xLUX Vault
|
||||
┌──────────────────────────┐ ┌──────────────────────────┐
|
||||
│ Whitelisted mint/burn │ │ DEX, Bridge, Lending, │
|
||||
│ ERC-3156 flash loans │ │ Perps, NFT fees │
|
||||
│ Sentinel emergency pause │ │ Validator rewards (0%) │
|
||||
│ Fee → feeRecipient │ │ 10% perf fee → treasury │
|
||||
└──────────────────────────┘ └──────────────────────────┘
|
||||
```
|
||||
|
||||
## Yield Model
|
||||
|
||||
- **Bridge tokens** earn from flash loan fees and protocol integrations. Minting and burning are restricted to whitelisted addresses (vaults, bridges).
|
||||
- **xLUX** collects fees from every protocol in the Lux DeFi stack. A 10% performance fee goes to the treasury; validator rewards are exempt from performance fees.
|
||||
|
||||
## Key Properties
|
||||
|
||||
- All liquid tokens use role-based access: `ADMIN_ROLE` and `SENTINEL_ROLE`.
|
||||
- Flash loans follow ERC-3156 with a configurable fee (minimum 1 basis point).
|
||||
- xLUX uses ERC20Votes for checkpointed, flash-loan-resistant governance power.
|
||||
- Slashing reserve absorbs validator losses before socializing to holders.
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","tokens","xLUX","api"]}
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
title: Liquid Tokens
|
||||
description: LETH, LBTC, and LUSD -- yield-bearing bridge tokens with flash loan support
|
||||
icon: Coins
|
||||
---
|
||||
|
||||
Each liquid token wraps an external asset (ETH, BTC, or stablecoins) as an LRC20B bridge token with ERC-3156 flash loan capabilities. Minting and burning are restricted to whitelisted addresses.
|
||||
|
||||
## Token Details
|
||||
|
||||
| Token | Name | Underlying | Contract |
|
||||
|-------|------|-----------|----------|
|
||||
| **LETH** | Liquid ETH | ETH | `LuxETH` extends `LRC20B` |
|
||||
| **LBTC** | Liquid BTC | BTC | `LuxBTC` extends `LRC20B` |
|
||||
| **LUSD** | Liquid USD | USDC/USDT | `LuxUSD` extends `LRC20B` |
|
||||
|
||||
All 32+ liquid tokens live in `contracts/liquid/tokens/` and share the same base contract.
|
||||
|
||||
## Minting and Redeeming
|
||||
|
||||
Only whitelisted addresses (vaults, bridges) can mint or burn liquid tokens.
|
||||
|
||||
```solidity
|
||||
// Whitelisted minter (vault or bridge)
|
||||
liquidToken.mint(recipient, amount);
|
||||
|
||||
// Any holder can burn their own tokens
|
||||
liquidToken.burn(amount);
|
||||
|
||||
// Burn from another account (requires approval)
|
||||
liquidToken.burnFrom(account, amount);
|
||||
```
|
||||
|
||||
Whitelisting is managed by the `ADMIN_ROLE`. The `SENTINEL_ROLE` can pause individual minters or remove them from the whitelist immediately.
|
||||
|
||||
## Flash Loans (ERC-3156)
|
||||
|
||||
Every liquid token is an ERC-3156 flash lender. Borrowers receive minted tokens within a single transaction and must repay the principal plus a fee.
|
||||
|
||||
```solidity
|
||||
// Query max flash loan
|
||||
uint256 max = liquidToken.maxFlashLoan(address(liquidToken));
|
||||
|
||||
// Query fee for 1000 tokens
|
||||
uint256 fee = liquidToken.flashFee(address(liquidToken), 1000e18);
|
||||
|
||||
// Execute flash loan
|
||||
liquidToken.flashLoan(borrower, address(liquidToken), amount, data);
|
||||
```
|
||||
|
||||
| Parameter | Range |
|
||||
|-----------|-------|
|
||||
| Flash fee | 1 - 10,000 basis points (minimum 1 bp enforced) |
|
||||
| Max flash loan | Configurable by admin |
|
||||
| Fee recipient | Configurable address |
|
||||
|
||||
## Yield Accrual
|
||||
|
||||
Liquid tokens do not rebase. Yield accrues to the protocol via flash loan fees and bridge fees, which flow into the xLUX vault through the FeeSplitter. Holders benefit indirectly when they also hold xLUX.
|
||||
|
||||
## Access Control
|
||||
|
||||
| Role | Permissions |
|
||||
|------|-------------|
|
||||
| `ADMIN_ROLE` | Whitelist minters, set flash fee, set fee recipient |
|
||||
| `SENTINEL_ROLE` | Pause minters, remove from whitelist (emergency) |
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
title: xLUX Vault
|
||||
description: Stake LUX, earn protocol-wide revenue, and participate in governance
|
||||
icon: Vault
|
||||
---
|
||||
|
||||
xLUX (LiquidLUX) is the master yield vault for the Lux Network. It receives fees from every DeFi protocol in the stack and distributes them to depositors as increasing share value.
|
||||
|
||||
## Deposit and Withdraw
|
||||
|
||||
```solidity
|
||||
// Deposit LUX, receive xLUX shares
|
||||
uint256 shares = liquidLux.deposit(luxAmount);
|
||||
|
||||
// Withdraw LUX by burning xLUX
|
||||
uint256 lux = liquidLux.withdraw(xLuxShares);
|
||||
|
||||
// Check exchange rate (LUX per xLUX, scaled 1e18)
|
||||
uint256 rate = liquidLux.exchangeRate();
|
||||
```
|
||||
|
||||
The first depositor receives shares 1:1 with LUX. As fees accumulate, each xLUX share represents more LUX.
|
||||
|
||||
## Fee Sources
|
||||
|
||||
| Source | Performance Fee | Description |
|
||||
|--------|----------------|-------------|
|
||||
| DEX fees | 10% | AMM swap fees |
|
||||
| Bridge fees | 10% | Cross-chain transfer fees |
|
||||
| Lending fees | 10% | Interest from Markets protocol |
|
||||
| Perps fees | 10% | Perpetual futures trading fees |
|
||||
| Liquid fees | 10% | Flash loan fees from LETH/LBTC/LUSD |
|
||||
| NFT fees | 10% | LSSVM marketplace fees |
|
||||
| Validator rewards | 0% | Exempt from performance fee |
|
||||
|
||||
Performance fees go to the treasury. The remaining 89-90% increases the vault balance.
|
||||
|
||||
## Slashing Protection
|
||||
|
||||
A configurable reserve buffer (default 1% of incoming fees) absorbs validator slashing losses before they affect holders. If a slashing event exceeds the reserve, remaining losses are socialized across all xLUX holders proportionally.
|
||||
|
||||
## Governance
|
||||
|
||||
xLUX uses `ERC20Votes` for checkpointed voting power, making it resistant to flash loan governance attacks. Combined with DLUX, it forms vLUX (Voting LUX):
|
||||
|
||||
```
|
||||
vLUX = xLUX + DLUX
|
||||
```
|
||||
|
||||
## Emergency Controls
|
||||
|
||||
| Role | Action |
|
||||
|------|--------|
|
||||
| `EMERGENCY_ROLE` | Pause deposits/withdrawals |
|
||||
| `GOVERNANCE_ROLE` (Timelock) | Unpause, set performance fee, set treasury |
|
||||
| `DEFAULT_ADMIN_ROLE` | Add/remove fee distributors and validator sources |
|
||||
@@ -8,26 +8,49 @@
|
||||
"tokenomics",
|
||||
"---Nodes---",
|
||||
"nodes",
|
||||
"staking",
|
||||
"---Chains & VMs---",
|
||||
"chains",
|
||||
"---DeFi---",
|
||||
"liquid",
|
||||
"---Trading---",
|
||||
"exchange",
|
||||
"dex",
|
||||
"cex",
|
||||
"broker",
|
||||
"compliance",
|
||||
"---Cross-Chain---",
|
||||
"warp",
|
||||
"teleport",
|
||||
"---Cryptography---",
|
||||
"crypto",
|
||||
"precompile",
|
||||
"threshold",
|
||||
"corona",
|
||||
"hsm",
|
||||
"kms",
|
||||
"mpc",
|
||||
"fhe",
|
||||
"lattice",
|
||||
"---Smart Contracts---",
|
||||
"standard",
|
||||
"---Developer Tools---",
|
||||
"cli",
|
||||
"sdk",
|
||||
"netrunner",
|
||||
"accel",
|
||||
"zap",
|
||||
"zapdb",
|
||||
"---Data---",
|
||||
"oracle",
|
||||
"---Identity---",
|
||||
"iam",
|
||||
"---Advertising---",
|
||||
"adx",
|
||||
"---Infrastructure---",
|
||||
"operator",
|
||||
"wallet",
|
||||
"safe",
|
||||
"bridge",
|
||||
"explorer",
|
||||
"indexer",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: Reconciliation API
|
||||
description: Operator state machine, health checks, and upgrade lifecycle
|
||||
icon: RefreshCw
|
||||
---
|
||||
|
||||
## State Machine
|
||||
|
||||
Every Lux CRD follows the same lifecycle phases:
|
||||
|
||||
```
|
||||
Pending --> Creating --> Bootstrapping --> Running <--> Degraded
|
||||
```
|
||||
|
||||
| Phase | Description |
|
||||
|-------|-------------|
|
||||
| Pending | CR accepted, waiting for dependencies |
|
||||
| Creating | Kubernetes resources being provisioned (StatefulSet, Services, ConfigMaps) |
|
||||
| Bootstrapping | Pods running, waiting for chain sync and peer connectivity |
|
||||
| Running | All validators healthy, chains synced, APIs responding |
|
||||
| Degraded | One or more health checks failing, operator attempting recovery |
|
||||
|
||||
Transitions are evaluated every 60 seconds during reconciliation.
|
||||
|
||||
## Health Checks
|
||||
|
||||
The operator performs two levels of health checking on each validator pod:
|
||||
|
||||
**Liveness** -- HTTP GET to `/ext/health/liveness` expecting status 200.
|
||||
|
||||
**Readiness** -- JSON-RPC call to `health.health` checking `result.healthy` is true.
|
||||
|
||||
Health policy is configurable per LuxNetwork:
|
||||
|
||||
| Field | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `maxHeightSkew` | 10 | Maximum allowed P-chain height difference between nodes |
|
||||
| `gracePeriodSeconds` | 300 | Seconds after pod start before enforcing checks |
|
||||
| `checkIntervalSeconds` | 60 | Seconds between health check cycles |
|
||||
| `requireInboundValidators` | false | Require inbound peer connections |
|
||||
|
||||
## Upgrade Strategy
|
||||
|
||||
### OnDelete (default)
|
||||
|
||||
The StatefulSet uses `OnDelete` update strategy. The operator does not restart pods automatically. Delete pods manually to pick up image changes.
|
||||
|
||||
### RollingCanary
|
||||
|
||||
Automated rolling upgrade with safety gates:
|
||||
|
||||
1. Operator detects image tag change on the StatefulSet
|
||||
2. Deletes pods highest-index-first (e.g., luxd-4 before luxd-0)
|
||||
3. Waits for pod Ready + liveness check
|
||||
4. Waits `stabilizationSeconds` (default 60s)
|
||||
5. Runs readiness health check before proceeding to next pod
|
||||
6. On failure after 5 retries, aborts upgrade and sets phase to Degraded
|
||||
|
||||
PodDisruptionBudget `maxUnavailable` matches the upgrade strategy setting.
|
||||
|
||||
## Startup Gate
|
||||
|
||||
Before starting luxd, an init container checks TCP reachability of peer pods:
|
||||
|
||||
| Field | Default | Description |
|
||||
|-------|---------|-------------|
|
||||
| `minPeers` | 2 | Peers that must be TCP-reachable |
|
||||
| `timeoutSeconds` | 300 | Maximum wait time |
|
||||
| `checkIntervalSeconds` | 5 | Seconds between attempts |
|
||||
| `onTimeout` | StartAnyway | Action on timeout: Fail or StartAnyway |
|
||||
@@ -0,0 +1,151 @@
|
||||
---
|
||||
title: Custom Resource Definitions
|
||||
description: YAML specifications for all 6 Lux Operator CRDs
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
All CRDs use API group `lux.network/v1alpha1` and are namespace-scoped.
|
||||
|
||||
## LuxNetwork
|
||||
|
||||
Deploys a validator cluster as a StatefulSet with staking keys, genesis, and consensus configuration.
|
||||
|
||||
```yaml
|
||||
apiVersion: lux.network/v1alpha1
|
||||
kind: LuxNetwork
|
||||
metadata:
|
||||
name: mainnet
|
||||
namespace: lux-mainnet
|
||||
spec:
|
||||
networkId: 1
|
||||
validators: 5
|
||||
image:
|
||||
repository: ghcr.io/luxfi/node
|
||||
tag: v1.23.23
|
||||
storage:
|
||||
size: 200Gi
|
||||
storageClass: do-block-storage
|
||||
dbType: zapdb
|
||||
consensus:
|
||||
sampleSize: 5
|
||||
quorumSize: 4
|
||||
sybilProtectionEnabled: true
|
||||
upgradeStrategy:
|
||||
strategyType: RollingCanary
|
||||
maxUnavailable: 1
|
||||
healthCheckBetweenRestarts: true
|
||||
stabilizationSeconds: 60
|
||||
healthPolicy:
|
||||
maxHeightSkew: 10
|
||||
gracePeriodSeconds: 300
|
||||
startupGate:
|
||||
enabled: true
|
||||
minPeers: 2
|
||||
timeoutSeconds: 300
|
||||
onTimeout: StartAnyway
|
||||
```
|
||||
|
||||
## LuxChain
|
||||
|
||||
Declares a subnet chain with VM configuration and validator assignments.
|
||||
|
||||
```yaml
|
||||
apiVersion: lux.network/v1alpha1
|
||||
kind: LuxChain
|
||||
metadata:
|
||||
name: zoo
|
||||
namespace: lux-mainnet
|
||||
spec:
|
||||
networkRef: mainnet
|
||||
alias: zoo
|
||||
vm:
|
||||
vmType: evm
|
||||
genesis:
|
||||
chainId: 200200
|
||||
chainConfig:
|
||||
feeConfig:
|
||||
gasLimit: 15000000
|
||||
validators:
|
||||
- nodeId: NodeID-abc123
|
||||
weight: 100
|
||||
```
|
||||
|
||||
## LuxIndexer
|
||||
|
||||
Deploys a blockchain data indexer with PostgreSQL storage and Blockscout v2 API.
|
||||
|
||||
```yaml
|
||||
apiVersion: lux.network/v1alpha1
|
||||
kind: LuxIndexer
|
||||
metadata:
|
||||
name: cchain-indexer
|
||||
namespace: lux-mainnet
|
||||
spec:
|
||||
networkRef: mainnet
|
||||
chainAlias: C
|
||||
chainId: 96369
|
||||
port: 4000
|
||||
database:
|
||||
host: indexer-postgres
|
||||
name: indexer
|
||||
defiIndexing: true
|
||||
traceEnabled: true
|
||||
```
|
||||
|
||||
## LuxExplorer
|
||||
|
||||
Deploys a block explorer frontend connected to one or more indexers.
|
||||
|
||||
```yaml
|
||||
apiVersion: lux.network/v1alpha1
|
||||
kind: LuxExplorer
|
||||
metadata:
|
||||
name: explorer
|
||||
namespace: lux-mainnet
|
||||
spec:
|
||||
networkRef: mainnet
|
||||
replicas: 2
|
||||
indexerRefs:
|
||||
- indexerName: cchain-indexer
|
||||
displayName: C-Chain
|
||||
default: true
|
||||
- indexerName: zoo-indexer
|
||||
displayName: Zoo
|
||||
ingress:
|
||||
host: explore.lux.network
|
||||
```
|
||||
|
||||
## LuxGateway
|
||||
|
||||
Deploys a KrakenD-based API gateway with auto-discovered routes and rate limiting.
|
||||
|
||||
```yaml
|
||||
apiVersion: lux.network/v1alpha1
|
||||
kind: LuxGateway
|
||||
metadata:
|
||||
name: api-gateway
|
||||
namespace: lux-mainnet
|
||||
spec:
|
||||
networkRef: mainnet
|
||||
host: api.lux.network
|
||||
replicas: 2
|
||||
autoRoutes: true
|
||||
rateLimit:
|
||||
maxRate: 5000
|
||||
clientMaxRate: 100
|
||||
```
|
||||
|
||||
## LuxMPC
|
||||
|
||||
Deploys an MPC signing cluster with threshold t-of-n key management.
|
||||
|
||||
```yaml
|
||||
apiVersion: lux.network/v1alpha1
|
||||
kind: LuxMPC
|
||||
metadata:
|
||||
name: mpc-cluster
|
||||
namespace: lux-mainnet
|
||||
spec:
|
||||
nodes: 3
|
||||
threshold: 2
|
||||
```
|
||||
@@ -0,0 +1,86 @@
|
||||
---
|
||||
title: Deployment
|
||||
description: Installing and configuring the Lux Operator on Kubernetes
|
||||
icon: Rocket
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Kubernetes 1.28+
|
||||
- `kubectl` configured with cluster access
|
||||
- Container registry access to `ghcr.io/luxfi`
|
||||
|
||||
## Install CRDs
|
||||
|
||||
Apply the custom resource definitions before deploying the operator:
|
||||
|
||||
```bash
|
||||
kubectl apply -f https://raw.githubusercontent.com/luxfi/operator/main/k8s/crds/
|
||||
```
|
||||
|
||||
## Deploy the Operator
|
||||
|
||||
```yaml
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
name: lux-operator
|
||||
namespace: lux-system
|
||||
spec:
|
||||
replicas: 1
|
||||
selector:
|
||||
matchLabels:
|
||||
app: lux-operator
|
||||
template:
|
||||
metadata:
|
||||
labels:
|
||||
app: lux-operator
|
||||
spec:
|
||||
serviceAccountName: lux-operator
|
||||
containers:
|
||||
- name: operator
|
||||
image: ghcr.io/luxfi/operator:v0.3.9
|
||||
args:
|
||||
- --leader-election
|
||||
resources:
|
||||
requests:
|
||||
cpu: 100m
|
||||
memory: 128Mi
|
||||
limits:
|
||||
cpu: 500m
|
||||
memory: 256Mi
|
||||
```
|
||||
|
||||
The operator requires a ServiceAccount with RBAC permissions to manage StatefulSets, Services, ConfigMaps, PodDisruptionBudgets, and all Lux CRDs.
|
||||
|
||||
## Apply with Kustomize
|
||||
|
||||
The recommended deployment method uses Kustomize:
|
||||
|
||||
```bash
|
||||
cd k8s/
|
||||
kubectl kustomize . | kubectl apply -f -
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The operator is configured primarily through CRD specs. Key operational flags:
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--leader-election` | Enable leader election for HA (presence = true) |
|
||||
| `--reconcile-interval` | Reconciliation loop interval (default: 60s) |
|
||||
| `--metrics-addr` | Prometheus metrics bind address (default: :8080) |
|
||||
|
||||
## Verify Installation
|
||||
|
||||
```bash
|
||||
kubectl get deployment lux-operator -n lux-system
|
||||
kubectl get crd | grep lux.network
|
||||
```
|
||||
|
||||
Check operator logs for reconciliation activity:
|
||||
|
||||
```bash
|
||||
kubectl logs -n lux-system deployment/lux-operator
|
||||
```
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Lux Operator
|
||||
description: Kubernetes operator for managing Lux blockchain infrastructure
|
||||
index: true
|
||||
icon: Container
|
||||
---
|
||||
|
||||
The Lux Operator (`github.com/luxfi/operator`) is a Kubernetes operator that manages Lux blockchain infrastructure declaratively. Built in Rust using the `kube-rs` framework, it reconciles custom resources every 60 seconds to maintain desired state.
|
||||
|
||||
## Custom Resource Definitions
|
||||
|
||||
The operator provides 6 CRDs under the `lux.network/v1alpha1` API group:
|
||||
|
||||
| CRD | Shortname | Purpose |
|
||||
|-----|-----------|---------|
|
||||
| LuxNetwork | `luxnet` | Validator cluster (StatefulSet, Services, PDB) |
|
||||
| LuxChain | `luxchain` | Subnet chain deployment and tracking |
|
||||
| LuxIndexer | `luxidx` | Blockchain data indexer per chain |
|
||||
| LuxExplorer | `luxexp` | Block explorer frontend |
|
||||
| LuxGateway | `luxgw` | API gateway with rate limiting and routing |
|
||||
| LuxMPC | `luxmpc` | MPC signing cluster (CGGMP21 + FROST) |
|
||||
|
||||
## Architecture
|
||||
|
||||
The operator runs as a single-replica Deployment with leader election. It watches all 6 CRDs and reconciles them into native Kubernetes resources: StatefulSets, Services, ConfigMaps, PodDisruptionBudgets, and Ingress/IngressRoute objects.
|
||||
|
||||
## Key Features
|
||||
|
||||
- **Upgrade Strategy**: RollingCanary with health checks between pod restarts, or OnDelete for manual control
|
||||
- **Startup Gating**: Waits for peer connectivity before starting luxd to prevent bootstrap race conditions
|
||||
- **Health Policy**: Monitors P-chain height skew, inbound peer connections, and liveness endpoints
|
||||
- **Seed Restore**: Fast bootstrap from VolumeSnapshot, PVC clone, or S3 object store
|
||||
- **Snapshot Scheduling**: Automated periodic snapshots for disaster recovery
|
||||
- **Chain Tracking**: Automatic `--track-chains` configuration from ChainRef entries
|
||||
|
||||
## Image
|
||||
|
||||
```
|
||||
ghcr.io/luxfi/operator:v0.3.9
|
||||
```
|
||||
|
||||
Cross-compiled with musl for `linux/amd64`. Build locally with:
|
||||
|
||||
```bash
|
||||
RUSTC=~/.rustup/toolchains/nightly/bin/rustc \
|
||||
CC_x86_64_unknown_linux_musl=x86_64-linux-musl-gcc \
|
||||
cargo build --release --target x86_64-unknown-linux-musl
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"pages": [
|
||||
"index",
|
||||
"crds",
|
||||
"deployment",
|
||||
"api"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Oracle API
|
||||
description: Solidity interfaces for asserting, disputing, and consuming oracle data
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## IOracle Interface
|
||||
|
||||
The core interface at `@luxfi/oracle/prediction/IOracle.sol`.
|
||||
|
||||
```solidity
|
||||
// Assert a claim with defaults
|
||||
function assertTruthWithDefaults(bytes memory claim, address asserter)
|
||||
external returns (bytes32 assertionId);
|
||||
|
||||
// Assert with full configuration
|
||||
function assertTruth(bytes memory claim, address asserter,
|
||||
address callbackRecipient, address escalationManager,
|
||||
uint64 liveness, IERC20 currency, uint256 bond,
|
||||
bytes32 identifier, bytes32 domainId)
|
||||
external returns (bytes32 assertionId);
|
||||
|
||||
// Dispute and settle
|
||||
function disputeAssertion(bytes32 assertionId, address disputer) external;
|
||||
function settleAssertion(bytes32 assertionId) external;
|
||||
function settleAndGetAssertionResult(bytes32 id) external returns (bool);
|
||||
|
||||
// Read functions
|
||||
function getAssertion(bytes32 id) external view returns (Assertion memory);
|
||||
function getAssertionResult(bytes32 id) external view returns (bool);
|
||||
function getMinimumBond(address currency) external view returns (uint256);
|
||||
```
|
||||
|
||||
## Consumer Example
|
||||
|
||||
```solidity
|
||||
import "@luxfi/oracle/prediction/IOracle.sol";
|
||||
|
||||
contract PriceConsumer is IOracleCallbacks {
|
||||
IOracle public oracle;
|
||||
mapping(bytes32 => bool) public results;
|
||||
|
||||
constructor(address _oracle) { oracle = IOracle(_oracle); }
|
||||
|
||||
function requestPrice(bytes memory claim, uint256 bond) external {
|
||||
IERC20 currency = IERC20(oracle.defaultIdentifier());
|
||||
oracle.assertTruth(claim, msg.sender, address(this), address(0),
|
||||
3600, currency, bond, oracle.defaultIdentifier(), bytes32(0));
|
||||
}
|
||||
|
||||
function assertionResolvedCallback(bytes32 id, bool truth) external override {
|
||||
require(msg.sender == address(oracle));
|
||||
results[id] = truth;
|
||||
}
|
||||
|
||||
function assertionDisputedCallback(bytes32) external override {}
|
||||
}
|
||||
```
|
||||
|
||||
## Events
|
||||
|
||||
```solidity
|
||||
event AssertionMade(bytes32 indexed assertionId, bytes32 domainId,
|
||||
bytes claim, address indexed asserter, address callbackRecipient,
|
||||
address escalationManager, address caller, uint64 expirationTime,
|
||||
IERC20 currency, uint256 bond, bytes32 indexed identifier);
|
||||
|
||||
event AssertionDisputed(bytes32 indexed assertionId,
|
||||
address indexed caller, address indexed disputer);
|
||||
|
||||
event AssertionSettled(bytes32 indexed assertionId,
|
||||
address indexed bondRecipient, bool disputed,
|
||||
bool settlementResolution, address settleCaller);
|
||||
```
|
||||
@@ -0,0 +1,64 @@
|
||||
---
|
||||
title: Oracle Data Feeds
|
||||
description: Optimistic assertions, dispute resolution, and custom data feeds
|
||||
icon: Activity
|
||||
---
|
||||
|
||||
The Lux Oracle uses an **optimistic assertion** model. Data providers assert truths and back them with bonded collateral. If no one disputes during the liveness window, the assertion settles as true.
|
||||
|
||||
## Assertion Lifecycle
|
||||
|
||||
| Phase | Action | Who |
|
||||
|-------|--------|-----|
|
||||
| Assert | `assertTruth(claim, bond)` | Data provider |
|
||||
| Challenge | `disputeAssertion(assertionId)` | Anyone (bonds collateral) |
|
||||
| Settle | `settleAssertion(assertionId)` | Anyone (after liveness expires) |
|
||||
| Callback | `assertionResolvedCallback()` | Oracle notifies consumer |
|
||||
|
||||
## Assertion Types
|
||||
|
||||
### Price Feeds
|
||||
|
||||
Assert a price at a given timestamp. The identifier and ancillary data define what is being priced.
|
||||
|
||||
```solidity
|
||||
bytes memory claim = abi.encode("ETH/USD", 3200e18, block.timestamp);
|
||||
bytes32 id = oracle.assertTruthWithDefaults(claim, msg.sender);
|
||||
```
|
||||
|
||||
### Custom Data
|
||||
|
||||
Any binary claim can be asserted. The oracle does not interpret the claim -- it only manages the dispute lifecycle.
|
||||
|
||||
```solidity
|
||||
bytes memory claim = abi.encode("match-result", teamA, teamB, scoreA, scoreB);
|
||||
bytes32 id = oracle.assertTruth(
|
||||
claim, msg.sender, callbackAddr, address(0),
|
||||
7200, currency, bondAmount, identifier, domainId
|
||||
);
|
||||
```
|
||||
|
||||
## Dispute Resolution
|
||||
|
||||
When an assertion is disputed, resolution follows one of two paths:
|
||||
|
||||
1. **DVM (default)** -- the decentralized verification mechanism resolves the dispute via token-holder vote
|
||||
2. **Escalation Manager** -- a custom contract implements `IEscalationManager` to provide domain-specific arbitration
|
||||
|
||||
## Bonds and Fees
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `bond` | ERC-20 collateral locked by asserter |
|
||||
| `finalFee` | Fee paid to the oracle system on disputes |
|
||||
| `burnedBondPercentage` | Portion of loser's bond that is burned |
|
||||
|
||||
The minimum bond is queried via `getMinimumBond(currency)`. Bonds are returned to the truthful party after settlement.
|
||||
|
||||
## Registry Contracts
|
||||
|
||||
| Contract | Purpose |
|
||||
|----------|---------|
|
||||
| `Finder` | Service locator -- maps interface names to deployed addresses |
|
||||
| `Store` | Manages final fees per currency |
|
||||
| `IdentifierWhitelist` | Controls which query identifiers are supported |
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: Lux Oracle
|
||||
description: Optimistic oracle for assertions, disputes, and on-chain truth verification
|
||||
index: true
|
||||
icon: Eye
|
||||
---
|
||||
|
||||
Lux Oracle (`github.com/luxfi/oracle`) provides an optimistic oracle system for the Lux ecosystem. Contracts assert truths about the world, and disputes are resolved through an escalation game backed by bonded stakes.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Asserter ──► Oracle.assertTruth(claim, bond)
|
||||
│
|
||||
▼
|
||||
┌─────────────┐
|
||||
│ Liveness │ (challenge period)
|
||||
│ Window │
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌─────────┼──────────┐
|
||||
▼ ▼
|
||||
No Dispute Disputed
|
||||
settleAssertion() disputeAssertion()
|
||||
Bond returned ──► Escalation Manager / DVM
|
||||
resolves truth
|
||||
```
|
||||
|
||||
## Contracts
|
||||
|
||||
| Contract | Path | Purpose |
|
||||
|----------|------|---------|
|
||||
| Oracle | `prediction/Oracle.sol` | Assert-dispute-settle engine |
|
||||
| IOracle | `prediction/IOracle.sol` | Oracle interface with callbacks |
|
||||
| Finder | `registry/Finder.sol` | Service locator for ecosystem contracts |
|
||||
| Store | `registry/Store.sol` | Fee management and final fees |
|
||||
| IdentifierWhitelist | `registry/IdentifierWhitelist.sol` | Supported query identifiers |
|
||||
|
||||
## Key Concepts
|
||||
|
||||
- **Assertion** -- a bonded claim about the world (e.g. "ETH price is above 3000 at timestamp T")
|
||||
- **Liveness period** -- time window during which anyone can dispute the assertion
|
||||
- **Bond** -- ERC-20 collateral locked by the asserter and returned on truthful settlement
|
||||
- **Escalation Manager** -- optional contract that controls dispute policy and arbitration
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
forge install luxfi/oracle
|
||||
```
|
||||
|
||||
```solidity
|
||||
import "@luxfi/oracle/prediction/Oracle.sol";
|
||||
import "@luxfi/oracle/registry/Finder.sol";
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
AGPL-3.0-only (derived from UMA Protocol Optimistic Oracle).
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Getting Started---","index","---Data Feeds---","feeds","---API Reference---","api"]}
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Precompile API
|
||||
description: How to call Lux precompiles from Solidity contracts
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
Precompiles are called like regular contracts at their fixed addresses. No deployment needed.
|
||||
|
||||
## Calling Convention
|
||||
|
||||
Use a Solidity interface targeting the precompile address:
|
||||
|
||||
```solidity
|
||||
interface IPoolManager {
|
||||
struct PoolKey {
|
||||
address currency0; address currency1;
|
||||
uint24 fee; int24 tickSpacing; address hooks;
|
||||
}
|
||||
struct SwapParams {
|
||||
bool zeroForOne; int256 amountSpecified; uint160 sqrtPriceLimitX96;
|
||||
}
|
||||
function swap(PoolKey calldata key, SwapParams calldata params,
|
||||
bytes calldata hookData) external returns (int256, int256);
|
||||
}
|
||||
|
||||
IPoolManager constant POOL_MANAGER = IPoolManager(address(0x0400));
|
||||
```
|
||||
|
||||
## Post-Quantum Verification
|
||||
|
||||
```solidity
|
||||
interface IMLDsa {
|
||||
function verify(bytes calldata message, bytes calldata signature,
|
||||
bytes calldata publicKey) external view returns (bool);
|
||||
}
|
||||
|
||||
IMLDsa constant ML_DSA = IMLDsa(address(0x0600));
|
||||
```
|
||||
|
||||
## Gas Costs
|
||||
|
||||
| Category | Range | Typical Gas |
|
||||
|----------|-------|-------------|
|
||||
| Curve operations | 3,000-10,000 | Low |
|
||||
| Signature verification | 25,000-100,000 | Medium |
|
||||
| ZK proof verification | 200,000-500,000 | High |
|
||||
| FHE operations | 500,000 | Very high |
|
||||
|
||||
## Error Handling
|
||||
|
||||
Precompiles revert with standard EVM revert data on invalid input: wrong signature length, malformed public key, failed proof verification, or unsupported parameter set.
|
||||
|
||||
## Testing
|
||||
|
||||
```bash
|
||||
go test -v github.com/luxfi/precompile/...
|
||||
go test -bench=. -benchmem github.com/luxfi/precompile/dex/...
|
||||
```
|
||||
@@ -0,0 +1,63 @@
|
||||
---
|
||||
title: DeFi Precompiles
|
||||
description: Native DEX, lending, perpetuals, and cross-chain bridge precompiles
|
||||
icon: Coins
|
||||
---
|
||||
|
||||
DeFi precompiles implement a complete financial stack as native EVM operations, achieving sub-microsecond execution latency.
|
||||
|
||||
## DEX (Uniswap v4-Style)
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0400` | PoolManager | 50,000 | Singleton AMM with flash accounting |
|
||||
| `0x0401` | SwapRouter | 10,000 | Optimized swap routing |
|
||||
| `0x0402` | HooksRegistry | 3,000 | Custom hook contracts |
|
||||
| `0x0403` | FlashLoan | 5,000 | Flash loan facility |
|
||||
|
||||
### Flash Accounting
|
||||
|
||||
All operations within a transaction are netted. Token transfers happen only at the end, reducing gas costs for multi-hop swaps.
|
||||
|
||||
```solidity
|
||||
// Inside lock callback:
|
||||
BalanceDelta delta = IPoolManager(0x0400).swap(key, params, hookData);
|
||||
IPoolManager(0x0400).settle(currency0, amount0);
|
||||
IPoolManager(0x0400).take(currency1, recipient, amount1);
|
||||
```
|
||||
|
||||
### Hooks
|
||||
|
||||
Hook capabilities are encoded in the hook contract address (first 2 bytes). Available hooks: BeforeInitialize, AfterInitialize, BeforeSwap, AfterSwap, BeforeAddLiquidity, AfterAddLiquidity, BeforeDonate, AfterDonate.
|
||||
|
||||
## Lending (Alchemist)
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0410` | LendingPool | 15,000 | Supply/borrow with collateral |
|
||||
| `0x0411` | InterestRate | 5,000 | Dynamic interest rate curves |
|
||||
| `0x0412` | Liquidator | 50,000 | Liquidation engine |
|
||||
|
||||
## Perpetuals
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0420` | PerpEngine | 25,000 | Perpetual futures (up to 1111x leverage) |
|
||||
| `0x0421` | FundingRate | 10,000 | Funding rate calculation |
|
||||
| `0x0422` | InsuranceFund | 20,000 | Insurance and auto-deleveraging |
|
||||
|
||||
## Liquid Staking
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0430` | LiquidVault | 20,000 | Self-repaying loans (90% LTV) |
|
||||
| `0x0431` | LiquidFx | 25,000 | L-token to underlying conversion |
|
||||
| `0x0432` | LiquidToken | 5,000 | Liquid token registry (LUSD, LETH) |
|
||||
| `0x0433` | YieldRouter | 30,000 | Yield strategy routing |
|
||||
|
||||
## Cross-Chain
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0440` | TeleportBridge | 50,000 | Cross-chain transfer engine |
|
||||
| `0x0441` | OmnichainRouter | 40,000 | Multi-chain liquidity routing |
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Lux Precompiles
|
||||
description: 39+ native EVM precompiles for post-quantum crypto, DeFi, ZK proofs, and more
|
||||
index: true
|
||||
icon: Cpu
|
||||
---
|
||||
|
||||
Lux Precompiles (`github.com/luxfi/precompile`) extend the EVM with native operations that run at near-hardware speed. Over 39 precompiles are organized across post-quantum cryptography, DeFi, ZK proofs, privacy, and threshold signatures.
|
||||
|
||||
## Address Map
|
||||
|
||||
| Range | Category | Examples |
|
||||
|-------|----------|----------|
|
||||
| `0x0300-0x03FF` | AI/ML | AI Mining, NVTrust, Model Registry |
|
||||
| `0x0400-0x04FF` | DeFi | PoolManager (Uniswap v4), SwapRouter, Lending, Perps |
|
||||
| `0x0500-0x05FF` | Graph/Query | GraphQL, Subscriptions, Cache |
|
||||
| `0x0600-0x06FF` | Post-Quantum | ML-DSA, ML-KEM, SLH-DSA, Quasar |
|
||||
| `0x0700-0x07FF` | Privacy | FHE, ECIES, Ring Signatures, HPKE |
|
||||
| `0x0800-0x08FF` | Threshold | FROST, CGGMP21, Corona |
|
||||
| `0x0900-0x09FF` | ZK Proofs | KZG, Groth16, PLONK, Halo2 |
|
||||
| `0x0A00-0x0AFF` | Curves | secp256r1 (P-256) |
|
||||
|
||||
## Performance (M1 Max)
|
||||
|
||||
| Operation | Latency | Throughput |
|
||||
|-----------|---------|------------|
|
||||
| DEX Swap | 2.26 us | 443K ops/sec |
|
||||
| ModifyLiquidity | 2.87 us | 348K ops/sec |
|
||||
| PoolKeyID | 439 ns | 2.7M ops/sec |
|
||||
| HookPermission | 0.45 ns | 2.2B ops/sec |
|
||||
|
||||
## Chain Activation
|
||||
|
||||
| Chain | Precompiles Enabled |
|
||||
|-------|---------------------|
|
||||
| C-Chain | All (full feature set) |
|
||||
| Z-Chain (Zoo) | Warp, PoolManager, SwapRouter, AIMining, GraphQL |
|
||||
| D-Chain (DEX) | Warp, full DEX suite, GraphQL |
|
||||
| K-Chain (Keys) | Warp, PQ Crypto, Privacy, Threshold, GraphQL |
|
||||
| Q-Chain (Quantum) | Warp, full PQ suite, Corona, GraphQL |
|
||||
| B-Chain (Bridge) | Warp, TeleportBridge, GraphQL |
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
go get github.com/luxfi/precompile
|
||||
```
|
||||
|
||||
```bash
|
||||
# Run tests
|
||||
go test -v ./...
|
||||
|
||||
# Run benchmarks
|
||||
go test -bench=. -benchmem ./dex/...
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Getting Started---","index","---Categories---","pq-crypto","defi","zk","---API Reference---","api"]}
|
||||
@@ -0,0 +1,61 @@
|
||||
---
|
||||
title: Post-Quantum Precompiles
|
||||
description: ML-DSA, ML-KEM, SLH-DSA, and Quasar consensus verification
|
||||
icon: Atom
|
||||
---
|
||||
|
||||
Post-quantum precompiles provide NIST-standardized cryptographic operations at native EVM speed, protecting against future quantum computing threats.
|
||||
|
||||
## Precompile Addresses
|
||||
|
||||
| Address | Name | Standard | Gas | Description |
|
||||
|---------|------|----------|-----|-------------|
|
||||
| `0x0600` | ML_DSA | FIPS 204 | 50,000 | ML-DSA signature verification (Dilithium) |
|
||||
| `0x0601` | ML_KEM | FIPS 203 | 25,000 | ML-KEM key encapsulation (Kyber) |
|
||||
| `0x0602` | SLH_DSA | FIPS 205 | 75,000 | SLH-DSA hash-based signatures (SPHINCS+) |
|
||||
| `0x0603` | PQ_CRYPTO | -- | 30,000 | Multi-PQ operations |
|
||||
| `0x0604` | QUASAR | -- | 100,000 | Quantum consensus verification |
|
||||
|
||||
## ML-DSA (FIPS 204)
|
||||
|
||||
Lattice-based digital signatures. Three security levels:
|
||||
|
||||
| Parameter Set | Security Level | Signature Size | Public Key |
|
||||
|---------------|---------------|----------------|------------|
|
||||
| ML-DSA-44 | NIST Level 2 | 2,420 bytes | 1,312 bytes |
|
||||
| ML-DSA-65 | NIST Level 3 | 3,309 bytes | 1,952 bytes |
|
||||
| ML-DSA-87 | NIST Level 5 | 4,627 bytes | 2,592 bytes |
|
||||
|
||||
Lux uses ML-DSA-65 (192-bit security) by default.
|
||||
|
||||
## ML-KEM (FIPS 203)
|
||||
|
||||
Lattice-based key encapsulation mechanism for establishing shared secrets.
|
||||
|
||||
| Parameter Set | Security Level | Ciphertext | Public Key |
|
||||
|---------------|---------------|------------|------------|
|
||||
| ML-KEM-512 | NIST Level 1 | 768 bytes | 800 bytes |
|
||||
| ML-KEM-768 | NIST Level 3 | 1,088 bytes | 1,184 bytes |
|
||||
| ML-KEM-1024 | NIST Level 5 | 1,568 bytes | 1,568 bytes |
|
||||
|
||||
## SLH-DSA (FIPS 205)
|
||||
|
||||
Stateless hash-based signatures. Conservative choice -- security relies only on hash function properties.
|
||||
|
||||
| Parameter Set | Security | Signature Size |
|
||||
|---------------|----------|----------------|
|
||||
| SLH-DSA-SHA2-128f | NIST Level 1 | 17,088 bytes |
|
||||
| SLH-DSA-SHA2-192f | NIST Level 3 | 35,664 bytes |
|
||||
| SLH-DSA-SHA2-256f | NIST Level 5 | 49,856 bytes |
|
||||
|
||||
## Hybrid Signatures (0x0610-0x0612)
|
||||
|
||||
Combine classical and post-quantum signatures for defense in depth:
|
||||
|
||||
| Address | Scheme | Classical | Post-Quantum |
|
||||
|---------|--------|-----------|-------------|
|
||||
| `0x0610` | Hybrid BLS+Corona | BLS12-381 | Corona lattice |
|
||||
| `0x0611` | Hybrid ECDSA+ML-DSA | secp256k1 | ML-DSA-65 |
|
||||
| `0x0612` | Hybrid Schnorr+Corona | Ed25519 | Corona lattice |
|
||||
|
||||
Both signatures must verify for the hybrid to pass. Graceful degradation is not supported -- this is intentional for maximum security.
|
||||
@@ -0,0 +1,59 @@
|
||||
---
|
||||
title: ZK Precompiles
|
||||
description: Zero-knowledge proof verification, commitments, and rollup support
|
||||
icon: Eye
|
||||
---
|
||||
|
||||
ZK precompiles provide native proof verification for Groth16, PLONK, Halo2, and KZG commitments, enabling privacy-preserving transactions and ZK rollups on Lux.
|
||||
|
||||
## Proof Verification
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0900` | ZK_VERIFY | 200,000 | Generic ZK proof verification |
|
||||
| `0x0901` | GROTH16 | 200,000 | Groth16 verifier |
|
||||
| `0x0902` | PLONK | 250,000 | PLONK verifier |
|
||||
| `0x0903` | FFLONK | 250,000 | fflonk verifier |
|
||||
| `0x0904` | HALO2 | 300,000 | Halo2 verifier (no trusted setup) |
|
||||
|
||||
## Commitments
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0910` | KZG | 50,000 | KZG polynomial commitments (EIP-4844) |
|
||||
| `0x0911` | PEDERSEN | 10,000 | Pedersen commitments |
|
||||
| `0x0912` | IPA | 75,000 | Inner product arguments (Verkle trees) |
|
||||
|
||||
## Privacy
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0920` | PRIVACY_POOL | 50,000 | Confidential transaction pool |
|
||||
| `0x0921` | NULLIFIER | 5,000 | Nullifier verification (double-spend prevention) |
|
||||
| `0x0922` | COMMITMENT | 10,000 | Commitment verification |
|
||||
| `0x0923` | RANGE_PROOF | 100,000 | Range proof verification (hidden amounts) |
|
||||
|
||||
## Rollups
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0930` | ROLLUP_VERIFY | 500,000 | ZK rollup batch verification |
|
||||
| `0x0931` | STATE_ROOT | 25,000 | State root verification |
|
||||
| `0x0932` | BATCH_PROOF | 100,000 | Batch proof aggregation |
|
||||
|
||||
## Privacy Precompiles
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0700` | FHE | 500,000 | Fully Homomorphic Encryption |
|
||||
| `0x0701` | ECIES | 25,000 | Elliptic Curve Integrated Encryption |
|
||||
| `0x0702` | RING | 50,000 | Ring signatures (anonymous signing) |
|
||||
| `0x0703` | HPKE | 20,000 | Hybrid Public Key Encryption |
|
||||
|
||||
## Threshold Signatures
|
||||
|
||||
| Address | Name | Gas | Description |
|
||||
|---------|------|-----|-------------|
|
||||
| `0x0800` | FROST | 25,000 | Schnorr threshold signatures |
|
||||
| `0x0801` | CGGMP21 | 50,000 | ECDSA threshold signatures |
|
||||
| `0x0802` | CORONA | 75,000 | Post-quantum threshold lattice signatures |
|
||||
@@ -0,0 +1,74 @@
|
||||
---
|
||||
title: Transaction API
|
||||
description: Building, signing, and executing Safe transactions
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## Transaction Types
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| ETH Transfer | Send native LUX to an address |
|
||||
| ERC-20 Transfer | Send tokens to an address |
|
||||
| Contract Interaction | Call any contract function with encoded calldata |
|
||||
| Batch | Execute multiple operations in a single transaction |
|
||||
|
||||
## Transaction Structure
|
||||
|
||||
Each Safe transaction contains:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `to` | address | Destination address |
|
||||
| `value` | uint256 | Amount of native token (wei) |
|
||||
| `data` | bytes | Encoded function call data |
|
||||
| `operation` | uint8 | 0 = Call, 1 = DelegateCall |
|
||||
| `nonce` | uint256 | Safe transaction nonce |
|
||||
|
||||
## Signing
|
||||
|
||||
Transactions are signed off-chain using EIP-712 typed data. Each owner signs the transaction hash, and signatures are collected until the threshold is met.
|
||||
|
||||
```
|
||||
Transaction Hash = keccak256(
|
||||
0x19, 0x01,
|
||||
domainSeparator,
|
||||
safeTxHash
|
||||
)
|
||||
```
|
||||
|
||||
The domain separator is unique to each Safe contract instance and chain.
|
||||
|
||||
## Execution
|
||||
|
||||
Once enough signatures are collected, the transaction is executed by calling `execTransaction` on the Safe contract:
|
||||
|
||||
```
|
||||
execTransaction(
|
||||
to, value, data, operation,
|
||||
safeTxGas, baseGas, gasPrice, gasToken, refundReceiver,
|
||||
signatures
|
||||
)
|
||||
```
|
||||
|
||||
Signatures are concatenated in ascending order of signer address.
|
||||
|
||||
## Querying Safe State
|
||||
|
||||
| Query | Description |
|
||||
|-------|-------------|
|
||||
| `getOwners()` | List all current owner addresses |
|
||||
| `getThreshold()` | Current signing threshold |
|
||||
| `nonce()` | Next expected transaction nonce |
|
||||
| `isOwner(address)` | Check if an address is an owner |
|
||||
| `getTransactionHash(...)` | Compute hash for a proposed transaction |
|
||||
|
||||
## Events
|
||||
|
||||
| Event | Description |
|
||||
|-------|-------------|
|
||||
| `ExecutionSuccess` | Transaction executed successfully |
|
||||
| `ExecutionFailure` | Transaction execution reverted |
|
||||
| `AddedOwner` | New owner added to the Safe |
|
||||
| `RemovedOwner` | Owner removed from the Safe |
|
||||
| `ChangedThreshold` | Signing threshold updated |
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
title: Deploying a Safe
|
||||
description: Create and configure a multi-signature Safe wallet
|
||||
icon: Rocket
|
||||
---
|
||||
|
||||
## Create a New Safe
|
||||
|
||||
1. Navigate to the Lux Safe application
|
||||
2. Connect your wallet (MetaMask, WalletConnect, or any injected provider)
|
||||
3. Select the target chain (C-Chain, Zoo, Hanzo, SPC, or Pars)
|
||||
4. Add owner addresses and set the signing threshold
|
||||
5. Confirm the creation transaction
|
||||
|
||||
## Owner Management
|
||||
|
||||
After creation, owners can propose changes to the Safe configuration:
|
||||
|
||||
- **Add Owner**: Propose adding a new signer address
|
||||
- **Remove Owner**: Propose removing an existing signer (threshold must remain achievable)
|
||||
- **Change Threshold**: Increase or decrease the number of required signatures
|
||||
|
||||
All configuration changes require the current threshold of approvals.
|
||||
|
||||
## Transaction Flow
|
||||
|
||||
```
|
||||
Propose --> Approve (threshold reached) --> Execute
|
||||
```
|
||||
|
||||
1. Any owner proposes a transaction (ETH transfer, token transfer, or contract call)
|
||||
2. Other owners review and approve the transaction
|
||||
3. Once the threshold is met, any owner can execute the transaction on-chain
|
||||
4. The Safe nonce increments, preventing replay
|
||||
|
||||
## Network Configuration
|
||||
|
||||
To use Lux Safe on a specific chain, ensure your wallet is configured with the correct RPC endpoint:
|
||||
|
||||
| Chain | RPC URL |
|
||||
|-------|---------|
|
||||
| C-Chain | `https://api.lux.network/mainnet/ext/bc/C/rpc` |
|
||||
| Zoo | `https://api.lux.network/mainnet/ext/bc/zoo/rpc` |
|
||||
| Hanzo | `https://api.lux.network/mainnet/ext/bc/hanzo/rpc` |
|
||||
| SPC | `https://api.lux.network/mainnet/ext/bc/spc/rpc` |
|
||||
| Pars | `https://api.lux.network/mainnet/ext/bc/pars/rpc` |
|
||||
|
||||
## Static Deployment
|
||||
|
||||
Lux Safe is deployed as a static site. Build and deploy with:
|
||||
|
||||
```bash
|
||||
pnpm build
|
||||
# Output in out/ directory, deploy to any static host
|
||||
```
|
||||
|
||||
The GitHub Actions workflow deploys automatically to GitHub Pages on push to main.
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: Lux Safe
|
||||
description: Multi-signature wallet for the Lux Network
|
||||
index: true
|
||||
icon: Shield
|
||||
---
|
||||
|
||||
Lux Safe (`@luxfi/safe`) is a multi-signature wallet application for the Lux Network blockchain ecosystem. It enables teams and organizations to manage funds with configurable m-of-n signing thresholds, ensuring no single key holder can unilaterally move assets.
|
||||
|
||||
## Multi-Signature Model
|
||||
|
||||
A Safe requires a configurable number of owner approvals (threshold) before a transaction can be executed. For example, a 3-of-5 Safe requires 3 out of 5 owners to sign each transaction.
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| Owners | List of addresses that can propose and approve transactions |
|
||||
| Threshold | Minimum number of approvals required to execute |
|
||||
| Nonce | Sequential counter preventing replay attacks |
|
||||
|
||||
## Supported Chains
|
||||
|
||||
Lux Safe works across all EVM-compatible chains in the Lux ecosystem:
|
||||
|
||||
| Chain | Chain ID | Network |
|
||||
|-------|----------|---------|
|
||||
| C-Chain | 96369 | Mainnet |
|
||||
| Zoo | 200200 | Mainnet |
|
||||
| Hanzo | 36963 | Mainnet |
|
||||
| SPC | 36911 | Mainnet |
|
||||
| Pars | 494949 | Mainnet |
|
||||
|
||||
Testnet and devnet chain IDs are also supported.
|
||||
|
||||
## Technology
|
||||
|
||||
- **Framework**: Next.js 15, React 18
|
||||
- **Package**: `@luxfi/safe`
|
||||
- **UI**: `@luxfi/ui`, Tailwind CSS
|
||||
- **Auth**: `@hanzo/auth` (Hanzo IAM integration)
|
||||
- **Deployment**: Static export via GitHub Pages
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
pnpm install
|
||||
pnpm dev # start development server
|
||||
pnpm build # production build (static export)
|
||||
```
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"pages": [
|
||||
"index",
|
||||
"deployment",
|
||||
"api"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
title: Staking API
|
||||
description: P-Chain staking API endpoints for validators and delegators
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
All staking operations go through the P-Chain API at `/ext/bc/P`.
|
||||
|
||||
## Add Validator
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "platform.addValidator",
|
||||
"params": {
|
||||
"nodeID": "NodeID-...",
|
||||
"startTime": 1700000000,
|
||||
"endTime": 1731536000,
|
||||
"stakeAmount": 2000000000000,
|
||||
"rewardAddress": "P-lux1...",
|
||||
"delegationFeeRate": 200000
|
||||
},
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `nodeID` | string | Node identifier from `info.getNodeID` |
|
||||
| `startTime` | uint64 | Unix timestamp for staking start |
|
||||
| `endTime` | uint64 | Unix timestamp for staking end |
|
||||
| `stakeAmount` | uint64 | Stake in nLUX (1 LUX = 1e9 nLUX) |
|
||||
| `rewardAddress` | string | P-Chain address for reward payout |
|
||||
| `delegationFeeRate` | uint32 | Fee in millionths (200000 = 2%) |
|
||||
|
||||
## Add Delegator
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "platform.addDelegator",
|
||||
"params": {
|
||||
"nodeID": "NodeID-...",
|
||||
"startTime": 1700000000,
|
||||
"endTime": 1731536000,
|
||||
"stakeAmount": 25000000000,
|
||||
"rewardAddress": "P-lux1..."
|
||||
},
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
## Query Validators
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "platform.getCurrentValidators",
|
||||
"params": {"subnetID": "11111111111111111111111111111111LpoYY"},
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
Returns an array of active validators with `nodeID`, `stakeAmount`, `startTime`, `endTime`, `uptime`, `delegationFee`, and `delegators`.
|
||||
|
||||
## Query Pending Validators
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "platform.getPendingValidators",
|
||||
"params": {"subnetID": "11111111111111111111111111111111LpoYY"},
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
## Query Staking Status
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"method": "platform.getMinStake",
|
||||
"params": {},
|
||||
"id": 1
|
||||
}
|
||||
```
|
||||
|
||||
Returns `minValidatorStake` and `minDelegatorStake` in nLUX.
|
||||
|
||||
## API Endpoint
|
||||
|
||||
| Network | URL |
|
||||
|---------|-----|
|
||||
| Mainnet | `https://api.lux.network/mainnet/ext/bc/P` |
|
||||
| Testnet | `https://api.lux.network/testnet/ext/bc/P` |
|
||||
@@ -0,0 +1,60 @@
|
||||
---
|
||||
title: Delegation
|
||||
description: Delegate LUX to validators and earn proportional rewards
|
||||
icon: Users
|
||||
---
|
||||
|
||||
Delegation lets LUX holders earn staking rewards without running a node. Delegators choose a validator and lock their LUX for a defined period.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. Choose a validator with high uptime and a competitive delegation fee.
|
||||
2. Submit an `addDelegator` transaction on the P-Chain.
|
||||
3. Your LUX is locked for the staking period.
|
||||
4. At the end of the period, you receive your stake plus rewards (minus the validator's delegation fee).
|
||||
|
||||
## Requirements
|
||||
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| Minimum delegation | 25 LUX |
|
||||
| Minimum period | 2 weeks |
|
||||
| Maximum period | 1 year |
|
||||
| Delegation fee | Set by validator (2% - 100%) |
|
||||
|
||||
## Delegate via CLI
|
||||
|
||||
```bash
|
||||
lux network delegator add \
|
||||
--node-id=NodeID-... \
|
||||
--stake-amount=100 \
|
||||
--start-time=$(date -u +%s) \
|
||||
--end-time=$(($(date -u +%s) + 2592000))
|
||||
```
|
||||
|
||||
## Rewards Calculation
|
||||
|
||||
Delegator rewards depend on three factors:
|
||||
|
||||
- **Stake weight**: Your delegation as a fraction of the validator's total stake.
|
||||
- **Validator uptime**: Must exceed 80% for rewards to be distributed.
|
||||
- **Delegation fee**: The validator's cut (e.g., 2% means you receive 98% of your proportional reward).
|
||||
|
||||
```
|
||||
Your Reward = (Your Delegation / Total Validator Stake) * Total Reward * (1 - DelegationFee)
|
||||
```
|
||||
|
||||
## Choosing a Validator
|
||||
|
||||
Check validator metrics before delegating:
|
||||
|
||||
```bash
|
||||
curl -s -X POST --data '{
|
||||
"jsonrpc":"2.0",
|
||||
"method":"platform.getCurrentValidators",
|
||||
"params":{},
|
||||
"id":1
|
||||
}' -H 'content-type:application/json' http://127.0.0.1:9630/ext/bc/P | jq '.result.validators[] | {nodeID, uptime, delegationFee}'
|
||||
```
|
||||
|
||||
Look for validators with uptime above 95% and delegation fees at or near the 2% minimum.
|
||||
@@ -0,0 +1,43 @@
|
||||
---
|
||||
title: Staking
|
||||
description: Validator staking, delegation, and liquid staking on Lux Network
|
||||
icon: Layers
|
||||
---
|
||||
|
||||
Lux Network uses a proof-of-stake consensus model. LUX holders can validate, delegate, or liquid-stake to earn rewards while securing the network.
|
||||
|
||||
## Staking Options
|
||||
|
||||
| Method | Min Stake | Lock Period | Rewards | Governance |
|
||||
|--------|-----------|-------------|---------|------------|
|
||||
| **Validator** | 2,000 LUX | 2 weeks min | Base + delegation fees | Direct |
|
||||
| **Delegation** | 25 LUX | 2 weeks min | Validator-shared | Via validator |
|
||||
| **Liquid (xLUX)** | None | None | Protocol fees + validator rewards | vLUX voting |
|
||||
|
||||
## How Rewards Work
|
||||
|
||||
Validators earn rewards proportional to their uptime and stake weight. The P-Chain distributes rewards at the end of each staking period.
|
||||
|
||||
```
|
||||
Validator Stake + Delegated Stake → Uptime-Weighted Rewards
|
||||
│ │
|
||||
▼ ▼
|
||||
Validator Share Delegator Share
|
||||
(minus delegation fee) (proportional)
|
||||
```
|
||||
|
||||
## Reward Parameters
|
||||
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| Maximum annual reward rate | 10% |
|
||||
| Minimum uptime for rewards | 80% |
|
||||
| Minimum staking period | 2 weeks |
|
||||
| Maximum staking period | 1 year |
|
||||
| Delegation fee range | 2% - 100% |
|
||||
|
||||
## Quick Start
|
||||
|
||||
1. **Validate** -- Run a node and register as a validator on the P-Chain.
|
||||
2. **Delegate** -- Choose a validator and delegate your LUX via the wallet or CLI.
|
||||
3. **Liquid stake** -- Deposit LUX into the xLUX vault for instant liquidity with no lock.
|
||||
@@ -0,0 +1,58 @@
|
||||
---
|
||||
title: Liquid Staking
|
||||
description: Stake LUX via xLUX with no lock period and full DeFi composability
|
||||
icon: Waves
|
||||
---
|
||||
|
||||
Liquid staking through the xLUX vault lets you earn staking rewards and protocol fees without locking your LUX. You receive xLUX shares that are freely transferable and usable across DeFi.
|
||||
|
||||
## How It Works
|
||||
|
||||
1. Deposit LUX into the LiquidLUX vault.
|
||||
2. Receive xLUX shares proportional to the current exchange rate.
|
||||
3. The vault accumulates protocol fees and validator rewards, increasing the LUX-per-xLUX ratio.
|
||||
4. Withdraw at any time by burning xLUX to receive your LUX plus earned yield.
|
||||
|
||||
## Comparison with P-Chain Staking
|
||||
|
||||
| Feature | P-Chain Staking | Liquid Staking (xLUX) |
|
||||
|---------|----------------|----------------------|
|
||||
| Lock period | 2 weeks - 1 year | None |
|
||||
| Minimum | 25 LUX (delegation) | No minimum |
|
||||
| Yield source | Validator rewards | All protocol fees + validator rewards |
|
||||
| Composability | None (locked) | Full DeFi (collateral, LP, trading) |
|
||||
| Governance | None | vLUX voting power |
|
||||
| Slashing risk | Direct | Socialized with reserve buffer |
|
||||
|
||||
## DeFi Composability
|
||||
|
||||
xLUX can be used as collateral, provided as liquidity, or traded on any Lux DEX:
|
||||
|
||||
- **Perps collateral**: Use xLUX as margin for leveraged positions.
|
||||
- **AMM liquidity**: Provide xLUX/LUSD or xLUX/WLUX liquidity and earn swap fees on top of vault yield.
|
||||
- **Governance**: xLUX counts toward vLUX voting power in the DAO.
|
||||
|
||||
## Yield Stacking Strategy
|
||||
|
||||
```
|
||||
Deposit LUX → xLUX (vault yield)
|
||||
│
|
||||
├── Use as Perps collateral (leveraged exposure)
|
||||
├── Provide AMM liquidity (swap fees)
|
||||
└── Vote in governance (vLUX)
|
||||
```
|
||||
|
||||
## Contract
|
||||
|
||||
Deposit and withdraw through the `LiquidLUX` contract. See the [Liquid Protocol API](/liquid/api) for the full interface.
|
||||
|
||||
```solidity
|
||||
// Deposit
|
||||
uint256 shares = liquidLux.deposit(1000e18);
|
||||
|
||||
// Check value
|
||||
uint256 luxValue = liquidLux.convertToAssets(shares);
|
||||
|
||||
// Withdraw
|
||||
uint256 luxReceived = liquidLux.withdraw(shares);
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","validator","delegation","liquid","api"]}
|
||||
@@ -0,0 +1,66 @@
|
||||
---
|
||||
title: Become a Validator
|
||||
description: Hardware requirements, node setup, and P-Chain registration
|
||||
icon: Server
|
||||
---
|
||||
|
||||
Validators secure the Lux Network by participating in consensus. They stake LUX on the P-Chain and run a node with sufficient uptime to earn rewards.
|
||||
|
||||
## Hardware Requirements
|
||||
|
||||
| Component | Minimum | Recommended |
|
||||
|-----------|---------|-------------|
|
||||
| CPU | 8 cores | 16 cores |
|
||||
| RAM | 16 GB | 32 GB |
|
||||
| Storage | 500 GB SSD | 1 TB NVMe |
|
||||
| Network | 100 Mbps | 1 Gbps |
|
||||
| OS | Ubuntu 22.04 | Ubuntu 24.04 |
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install the Lux node binary:
|
||||
|
||||
```bash
|
||||
curl -sSfL https://raw.githubusercontent.com/luxfi/node/main/scripts/install.sh | sh
|
||||
```
|
||||
|
||||
2. Start the node and wait for it to bootstrap:
|
||||
|
||||
```bash
|
||||
luxd --network-id=1
|
||||
```
|
||||
|
||||
3. Verify the node is healthy:
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:9630/ext/health | jq .healthy
|
||||
```
|
||||
|
||||
## Register as a Validator
|
||||
|
||||
Use the Lux CLI or wallet to submit an `addValidator` transaction on the P-Chain.
|
||||
|
||||
```bash
|
||||
lux network validator add \
|
||||
--node-id=$(curl -s -X POST --data '{"jsonrpc":"2.0","method":"info.getNodeID","params":{},"id":1}' \
|
||||
-H 'content-type:application/json' http://127.0.0.1:9630/ext/info | jq -r .result.nodeID) \
|
||||
--stake-amount=2000 \
|
||||
--start-time=$(date -u +%s) \
|
||||
--end-time=$(($(date -u +%s) + 31536000)) \
|
||||
--delegation-fee=2
|
||||
```
|
||||
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| Minimum stake | 2,000 LUX |
|
||||
| Minimum period | 2 weeks |
|
||||
| Maximum period | 1 year |
|
||||
| Delegation fee | 2% minimum |
|
||||
|
||||
## BLS Signer Key
|
||||
|
||||
Each validator requires a 32-byte BLS signer key (separate from the TLS staker certificate). The genesis `initialStakers.signer` field must match the node's actual BLS public key. Place `signer.key` alongside `staker.crt` and `staker.key` in the staking directory.
|
||||
|
||||
## Uptime
|
||||
|
||||
Validators must maintain at least 80% uptime to receive rewards. Uptime is measured by peer sampling with `consensus-sample-size=5` and `quorum-size=4`.
|
||||
@@ -0,0 +1,108 @@
|
||||
---
|
||||
title: AMM
|
||||
description: Automated Market Makers - V2 constant-product, V3 concentrated liquidity, and StableSwap
|
||||
icon: ArrowLeftRight
|
||||
---
|
||||
|
||||
The AMM module provides three pool types for different trading scenarios. All AMM contracts are in `contracts/amm/`.
|
||||
|
||||
## V2 (Constant Product)
|
||||
|
||||
Classic `x * y = k` AMM based on Uniswap V2. Best for long-tail token pairs.
|
||||
|
||||
| Contract | Import |
|
||||
|----------|--------|
|
||||
| **AMMV2Factory** | `@luxfi/contracts/amm/AMMV2Factory.sol` |
|
||||
| **AMMV2Pair** | `@luxfi/contracts/amm/AMMV2Pair.sol` |
|
||||
| **AMMV2Router** | `@luxfi/contracts/amm/AMMV2Router.sol` |
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/amm/AMMV2Router.sol";
|
||||
|
||||
AMMV2Router router = AMMV2Router(ROUTER_ADDRESS);
|
||||
|
||||
// Add liquidity
|
||||
router.addLiquidity(
|
||||
tokenA, tokenB,
|
||||
amountADesired, amountBDesired,
|
||||
amountAMin, amountBMin,
|
||||
to, deadline
|
||||
);
|
||||
|
||||
// Swap exact tokens for tokens
|
||||
router.swapExactTokensForTokens(
|
||||
amountIn, amountOutMin,
|
||||
path, to, deadline
|
||||
);
|
||||
```
|
||||
|
||||
## V3 (Concentrated Liquidity)
|
||||
|
||||
Uniswap V3-style concentrated liquidity. LPs provide liquidity within specific price ranges for higher capital efficiency.
|
||||
|
||||
| Contract | Import |
|
||||
|----------|--------|
|
||||
| **AMMV3Factory** | `@luxfi/contracts/amm/AMMV3Factory.sol` |
|
||||
| **AMMV3Pool** | `@luxfi/contracts/amm/AMMV3Pool.sol` |
|
||||
|
||||
Fee tiers: 0.01% (1 tick), 0.05% (10 ticks), 0.3% (60 ticks), 1% (200 ticks).
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/amm/AMMV3Factory.sol";
|
||||
|
||||
AMMV3Factory factory = AMMV3Factory(FACTORY_ADDRESS);
|
||||
|
||||
// Create pool with 0.3% fee
|
||||
address pool = factory.createPool(tokenA, tokenB, 3000);
|
||||
```
|
||||
|
||||
## StableSwap (Curve-Style)
|
||||
|
||||
Optimized for pegged assets (stablecoins, wrapped tokens) using the StableSwap invariant. Supports 2-4 token pools with minimal slippage between like-kind assets.
|
||||
|
||||
| Contract | Import |
|
||||
|----------|--------|
|
||||
| **StableSwap** | `@luxfi/contracts/amm/StableSwap.sol` |
|
||||
| **StableSwapFactory** | `@luxfi/contracts/amm/StableSwapFactory.sol` |
|
||||
|
||||
The amplification coefficient `A` controls pool behavior -- higher values produce tighter peg, lower values behave more like constant-product.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/amm/StableSwap.sol";
|
||||
|
||||
StableSwap pool = StableSwap(POOL_ADDRESS);
|
||||
|
||||
// Swap token index 0 for token index 1
|
||||
uint256 dy = pool.exchange(0, 1, dx, minDy);
|
||||
|
||||
// Add liquidity (balanced or imbalanced)
|
||||
uint256 lpTokens = pool.addLiquidity(amounts, minMintAmount);
|
||||
|
||||
// Remove liquidity in a single token
|
||||
uint256 received = pool.removeLiquidityOneCoin(lpAmount, tokenIndex, minAmount);
|
||||
```
|
||||
|
||||
### StableSwap Invariant
|
||||
|
||||
```
|
||||
A * n^n * sum(x_i) + D = A * D * n^n + D^(n+1) / (n^n * prod(x_i))
|
||||
```
|
||||
|
||||
Pool `D` is computed iteratively using Newton's method with guaranteed convergence in under 255 iterations.
|
||||
|
||||
### Dynamic A Parameter
|
||||
|
||||
The amplification coefficient can be ramped over time (minimum 24-hour ramp period) to adjust pool characteristics without redeployment:
|
||||
|
||||
```solidity
|
||||
// Ramp A from current value to 500 over 48 hours
|
||||
pool.rampA(500, block.timestamp + 48 hours);
|
||||
```
|
||||
|
||||
## Fee Structure
|
||||
|
||||
| Pool Type | Swap Fee | Admin Fee |
|
||||
|-----------|----------|-----------|
|
||||
| V2 Pair | 0.3% | Protocol-defined |
|
||||
| V3 Pool | 0.01% - 1% | Per fee tier |
|
||||
| StableSwap | 0.04% | 50% of swap fee |
|
||||
@@ -0,0 +1,176 @@
|
||||
---
|
||||
title: API Reference
|
||||
description: Key interfaces and function signatures for the Lux Standard Library
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
This page lists the primary Solidity interfaces for integrating with the Lux Standard Library. All imports use the `@luxfi/contracts/` prefix.
|
||||
|
||||
## Tokens
|
||||
|
||||
### LRC20
|
||||
|
||||
Standard ERC20 with Lux naming conventions.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/tokens/LRC20.sol";
|
||||
|
||||
// Core ERC20 functions
|
||||
function totalSupply() external view returns (uint256);
|
||||
function balanceOf(address account) external view returns (uint256);
|
||||
function transfer(address to, uint256 amount) external returns (bool);
|
||||
function approve(address spender, uint256 amount) external returns (bool);
|
||||
function transferFrom(address from, address to, uint256 amount) external returns (bool);
|
||||
```
|
||||
|
||||
### LRC20B (Bridgeable)
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/bridge/LRC20B.sol";
|
||||
|
||||
function mint(address to, uint256 amount) external onlyAdmin;
|
||||
function burn(address from, uint256 amount) external onlyAdmin;
|
||||
```
|
||||
|
||||
## Oracle
|
||||
|
||||
### IOracle
|
||||
|
||||
Unified price oracle consumed by all DeFi protocols.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/oracle/IOracle.sol";
|
||||
|
||||
// Get single asset price
|
||||
function getPrice(address asset) external view returns (uint256 price, uint256 timestamp);
|
||||
|
||||
// Get price optimized for perps (with spread)
|
||||
function getPriceForPerps(address asset, bool maximize) external view returns (uint256);
|
||||
|
||||
// Batch price query
|
||||
function getPrices(address[] calldata assets) external view returns (uint256[] memory prices, uint256[] memory timestamps);
|
||||
|
||||
// Health check
|
||||
function health() external view returns (bool healthy, uint256 sourceCount);
|
||||
```
|
||||
|
||||
## Liquid Protocol
|
||||
|
||||
### LiquidLUX (ERC4626)
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/liquid/LiquidLUX.sol";
|
||||
|
||||
// Deposit WLUX, receive xLUX shares
|
||||
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
|
||||
|
||||
// Withdraw WLUX by burning xLUX
|
||||
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
|
||||
|
||||
// Redeem xLUX for WLUX
|
||||
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
|
||||
|
||||
// Fee intake
|
||||
function receiveFees(uint256 amount, bytes32 feeType) external;
|
||||
function depositValidatorRewards() external payable;
|
||||
```
|
||||
|
||||
## Governance
|
||||
|
||||
### Karma
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/governance/Karma.sol";
|
||||
|
||||
function balanceOf(address account) external view returns (uint256);
|
||||
function isActive(address account) external view returns (bool);
|
||||
function getDecayRate(address account) external view returns (uint256);
|
||||
function getActivityStatus(address account) external view returns (
|
||||
uint256 karma, bool verified, bool activeThisMonth,
|
||||
bool activeLastMonth, uint256 currentDecayRate, bool hasKarmaFloor
|
||||
);
|
||||
```
|
||||
|
||||
### GaugeController
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/governance/GaugeController.sol";
|
||||
|
||||
function voteForGaugeWeights(address gauge, uint256 weight) external;
|
||||
function gaugeRelativeWeight(address gauge, uint256 time) external view returns (uint256);
|
||||
```
|
||||
|
||||
## Markets (Lending)
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/markets/Markets.sol";
|
||||
|
||||
function supplyCollateral(bytes32 id, uint256 amount, address onBehalf, bytes calldata data) external;
|
||||
function borrow(bytes32 id, uint256 amount, address onBehalf, address receiver) external;
|
||||
function repay(bytes32 id, uint256 amount, address onBehalf, bytes calldata data) external;
|
||||
function withdrawCollateral(bytes32 id, uint256 amount, address onBehalf, address receiver) external;
|
||||
function liquidate(bytes32 id, address borrower, uint256 seized, uint256 repaidShares, bytes calldata data) external;
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/options/Options.sol";
|
||||
|
||||
function createSeries(address underlying, address quote, uint256 strike, uint256 expiry, OptionType optionType, SettlementType settlement) external returns (bytes32);
|
||||
function write(bytes32 seriesId, uint256 amount) external returns (uint256 positionId);
|
||||
function exercise(bytes32 seriesId, uint256 amount) external returns (uint256 payout);
|
||||
function settle(bytes32 seriesId) external returns (uint256 collateralReturned);
|
||||
function getCollateralRequired(bytes32 seriesId, uint256 amount) external view returns (uint256);
|
||||
function getExercisePayout(bytes32 seriesId, uint256 amount) external view returns (uint256);
|
||||
```
|
||||
|
||||
## LSSVM (NFT AMM)
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/lssvm/LSSVMPairFactory.sol";
|
||||
|
||||
function createPairETH(address nft, ICurve curve, LSSVMPair.PoolType poolType, uint128 delta, uint96 fee, uint128 spotPrice, uint256[] calldata ids) external payable returns (LSSVMPair);
|
||||
```
|
||||
|
||||
## Precompile Interfaces
|
||||
|
||||
```solidity
|
||||
// Post-quantum signatures
|
||||
import "@luxfi/contracts/precompile/interfaces/IMLDSA.sol";
|
||||
function verify(bytes calldata pubKey, bytes calldata msg, bytes calldata sig) external view returns (bool);
|
||||
|
||||
// Threshold signatures
|
||||
import "@luxfi/contracts/precompile/interfaces/IFROST.sol";
|
||||
function verify(uint8 threshold, uint8 total, bytes calldata pubKey, bytes32 msgHash, bytes calldata sig) external view returns (bool);
|
||||
|
||||
// ZK proofs
|
||||
import "@luxfi/contracts/precompile/interfaces/IZK.sol";
|
||||
function verifyProof(bytes calldata proof, bytes calldata publicInputs) external view returns (bool);
|
||||
|
||||
// Cross-chain messaging
|
||||
import "@luxfi/contracts/precompile/interfaces/IWarp.sol";
|
||||
function sendWarpMessage(bytes calldata payload) external returns (bytes32 messageID);
|
||||
function getVerifiedWarpMessage(uint32 index) external view returns (WarpMessage memory);
|
||||
```
|
||||
|
||||
## FHE (Confidential Computing)
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/fhe/FHE.sol";
|
||||
|
||||
// Encrypted arithmetic
|
||||
function add(euint64 a, euint64 b) internal returns (euint64);
|
||||
function sub(euint64 a, euint64 b) internal returns (euint64);
|
||||
function mul(euint64 a, euint64 b) internal returns (euint64);
|
||||
|
||||
// Encrypted comparison
|
||||
function lt(euint64 a, euint64 b) internal returns (ebool);
|
||||
function gt(euint64 a, euint64 b) internal returns (ebool);
|
||||
|
||||
// Access control
|
||||
function allow(euint64 ctHash, address account) internal;
|
||||
|
||||
// Random number generation
|
||||
function randomEuint64() internal returns (euint64);
|
||||
```
|
||||
@@ -0,0 +1,101 @@
|
||||
---
|
||||
title: Deployment
|
||||
description: Deployed contract addresses per chain and deployment scripts
|
||||
icon: Rocket
|
||||
---
|
||||
|
||||
The full DeFi stack is deployed via `script/DeployFullStack.s.sol` in 12 phases. Additional governance contracts are deployed via `script/DeployGovernanceSuite.s.sol`.
|
||||
|
||||
## Deployment Scripts
|
||||
|
||||
```bash
|
||||
# Local deployment (start anvil first)
|
||||
anvil --chain-id 96369 --mnemonic "$LUX_MNEMONIC" --balance 10000000000
|
||||
forge script script/DeployFullStack.s.sol --rpc-url http://127.0.0.1:8545 --broadcast -vvv
|
||||
|
||||
# Mainnet deployment
|
||||
forge script script/DeployFullStack.s.sol --rpc-url lux --broadcast --verify
|
||||
|
||||
# Testnet deployment
|
||||
forge script script/DeployFullStack.s.sol --rpc-url lux_testnet --broadcast --verify
|
||||
```
|
||||
|
||||
## Deployment Phases
|
||||
|
||||
| Phase | Contracts | Description |
|
||||
|-------|-----------|-------------|
|
||||
| 1 | WLUX, LUSD, LETH, LBTC | Core tokens |
|
||||
| 2 | StakedLUX | LUX staking |
|
||||
| 3 | LiquidLUX | Master yield vault (xLUX) |
|
||||
| 4 | AMMV2Factory, AMMV2Router | AMM DEX |
|
||||
| 5 | 5 LP pools | Core trading pairs |
|
||||
| 6 | FeeSplitter, ValidatorVault | Fee distribution |
|
||||
| 7 | DIDRegistry | Identity/DID |
|
||||
| 8 | Governor, Timelock, vLUX, GaugeController, Karma, DLUX | Governance |
|
||||
| 9 | FeeSplitter wiring | Treasury integration |
|
||||
| 10 | LinearCurve, ExponentialCurve, LSSVMFactory, LSSVMRouter | NFT AMM |
|
||||
| 11 | Markets | Morpho-style lending |
|
||||
| 12 | Perps | Perpetual futures |
|
||||
|
||||
## C-Chain Mainnet (96369)
|
||||
|
||||
| Contract | Address |
|
||||
|----------|---------|
|
||||
| **WLUX** | `0x52c84043cd9c865236f11d9fc9f56aa003c1f922` |
|
||||
| **AI** | `0xa4cd3b0eb6e5ab5d8ce4065bccd70040adab1f00` |
|
||||
|
||||
RPC: `https://api.lux.network/ext/bc/C/rpc`
|
||||
|
||||
## C-Chain Testnet (96368)
|
||||
|
||||
| Contract | Address |
|
||||
|----------|---------|
|
||||
| **WLUX** | `0xc65ea8882020af7cda7854d590c6fcd34bf364ec` |
|
||||
| **LUSD** | `0x413e4a820635702ec199bc5b62dcbca1749851bf` |
|
||||
| **LETH** | `0x9378b62fc172d2a4f715d7ecf49de0362f1bb702` |
|
||||
| **LBTC** | `0x7fc4f8a926e47fa3587c0d7658c00e7489e67916` |
|
||||
| **LiquidLUX** | `0x00947bbdc619974b0eddaf103b981f3273a3e8da` |
|
||||
|
||||
RPC: `https://api.lux-test.network/ext/bc/C/rpc`
|
||||
|
||||
## C-Chain Devnet (96370)
|
||||
|
||||
| Contract | Address |
|
||||
|----------|---------|
|
||||
| **WLUX** | `0xc65ea8882020Af7CDa7854d590C6Fcd34BF364ec` |
|
||||
| **DLUX** | `0x316520ca05eaC5d2418F562a116091F1b22Bf6e0` |
|
||||
| **Timelock** | `0x80f3bd0Bdf7861487dDDA61bc651243ecB8B5072` |
|
||||
| **vLUX** | `0x91954cf6866d557C5CA1D2f384D204bcE9DFfd5a` |
|
||||
| **DAO Treasury** | `0xC764A58Ee3C5bAE3008C034E566352424be933F3` |
|
||||
| **Markets** | `0x6fc44509a32E513bE1aa00d27bb298e63830C6A8` |
|
||||
| **Perps** | `0xb2ee1CE7b84853b83AA08702aD0aD4D79711882D` |
|
||||
| **LSSVM Factory** | `0x0570b2c59976E87D37d3a9915750BFf131d295D6` |
|
||||
| **GaugeController** | `0x26328AC03d07BD9A7Caaafbde39F9b56B5449240` |
|
||||
| **Karma** | `0x97c265001EB088E1dE2F77A13a62B708014c9e68` |
|
||||
| **Governor** | `0x6fc44509a32E513bE1aa00d27bb298e63830C6A8` |
|
||||
| **Options** | `0xac604Fd2F423Ea738de9C0d6Eb03eBA6F90b63FB` |
|
||||
| **Streams** | `0xd9e69a0A38BF48898456170CB3B4451cBaF5F597` |
|
||||
| **Cover** | `0x92d057F8B4132Ca8Aa237fbd4C41F9c57079582E` |
|
||||
|
||||
RPC: `https://api.lux-dev.network/ext/bc/C/rpc`
|
||||
|
||||
## AMM Production Addresses (Shared via CREATE2)
|
||||
|
||||
These addresses are identical across LUX mainnet, testnet, and Zoo:
|
||||
|
||||
| Contract | Address |
|
||||
|----------|---------|
|
||||
| **V2 Factory** | `0xD173926A10A0C4eCd3A51B1422270b65Df0551c1` |
|
||||
| **V2 Router** | `0xAe2cf1E403aAFE6C05A5b8Ef63EB19ba591d8511` |
|
||||
| **V3 Factory** | `0x80bBc7C4C7a59C899D1B37BC14539A22D5830a84` |
|
||||
| **V3 Swap Router** | `0x939bC0Bca6F9B9c52E6e3AD8A3C590b5d9B9D10E` |
|
||||
| **Multicall** | `0xd25F88CBdAe3c2CCA3Bb75FC4E723b44C0Ea362F` |
|
||||
| **NFT Position Manager** | `0x7a4C48B9dae0b7c396569b34042fcA604150Ee28` |
|
||||
|
||||
## Network Configuration
|
||||
|
||||
| Network | Network ID | C-Chain ID | RPC |
|
||||
|---------|------------|-----------|-----|
|
||||
| Mainnet | 1 | 96369 | `https://api.lux.network/ext/bc/C/rpc` |
|
||||
| Testnet | 2 | 96368 | `https://api.lux-test.network/ext/bc/C/rpc` |
|
||||
| Devnet | 3 | 96370 | `https://api.lux-dev.network/ext/bc/C/rpc` |
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
title: Governance
|
||||
description: Governor, Timelock, vLUX voting power, Karma reputation, DLUX emissions, and GaugeController
|
||||
icon: Vote
|
||||
---
|
||||
|
||||
The governance module (`contracts/governance/`) implements a full on-chain governance stack with reputation-weighted voting, soulbound Karma, and gauge-directed emissions.
|
||||
|
||||
## Token Stack
|
||||
|
||||
| Token | Type | Purpose |
|
||||
|-------|------|---------|
|
||||
| **xLUX** | Transferable, yield-bearing | LiquidLUX vault shares |
|
||||
| **DLUX** | Transferable, rebasing | Governance token with collateral backing |
|
||||
| **vLUX** | Non-transferable | Aggregated voting power (xLUX + DLUX) |
|
||||
| **Karma (K)** | Soulbound | Reputation score with activity-driven decay |
|
||||
|
||||
### Voting Power Formula
|
||||
|
||||
```
|
||||
vLUX = DLUX * sqrt(K / 100) * (1 + lock_months * 0.1)
|
||||
```
|
||||
|
||||
Quadratic Karma scaling reduces whale dominance. Longer lock periods amplify voting weight.
|
||||
|
||||
## Governor and Timelock
|
||||
|
||||
Standard OpenZeppelin Governor with Timelock execution delay.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/governance/Governor.sol";
|
||||
|
||||
Governor governor = Governor(GOVERNOR_ADDRESS);
|
||||
|
||||
// Create proposal
|
||||
uint256 proposalId = governor.propose(
|
||||
targets, values, calldatas, "Increase fee to 0.5%"
|
||||
);
|
||||
|
||||
// Cast vote (0=Against, 1=For, 2=Abstain)
|
||||
governor.castVote(proposalId, 1);
|
||||
|
||||
// Execute after timelock delay
|
||||
governor.execute(targets, values, calldatas, descriptionHash);
|
||||
```
|
||||
|
||||
## Karma (K) -- Soulbound Reputation
|
||||
|
||||
Karma is a non-transferable reputation token. It decays based on activity and provides a floor for verified DID holders.
|
||||
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| Active decay | 1% per year (at least 1 tx/month) |
|
||||
| Inactive decay | 10% per year |
|
||||
| Verified DID floor | 50 K minimum |
|
||||
| Max Karma | 1,000 K soft cap |
|
||||
| Activity period | 30 days |
|
||||
|
||||
### KarmaMinter
|
||||
|
||||
DAO-controlled minting for positive ecosystem actions:
|
||||
|
||||
| Event | Base K | Cooldown |
|
||||
|-------|--------|----------|
|
||||
| DID verification | 100 | 1 year |
|
||||
| Proposal passed | 50 | None |
|
||||
| Vote cast | 1 | None |
|
||||
| Liquidity provided | 10 | 1 day |
|
||||
| Bug bounty | 100 | None |
|
||||
|
||||
### Strike Mechanism
|
||||
|
||||
Users can burn their own Karma to reduce another user's Karma at a 2:1 ratio (burn 2K to strike 1K from target), capped at 10% of the target's balance per day.
|
||||
|
||||
## DLUX -- Governance Token
|
||||
|
||||
Rebasing governance token with collateral-backed minting via `DLUXMinter`.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/governance/DLUXMinter.sol";
|
||||
|
||||
DLUXMinter minter = DLUXMinter(MINTER_ADDRESS);
|
||||
|
||||
// Collateral-backed minting: deposit LUX, receive DLUX 1:1
|
||||
uint256 dlux = minter.depositCollateral(luxAmount);
|
||||
|
||||
// Withdraw: burn DLUX, receive LUX back
|
||||
uint256 lux = minter.withdrawCollateral(dluxAmount);
|
||||
```
|
||||
|
||||
Protocol contracts can also emit DLUX as rewards for validator bonuses, LP provision, and staking milestones, all controlled by the DAO via Timelock.
|
||||
|
||||
## GaugeController
|
||||
|
||||
Directs protocol emissions across pools and fee recipients. vLUX holders vote on gauge weights to determine how rewards are distributed.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/governance/GaugeController.sol";
|
||||
|
||||
GaugeController gauge = GaugeController(GAUGE_ADDRESS);
|
||||
|
||||
// Vote for a gauge (allocate voting weight)
|
||||
gauge.voteForGaugeWeights(gaugeAddress, weight);
|
||||
|
||||
// Read current gauge weight
|
||||
uint256 w = gauge.gaugeRelativeWeight(gaugeAddress, block.timestamp);
|
||||
```
|
||||
|
||||
## Role Hierarchy
|
||||
|
||||
| Role | Holder | Permissions |
|
||||
|------|--------|-------------|
|
||||
| `DEFAULT_ADMIN_ROLE` | Deployer, then multisig | Manage all roles |
|
||||
| `GOVERNOR_ROLE` | Timelock (DAO) | Configure mint/emission params |
|
||||
| `HOOK_ROLE` | Protocol contracts | Trigger Karma minting |
|
||||
| `EMITTER_ROLE` | Protocol contracts | Trigger DLUX emissions |
|
||||
@@ -0,0 +1,137 @@
|
||||
---
|
||||
title: Identity (DID)
|
||||
description: W3C-compliant Decentralized Identity Registry, Soulbound NFTs, and on-chain reputation
|
||||
icon: Fingerprint
|
||||
---
|
||||
|
||||
The Identity module (`contracts/identity/`) implements W3C-compliant Decentralized Identifiers (DIDs), soulbound identity NFTs, and on-chain reputation linked to the Karma governance system.
|
||||
|
||||
## DID Registry
|
||||
|
||||
The `DIDRegistry` stores DID documents on-chain following the W3C DID Core specification. Each DID is identified by its Ethereum address and can have multiple delegates, attributes, and service endpoints.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/identity/DIDRegistry.sol";
|
||||
|
||||
DIDRegistry registry = DIDRegistry(REGISTRY_ADDRESS);
|
||||
|
||||
// Register a DID attribute (e.g., service endpoint)
|
||||
registry.setAttribute(
|
||||
identity,
|
||||
"did/svc/MessagingService",
|
||||
"https://messaging.example.com",
|
||||
86400 // validity in seconds
|
||||
);
|
||||
|
||||
// Add a delegate (e.g., signing key)
|
||||
registry.addDelegate(
|
||||
identity,
|
||||
"sigAuth",
|
||||
delegateAddress,
|
||||
86400
|
||||
);
|
||||
|
||||
// Revoke a delegate
|
||||
registry.revokeDelegate(identity, "sigAuth", delegateAddress);
|
||||
```
|
||||
|
||||
### DID Format
|
||||
|
||||
Lux DIDs follow the format:
|
||||
|
||||
```
|
||||
did:lux:0x1234...abcd
|
||||
```
|
||||
|
||||
The DID document is constructed from on-chain events (attribute changes, delegate additions) and resolved by the `DIDResolver`.
|
||||
|
||||
## DID Resolver
|
||||
|
||||
Resolves a DID to its full DID document by reading the event log from the registry.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/identity/DIDResolver.sol";
|
||||
|
||||
DIDResolver resolver = DIDResolver(RESOLVER_ADDRESS);
|
||||
|
||||
// Check if identity is valid
|
||||
bool valid = resolver.isValidDID(identity);
|
||||
|
||||
// Get delegate validity
|
||||
bool isDelegate = registry.validDelegate(
|
||||
identity, "sigAuth", delegateAddress
|
||||
);
|
||||
```
|
||||
|
||||
## Premium DID Registry
|
||||
|
||||
Extended DID features including human-readable names, verified status, and Karma integration.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/identity/PremiumDIDRegistry.sol";
|
||||
|
||||
PremiumDIDRegistry premium = PremiumDIDRegistry(PREMIUM_ADDRESS);
|
||||
|
||||
// Register a human-readable DID name
|
||||
premium.registerName(identity, "alice.lux");
|
||||
|
||||
// Verify identity (requires attestation)
|
||||
premium.verifyIdentity(identity, proof);
|
||||
```
|
||||
|
||||
### Verified DID Benefits
|
||||
|
||||
Verified DID holders receive special treatment in the governance system:
|
||||
|
||||
| Benefit | Description |
|
||||
|---------|-------------|
|
||||
| Karma floor | Minimum 50 K (never fully decays) |
|
||||
| Governance access | Required for proposal creation |
|
||||
| Premium features | Human-readable DID names |
|
||||
|
||||
## Soulbound Identity
|
||||
|
||||
Identity tokens are soulbound (non-transferable) by default. They represent a verified on-chain identity tied to a specific address.
|
||||
|
||||
Key properties:
|
||||
- **Non-transferable**: Cannot be sent to another address
|
||||
- **Revocable**: The issuer or the holder can revoke
|
||||
- **Composable**: Other contracts can query identity status
|
||||
- **Karma-linked**: Verified DIDs get a Karma floor of 50 K
|
||||
|
||||
## Integration with Governance
|
||||
|
||||
The identity system integrates directly with the Karma reputation system:
|
||||
|
||||
```solidity
|
||||
// KarmaMinter checks DID verification status
|
||||
function rewardKarma(address recipient, bytes32 eventType, uint256 amount, bytes32 reason)
|
||||
external onlyRole(HOOK_ROLE);
|
||||
|
||||
// DID_VERIFICATION event: 100 K base, 1-year cooldown
|
||||
// HUMANITY_PROOF event: 200 K base, 1-year cooldown
|
||||
```
|
||||
|
||||
Verified DID holders enjoy a permanent Karma floor of 50 K, ensuring they always retain baseline voting power even after extended inactivity.
|
||||
|
||||
## Events
|
||||
|
||||
The registry emits events for all state changes, enabling off-chain indexing:
|
||||
|
||||
```solidity
|
||||
event DIDAttributeChanged(
|
||||
address indexed identity,
|
||||
bytes32 name,
|
||||
bytes value,
|
||||
uint256 validTo,
|
||||
uint256 previousChange
|
||||
);
|
||||
|
||||
event DIDDelegateChanged(
|
||||
address indexed identity,
|
||||
bytes32 delegateType,
|
||||
address delegate,
|
||||
uint256 validTo,
|
||||
uint256 previousChange
|
||||
);
|
||||
```
|
||||
@@ -0,0 +1,105 @@
|
||||
---
|
||||
title: Lux Standard Library
|
||||
description: Production Solidity contracts for the Lux Network - DeFi, governance, identity, privacy, and 39 precompiles
|
||||
icon: Library
|
||||
---
|
||||
|
||||
The Lux Standard Library (`@luxfi/contracts`) is the canonical Solidity contracts package for the Lux Network ecosystem. It provides production-ready contracts for DeFi protocols, governance, identity, cross-chain bridges, post-quantum cryptography, and FHE confidential computing.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @luxfi/contracts
|
||||
```
|
||||
|
||||
For Foundry projects:
|
||||
|
||||
```bash
|
||||
forge install luxfi/standard
|
||||
```
|
||||
|
||||
Add to `remappings.txt`:
|
||||
|
||||
```
|
||||
@luxfi/contracts/=lib/standard/contracts/
|
||||
```
|
||||
|
||||
## Contract Categories
|
||||
|
||||
| Category | Directory | Description |
|
||||
|----------|-----------|-------------|
|
||||
| **AMM** | `amm/` | V2 constant-product, V3 concentrated liquidity, StableSwap |
|
||||
| **Lending** | `markets/` | Morpho-style isolated lending markets |
|
||||
| **Perpetuals** | `perps/` | GMX-style leveraged perpetual futures |
|
||||
| **Liquid** | `liquid/` | Yield-bearing bridge tokens (LETH, LBTC, LUSD), xLUX vault |
|
||||
| **Governance** | `governance/` | Governor, Timelock, vLUX, Karma, DLUX, GaugeController |
|
||||
| **Identity** | `identity/` | W3C DID Registry, Soulbound NFTs, Reputation |
|
||||
| **NFT AMM** | `lssvm/` | sudoswap-style bonding curve NFT trading |
|
||||
| **Options** | `options/` | European options with ERC-1155 positions |
|
||||
| **Streaming** | `streaming/` | Sablier-style linear and cliff token vesting |
|
||||
| **Insurance** | `insurance/` | Protocol coverage with underwriter staking |
|
||||
| **Privacy** | `privacy/` | Z-Chain UTXO notes with Poseidon2 and STARK proofs |
|
||||
| **FHE** | `fhe/` | Fully Homomorphic Encryption for confidential contracts |
|
||||
| **Precompiles** | `precompile/` | 39 EVM precompiles (PQ crypto, DeFi, ZK, attestation) |
|
||||
| **Bridge** | `bridge/` | Cross-chain Warp messaging and LRC20B tokens |
|
||||
| **Tokens** | `tokens/` | LRC20, WLUX, AI, and token extensions |
|
||||
|
||||
## Quick Start
|
||||
|
||||
```solidity
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity ^0.8.24;
|
||||
|
||||
import "@luxfi/contracts/tokens/LRC20.sol";
|
||||
|
||||
contract MyToken is LRC20 {
|
||||
constructor() LRC20("My Token", "MTK") {
|
||||
_mint(msg.sender, 1_000_000e18);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
The library is organized by protocol domain. Each module is self-contained with its own interfaces, and cross-module imports use the `@luxfi/contracts/` prefix. All contracts compile with Solidity 0.8.31, EVM target Cancun, and 200 optimizer runs.
|
||||
|
||||
```
|
||||
contracts/
|
||||
amm/ # V2, V3, StableSwap factories and routers
|
||||
markets/ # Isolated lending (Morpho-style)
|
||||
perps/ # Perpetual futures vault, router, LLP
|
||||
liquid/ # LiquidLUX (xLUX), bridge tokens (LETH, LBTC...)
|
||||
governance/ # Governor, vLUX, Karma, DLUX, GaugeController
|
||||
identity/ # DIDRegistry, DIDResolver, PremiumDID
|
||||
lssvm/ # NFT AMM with linear and exponential curves
|
||||
options/ # European options (ERC-1155)
|
||||
streaming/ # Token streaming and vesting
|
||||
insurance/ # Protocol insurance pools
|
||||
privacy/ # ZNote, ZNotePQ, PrivateTeleport
|
||||
fhe/ # FHE.sol, ConfidentialERC20, Gateway
|
||||
precompile/ # Interfaces for 39 EVM precompiles
|
||||
bridge/ # Warp-based cross-chain transfers
|
||||
tokens/ # LRC20, WLUX, AI, LUX
|
||||
oracle/ # Multi-source price aggregation
|
||||
treasury/ # FeeSplitter, ValidatorVault, FeeGov
|
||||
```
|
||||
|
||||
## Build and Test
|
||||
|
||||
```bash
|
||||
# Build all contracts
|
||||
forge build
|
||||
|
||||
# Run full test suite (761 tests)
|
||||
forge test
|
||||
|
||||
# Gas reporting
|
||||
forge test --gas-report
|
||||
|
||||
# Coverage
|
||||
forge coverage
|
||||
```
|
||||
|
||||
## Links
|
||||
|
||||
- [npm](https://www.npmjs.com/package/@luxfi/contracts) -- [GitHub](https://github.com/luxfi/standard) -- [Lux Network](https://lux.network)
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
title: Lending (Markets)
|
||||
description: Morpho-style isolated lending markets with permissionless pool creation
|
||||
icon: Landmark
|
||||
---
|
||||
|
||||
The Markets module (`contracts/markets/`) implements Morpho-style isolated lending markets. Each market is a standalone pair of one collateral token and one loan token, with independent risk parameters.
|
||||
|
||||
## Architecture
|
||||
|
||||
Unlike monolithic lending pools (Aave, Compound), each market is isolated. A bad collateral asset only affects that specific market, not the entire protocol.
|
||||
|
||||
| Contract | Import | Purpose |
|
||||
|----------|--------|---------|
|
||||
| **Markets** | `@luxfi/contracts/markets/Markets.sol` | Core lending engine |
|
||||
| **Allocator** | `@luxfi/contracts/markets/Allocator.sol` | Capital allocation |
|
||||
| **Router** | `@luxfi/contracts/markets/Router.sol` | User-facing router |
|
||||
|
||||
## Market Parameters
|
||||
|
||||
Each market is defined by:
|
||||
|
||||
| Parameter | Description |
|
||||
|-----------|-------------|
|
||||
| `loanToken` | Token being borrowed |
|
||||
| `collateralToken` | Token used as collateral |
|
||||
| `oracle` | Price oracle for the pair |
|
||||
| `irm` | Interest rate model |
|
||||
| `lltv` | Liquidation loan-to-value ratio |
|
||||
|
||||
## Usage
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/markets/Markets.sol";
|
||||
|
||||
Markets markets = Markets(MARKETS_ADDRESS);
|
||||
|
||||
// Supply collateral
|
||||
markets.supplyCollateral(marketId, amount, onBehalf, data);
|
||||
|
||||
// Borrow against collateral
|
||||
markets.borrow(marketId, amount, onBehalf, receiver);
|
||||
|
||||
// Repay loan
|
||||
markets.repay(marketId, amount, onBehalf, data);
|
||||
|
||||
// Withdraw collateral
|
||||
markets.withdrawCollateral(marketId, amount, onBehalf, receiver);
|
||||
```
|
||||
|
||||
## Liquidation
|
||||
|
||||
When a position's LTV exceeds the market's `lltv`, anyone can liquidate:
|
||||
|
||||
```solidity
|
||||
// Liquidate an unhealthy position
|
||||
markets.liquidate(
|
||||
marketId,
|
||||
borrower,
|
||||
seizedAssets, // collateral to seize
|
||||
repaidShares, // debt shares to repay
|
||||
data
|
||||
);
|
||||
```
|
||||
|
||||
The liquidation incentive is determined by the market's LLTV -- higher LLTV markets offer larger liquidation bonuses to compensate for the tighter margin.
|
||||
|
||||
## Interest Rate Model
|
||||
|
||||
Interest rates adjust dynamically based on utilization:
|
||||
|
||||
| Utilization | Rate Behavior |
|
||||
|-------------|---------------|
|
||||
| Below target | Rate decreases slowly |
|
||||
| At target | Rate is stable |
|
||||
| Above target | Rate increases rapidly |
|
||||
|
||||
The target utilization is typically 90%, ensuring sufficient liquidity for withdrawals while maximizing capital efficiency.
|
||||
|
||||
## Oracle Integration
|
||||
|
||||
Markets use the unified Lux Oracle (`contracts/oracle/Oracle.sol`) which aggregates prices from Chainlink, Pyth, TWAP, and the DEX precompile. Each market specifies its oracle at creation time.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/oracle/IOracle.sol";
|
||||
|
||||
// Oracle returns price with 18 decimal precision
|
||||
(uint256 price, uint256 timestamp) = oracle.getPrice(collateralToken);
|
||||
```
|
||||
|
||||
## Key Properties
|
||||
|
||||
- **Permissionless**: Anyone can create a market with any token pair
|
||||
- **Isolated risk**: Each market has independent solvency
|
||||
- **Gas efficient**: Single contract manages all markets (no factory pattern)
|
||||
- **Flash loans**: Built-in flash loan support for arbitrage and liquidation
|
||||
@@ -0,0 +1,106 @@
|
||||
---
|
||||
title: Liquid Protocol
|
||||
description: Yield-bearing bridge tokens (LETH, LBTC, LUSD) and the xLUX master yield vault
|
||||
icon: Droplets
|
||||
---
|
||||
|
||||
The Liquid Protocol (`contracts/liquid/`) provides yield-bearing bridge tokens and the LiquidLUX (xLUX) master yield vault that receives all protocol fees across the Lux ecosystem.
|
||||
|
||||
## LiquidLUX (xLUX)
|
||||
|
||||
The master yield vault. Deposit WLUX, receive xLUX shares. All protocol fees (DEX, bridge, lending, perps, NFT) flow into this vault, increasing the value of xLUX over time.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/liquid/LiquidLUX.sol";
|
||||
|
||||
LiquidLUX vault = LiquidLUX(VAULT_ADDRESS);
|
||||
|
||||
// Deposit WLUX, receive xLUX shares
|
||||
wlux.approve(address(vault), amount);
|
||||
uint256 shares = vault.deposit(amount, msg.sender);
|
||||
|
||||
// Withdraw -- burns xLUX, returns WLUX
|
||||
uint256 assets = vault.withdraw(shares, msg.sender, msg.sender);
|
||||
```
|
||||
|
||||
### Fee Sources
|
||||
|
||||
| Source | Fee Type | Performance Fee |
|
||||
|--------|----------|-----------------|
|
||||
| DEX trading | `FEE_DEX` | 10% to treasury |
|
||||
| Bridge transfers | `FEE_BRIDGE` | 10% to treasury |
|
||||
| Lending interest | `FEE_LENDING` | 10% to treasury |
|
||||
| Perps trading | `FEE_PERPS` | 10% to treasury |
|
||||
| NFT marketplace | `FEE_NFT` | 10% to treasury |
|
||||
| Validator rewards | `FEE_VALIDATOR` | 0% (exempt) |
|
||||
|
||||
Fees are pushed by the `FeeSplitter` contract. 90% goes to the vault (increasing xLUX value), 10% to the DAO treasury. Validator rewards are exempt from the performance fee.
|
||||
|
||||
### Governance Integration
|
||||
|
||||
xLUX holders automatically have voting power through `VotingLUX`:
|
||||
|
||||
```
|
||||
vLUX = xLUX + DLUX
|
||||
```
|
||||
|
||||
xLUX uses `ERC20Votes` for checkpoint-based voting power, preventing flash loan governance attacks.
|
||||
|
||||
## Bridge Tokens
|
||||
|
||||
Yield-bearing wrapped tokens bridged from external chains. All use `LRC20B` as the base contract with MPC-controlled minting.
|
||||
|
||||
| Token | Import | Source Asset |
|
||||
|-------|--------|--------------|
|
||||
| **LETH** | `@luxfi/contracts/liquid/tokens/LETH.sol` | Ethereum ETH |
|
||||
| **LBTC** | `@luxfi/contracts/liquid/tokens/LBTC.sol` | Bitcoin BTC |
|
||||
| **LUSD** | `@luxfi/contracts/liquid/tokens/LUSD.sol` | USD stablecoins |
|
||||
| **LUSDC** | `@luxfi/contracts/liquid/tokens/LUSDC.sol` | USDC |
|
||||
| **LUSDT** | `@luxfi/contracts/liquid/tokens/LUSDT.sol` | USDT |
|
||||
| **LSOL** | `@luxfi/contracts/liquid/tokens/LSOL.sol` | Solana SOL |
|
||||
| **LBNB** | `@luxfi/contracts/liquid/tokens/LBNB.sol` | BNB |
|
||||
| **LAVAX** | `@luxfi/contracts/liquid/tokens/LAVAX.sol` | Avalanche AVAX |
|
||||
|
||||
### Token Naming Convention
|
||||
|
||||
- `L*` prefix: Bridge tokens on Lux (LETH, LBTC, LUSD)
|
||||
- `Z*` prefix: Bridge tokens on Zoo (ZETH, ZBTC, ZUSD)
|
||||
- `x*` prefix: Liquid staked tokens (xLUX)
|
||||
|
||||
## LiquidToken Base
|
||||
|
||||
All liquid tokens extend `LiquidToken`, which adds ERC-3156 flash loan support:
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/liquid/LiquidToken.sol";
|
||||
|
||||
// Flash loan any liquid token
|
||||
function executeFlashLoan(
|
||||
IERC3156FlashLender lender,
|
||||
address token,
|
||||
uint256 amount
|
||||
) external {
|
||||
lender.flashLoan(this, token, amount, "");
|
||||
}
|
||||
|
||||
// Implement the callback
|
||||
function onFlashLoan(
|
||||
address initiator,
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint256 fee,
|
||||
bytes calldata data
|
||||
) external returns (bytes32) {
|
||||
// Use the borrowed tokens
|
||||
// Repay amount + fee
|
||||
return keccak256("ERC3156FlashBorrower.onFlashLoan");
|
||||
}
|
||||
```
|
||||
|
||||
## Yield Strategies
|
||||
|
||||
**Yield Stacking**: Deposit LUX into LiquidLUX, then use xLUX as perps collateral for leveraged fee exposure.
|
||||
|
||||
**Delta-Neutral**: 50% into LLP (perps LP), 50% short ETH via perps. Net: ETH-neutral, pure fee yield.
|
||||
|
||||
**Governance + Yield**: Stake LUX into LiquidLUX, use xLUX voting power via vLUX to direct gauge weights, earn fees plus influence protocol emissions.
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["index","amm","lending","perpetuals","liquid","governance","identity","nft-amm","options","precompiles","deployment","api"]}
|
||||
@@ -0,0 +1,130 @@
|
||||
---
|
||||
title: NFT AMM (LSSVM)
|
||||
description: sudoswap-style NFT automated market maker with bonding curves
|
||||
icon: Image
|
||||
---
|
||||
|
||||
The LSSVM module (`contracts/lssvm/`) implements a sudoswap-style NFT AMM. Instead of traditional NFT listings, sellers deposit NFTs into bonding curve pools where pricing adjusts automatically with each trade.
|
||||
|
||||
## Contracts
|
||||
|
||||
| Contract | Import | Purpose |
|
||||
|----------|--------|---------|
|
||||
| **LSSVMPairFactory** | `@luxfi/contracts/lssvm/LSSVMPairFactory.sol` | Deploys new pair pools |
|
||||
| **LSSVMPair** | `@luxfi/contracts/lssvm/LSSVMPair.sol` | NFT/token trading pair |
|
||||
| **LSSVMRouter** | `@luxfi/contracts/lssvm/LSSVMRouter.sol` | Multi-pool swap routing |
|
||||
| **LinearCurve** | `@luxfi/contracts/lssvm/LinearCurve.sol` | Linear bonding curve |
|
||||
| **ExponentialCurve** | `@luxfi/contracts/lssvm/ExponentialCurve.sol` | Exponential bonding curve |
|
||||
|
||||
## Pool Types
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| **Token pool** | Sells tokens, buys NFTs (bid-side liquidity) |
|
||||
| **NFT pool** | Sells NFTs, buys tokens (ask-side liquidity) |
|
||||
| **Trade pool** | Both buys and sells (spread-based market making) |
|
||||
|
||||
## Bonding Curves
|
||||
|
||||
### Linear Curve
|
||||
|
||||
Price changes by a fixed `delta` with each trade:
|
||||
|
||||
```
|
||||
Buy: price = spotPrice + delta
|
||||
Sell: price = spotPrice - delta
|
||||
```
|
||||
|
||||
### Exponential Curve
|
||||
|
||||
Price changes by a percentage `delta` with each trade:
|
||||
|
||||
```
|
||||
Buy: price = spotPrice * (1 + delta)
|
||||
Sell: price = spotPrice / (1 + delta)
|
||||
```
|
||||
|
||||
## Creating a Pool
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/lssvm/LSSVMPairFactory.sol";
|
||||
|
||||
LSSVMPairFactory factory = LSSVMPairFactory(FACTORY_ADDRESS);
|
||||
|
||||
// Create a trade pool with linear curve
|
||||
LSSVMPair pair = factory.createPairETH(
|
||||
nftCollection, // ERC721 address
|
||||
linearCurve, // bonding curve contract
|
||||
LSSVMPair.PoolType.TRADE,
|
||||
1e17, // delta: 0.1 ETH per trade
|
||||
0, // fee: 0%
|
||||
1e18, // spotPrice: 1 ETH
|
||||
nftIds // initial NFT IDs to deposit
|
||||
);
|
||||
```
|
||||
|
||||
## Trading
|
||||
|
||||
### Buying NFTs
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/lssvm/LSSVMRouter.sol";
|
||||
|
||||
LSSVMRouter router = LSSVMRouter(ROUTER_ADDRESS);
|
||||
|
||||
// Buy specific NFTs from a pool
|
||||
LSSVMRouter.PairSwapSpecific[] memory swaps = new LSSVMRouter.PairSwapSpecific[](1);
|
||||
swaps[0] = LSSVMRouter.PairSwapSpecific(pair, nftIds);
|
||||
|
||||
uint256 totalCost = router.swapETHForSpecificNFTs{value: maxCost}(
|
||||
swaps,
|
||||
payable(msg.sender), // NFT recipient
|
||||
msg.sender, // refund address
|
||||
block.timestamp // deadline
|
||||
);
|
||||
```
|
||||
|
||||
### Selling NFTs
|
||||
|
||||
```solidity
|
||||
// Sell NFTs into a pool for ETH
|
||||
LSSVMRouter.PairSwapSpecific[] memory swaps = new LSSVMRouter.PairSwapSpecific[](1);
|
||||
swaps[0] = LSSVMRouter.PairSwapSpecific(pair, nftIds);
|
||||
|
||||
uint256 totalReceived = router.swapNFTsForToken(
|
||||
swaps,
|
||||
minOutput,
|
||||
payable(msg.sender), // token recipient
|
||||
block.timestamp // deadline
|
||||
);
|
||||
```
|
||||
|
||||
## Custom Curves
|
||||
|
||||
Implement the `ICurve` interface to create custom pricing logic:
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/lssvm/ICurve.sol";
|
||||
|
||||
contract SigmoidCurve is ICurve {
|
||||
function getBuyInfo(
|
||||
uint128 spotPrice,
|
||||
uint128 delta,
|
||||
uint256 numItems,
|
||||
uint256 feeMultiplier,
|
||||
uint256 protocolFeeMultiplier
|
||||
) external pure returns (
|
||||
CurveErrorCodes.Error error,
|
||||
uint128 newSpotPrice,
|
||||
uint128 newDelta,
|
||||
uint256 inputValue,
|
||||
uint256 protocolFee
|
||||
) {
|
||||
// Custom pricing logic
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Fee Structure
|
||||
|
||||
Pool creators set a spread fee (in basis points) that applies to each trade. The protocol also takes a small fee on each swap, directed to the DAO treasury via the `FeeSplitter`.
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: Options
|
||||
description: European-style options protocol with ERC-1155 fungible positions
|
||||
icon: CircleDollarSign
|
||||
---
|
||||
|
||||
The Options module (`contracts/options/Options.sol`) implements European-style options with ERC-1155 fungible position tokens. Writers deposit collateral to create option series, and holders can exercise at expiry.
|
||||
|
||||
## Option Types
|
||||
|
||||
| Type | Payoff at Expiry |
|
||||
|------|-----------------|
|
||||
| **Call** | max(0, spot - strike) |
|
||||
| **Put** | max(0, strike - spot) |
|
||||
|
||||
## Settlement Types
|
||||
|
||||
| Type | Description |
|
||||
|------|-------------|
|
||||
| **Cash** | Difference paid in quote token |
|
||||
| **Physical** | Actual asset delivery at strike price |
|
||||
|
||||
## Creating an Option Series
|
||||
|
||||
Each series is defined by underlying asset, strike price, expiry, and type. All options with the same parameters are fungible via ERC-1155.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/options/Options.sol";
|
||||
|
||||
Options options = Options(OPTIONS_ADDRESS);
|
||||
|
||||
// Create a WETH call option series
|
||||
bytes32 seriesId = options.createSeries(
|
||||
WETH, // underlying
|
||||
LUSD, // quote token
|
||||
3000e18, // strike: $3,000
|
||||
block.timestamp + 30 days, // expiry
|
||||
Options.OptionType.CALL,
|
||||
Options.SettlementType.CASH
|
||||
);
|
||||
```
|
||||
|
||||
## Writing Options
|
||||
|
||||
Writers deposit collateral and receive writer position tokens (ERC-1155). The collateral is locked until expiry.
|
||||
|
||||
```solidity
|
||||
// Write 10 call options (requires collateral deposit)
|
||||
uint256 positionId = options.write(seriesId, 10e18);
|
||||
|
||||
// Check collateral requirement
|
||||
uint256 required = options.getCollateralRequired(seriesId, 10e18);
|
||||
```
|
||||
|
||||
### Collateral Requirements
|
||||
|
||||
| Option Type | Collateral |
|
||||
|-------------|------------|
|
||||
| Call | Underlying token (e.g., WETH) |
|
||||
| Put | Quote token (e.g., LUSD at strike price) |
|
||||
|
||||
## Exercising Options
|
||||
|
||||
Holders exercise at or after expiry. Only in-the-money options produce a payout.
|
||||
|
||||
```solidity
|
||||
// Exercise 5 call options at expiry
|
||||
uint256 payout = options.exercise(seriesId, 5e18);
|
||||
|
||||
// Preview payout before exercising
|
||||
uint256 expectedPayout = options.getExercisePayout(seriesId, 5e18);
|
||||
```
|
||||
|
||||
### Payout Calculation
|
||||
|
||||
For a cash-settled call with strike $3,000 and spot $3,500:
|
||||
|
||||
```
|
||||
payout = (spot - strike) * amount = ($3,500 - $3,000) * 5 = $2,500
|
||||
```
|
||||
|
||||
## Settling (Writer Collateral Return)
|
||||
|
||||
After expiry, writers reclaim unused collateral. If options expired out-of-the-money, writers receive their full collateral back.
|
||||
|
||||
```solidity
|
||||
// Settle writer position, reclaim remaining collateral
|
||||
uint256 collateralReturned = options.settle(seriesId);
|
||||
```
|
||||
|
||||
## ERC-1155 Position Tokens
|
||||
|
||||
Position IDs are deterministic:
|
||||
|
||||
```solidity
|
||||
// Holder and writer positions have separate token IDs
|
||||
uint256 holderPositionId = uint256(keccak256(abi.encodePacked(seriesId, false)));
|
||||
uint256 writerPositionId = uint256(keccak256(abi.encodePacked(seriesId, true)));
|
||||
```
|
||||
|
||||
Because positions are ERC-1155, they are:
|
||||
- **Fungible** within the same series and side (writer/holder)
|
||||
- **Transferable** on any NFT marketplace
|
||||
- **Composable** with other DeFi protocols
|
||||
|
||||
## Oracle Integration
|
||||
|
||||
Options use the unified Lux Oracle for settlement price determination. At expiry, the oracle's spot price determines whether options are in-the-money.
|
||||
|
||||
```solidity
|
||||
// Oracle provides the settlement price
|
||||
(uint256 price, ) = oracle.getPrice(underlying);
|
||||
```
|
||||
|
||||
## Key Properties
|
||||
|
||||
- **European-style**: Exercise only at expiry, not before
|
||||
- **Fully collateralized**: No margin calls or liquidation risk for holders
|
||||
- **Permissionless series creation**: Anyone can create new option series
|
||||
- **Gas efficient**: Single contract manages all series via ERC-1155
|
||||
@@ -0,0 +1,115 @@
|
||||
---
|
||||
title: Perpetuals
|
||||
description: GMX-style leveraged perpetual futures with LLP liquidity pool
|
||||
icon: TrendingUp
|
||||
---
|
||||
|
||||
The Perps module (`contracts/perps/`) implements leveraged perpetual futures trading. Traders can open long or short positions with up to 50x leverage, while liquidity providers earn 70% of trading fees through the LLP token.
|
||||
|
||||
## Core Contracts
|
||||
|
||||
| Contract | Import | Purpose |
|
||||
|----------|--------|---------|
|
||||
| **Vault** | `@luxfi/contracts/perps/core/Vault.sol` | Central liquidity pool and position management |
|
||||
| **Router** | `@luxfi/contracts/perps/core/Router.sol` | User-facing position operations |
|
||||
| **PositionRouter** | `@luxfi/contracts/perps/core/PositionRouter.sol` | Keeper-executed position changes |
|
||||
| **LlpManager** | `@luxfi/contracts/perps/core/LlpManager.sol` | LLP token minting and burning |
|
||||
| **LLP** | `@luxfi/contracts/perps/gmx/LLP.sol` | Multi-asset LP token |
|
||||
| **LPUSD** | `@luxfi/contracts/perps/tokens/LPUSD.sol` | Internal accounting stablecoin |
|
||||
|
||||
## Token Naming
|
||||
|
||||
| Token | Description |
|
||||
|-------|-------------|
|
||||
| **LPX** | Lux Perps governance/utility token |
|
||||
| **LLP** | Lux Liquidity Provider (vault share token) |
|
||||
| **LPUSD** | Lux Perps USD (internal accounting) |
|
||||
| **xLPX** | Escrowed LPX (vesting rewards) |
|
||||
|
||||
## Opening Positions
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/perps/core/Router.sol";
|
||||
|
||||
Router router = Router(ROUTER_ADDRESS);
|
||||
|
||||
// Open leveraged long position
|
||||
router.increasePosition(
|
||||
collateralToken, // e.g., WETH
|
||||
indexToken, // asset to go long on
|
||||
collateralAmount, // collateral deposited
|
||||
sizeDelta, // position size in USD
|
||||
true // isLong
|
||||
);
|
||||
|
||||
// Open short position
|
||||
router.increasePosition(
|
||||
LUSD, // stablecoin collateral for shorts
|
||||
indexToken, // asset to short
|
||||
collateralAmount,
|
||||
sizeDelta,
|
||||
false // isShort
|
||||
);
|
||||
```
|
||||
|
||||
## Providing Liquidity
|
||||
|
||||
LPs deposit whitelisted tokens and receive LLP. They earn 70% of trading fees and act as counterparty to all traders.
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/perps/core/LlpManager.sol";
|
||||
|
||||
LlpManager manager = LlpManager(MANAGER_ADDRESS);
|
||||
|
||||
// Deposit WETH, receive LLP tokens
|
||||
token.approve(address(manager), amount);
|
||||
uint256 llpAmount = manager.addLiquidity(WETH, amount, minUsdg, minLlp);
|
||||
|
||||
// Withdraw -- burn LLP, receive token
|
||||
uint256 received = manager.removeLiquidity(WETH, llpAmount, minOut, recipient);
|
||||
```
|
||||
|
||||
## Fee Structure
|
||||
|
||||
| Fee Type | Amount |
|
||||
|----------|--------|
|
||||
| Swap | 0.3% (stables: 0.04%) |
|
||||
| Margin | 0.1% of position size |
|
||||
| Funding | Variable, 8-hour intervals |
|
||||
| Liquidation | $100 USD equivalent |
|
||||
|
||||
## Liquidation
|
||||
|
||||
Positions are liquidated when losses consume the collateral minus the liquidation fee. The liquidation price depends on entry price, leverage, and accumulated fees.
|
||||
|
||||
## Staking Rewards
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/perps/staking/RewardRouterV2.sol";
|
||||
|
||||
RewardRouterV2 rewardRouter = RewardRouterV2(REWARD_ROUTER);
|
||||
|
||||
// Stake LPX to earn WETH + xLPX
|
||||
rewardRouter.stakeLpx(amount);
|
||||
|
||||
// Claim all rewards
|
||||
rewardRouter.handleRewards(
|
||||
true, // shouldClaimLpx
|
||||
true, // shouldStakeLpx
|
||||
true, // shouldClaimXLpx
|
||||
true, // shouldStakeXLpx
|
||||
true, // shouldStakeMultiplierPoints
|
||||
true, // shouldClaimWeth
|
||||
false // shouldConvertWethToEth
|
||||
);
|
||||
```
|
||||
|
||||
## Oracle
|
||||
|
||||
The Vault uses `VaultPriceFeed` which aggregates Chainlink, Pyth, and `FastPriceFeed` for low-latency updates. Spread pricing protects against MEV.
|
||||
|
||||
```solidity
|
||||
// Get price for perps (with spread)
|
||||
uint256 longPrice = oracle.getPriceForPerps(WETH, true); // maximize for longs
|
||||
uint256 shortPrice = oracle.getPriceForPerps(WETH, false); // minimize for shorts
|
||||
```
|
||||
@@ -0,0 +1,120 @@
|
||||
---
|
||||
title: Precompiles
|
||||
description: 39 EVM precompiles for post-quantum cryptography, DeFi, ZK proofs, and attestation
|
||||
icon: Cpu
|
||||
---
|
||||
|
||||
Lux EVM includes 39 custom precompiles accessible as native Solidity calls. Interfaces are in `contracts/precompile/interfaces/` and addresses in `contracts/precompile/addresses/PrecompileRegistry.sol`.
|
||||
|
||||
## Core Precompiles
|
||||
|
||||
| Address | Name | Interface | Purpose |
|
||||
|---------|------|-----------|---------|
|
||||
| `0x0200...0001` | DeployerAllowList | -- | Deployer permissions |
|
||||
| `0x0200...0002` | TxAllowList | -- | Transaction permissions |
|
||||
| `0x0200...0003` | FeeManager | -- | Dynamic fee management |
|
||||
| `0x0200...0004` | NativeMinter | -- | Native token minting |
|
||||
| `0x0200...0005` | Warp | `IWarp.sol` | Cross-chain messaging with BLS |
|
||||
| `0x0200...0006` | RewardManager | -- | Validator rewards |
|
||||
|
||||
## Cryptography Precompiles
|
||||
|
||||
| Address | Name | Interface | Purpose |
|
||||
|---------|------|-----------|---------|
|
||||
| `0x0200...0007` | ML-DSA | `IMLDSA.sol` | FIPS 204 post-quantum signatures |
|
||||
| `0x0200...0008` | SLH-DSA | `ISLHDSA.sol` | Hash-based PQ signatures (SPHINCS+) |
|
||||
| `0x0200...0009` | PQCrypto | `IPQCrypto.sol` | Multi-PQ operations |
|
||||
| `0x0200...000A` | Quasar | `IQuasar.sol` | Quantum consensus operations |
|
||||
| `0x0200...000B` | Corona | `ICoronaThreshold.sol` | Post-quantum threshold signatures |
|
||||
| `0x0200...000C` | FROST | `IFROST.sol` | Schnorr threshold (BIP-340 Taproot) |
|
||||
| `0x0200...000D` | CGGMP21 | `ICGGMP21.sol` | ECDSA threshold (MPC custody) |
|
||||
|
||||
### Usage: Post-Quantum Signatures
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/precompile/interfaces/IMLDSA.sol";
|
||||
|
||||
// Verify a post-quantum ML-DSA signature
|
||||
bool valid = IMLDSA.verify(publicKey, message, signature);
|
||||
```
|
||||
|
||||
### Usage: Threshold Signatures
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/precompile/interfaces/IFROST.sol";
|
||||
|
||||
// Verify 2-of-3 FROST threshold signature
|
||||
FROSTLib.verifyOrRevert(2, 3, aggregatedPubKey, messageHash, signature);
|
||||
```
|
||||
|
||||
## DeFi Precompiles
|
||||
|
||||
| Address | Name | Interface | Purpose |
|
||||
|---------|------|-----------|---------|
|
||||
| `0x0200...0010` | DEX | `ILXBook.sol` | QuantumSwap on-chain CLOB |
|
||||
| `0x0200...0011` | Oracle | `IOracle.sol` | Multi-source price aggregation |
|
||||
| `0x0200...0012` | Lending | -- | Lending operations |
|
||||
| `0x0200...0013` | Staking | -- | Staking operations |
|
||||
| `0x0200...0014` | Yield | -- | Yield operations |
|
||||
| `0x0200...0015` | Perps | -- | Perpetuals operations |
|
||||
|
||||
## Attestation Precompile
|
||||
|
||||
| Address | Name | Purpose |
|
||||
|---------|------|---------|
|
||||
| `0x0200...0300` | Attestation | GPU/TEE hardware attestation for AI mining |
|
||||
|
||||
## Hashing Precompiles
|
||||
|
||||
| Address | Name | Interface | Gas | Purpose |
|
||||
|---------|------|-----------|-----|---------|
|
||||
| `0x0501` | Poseidon2 | `IHash.sol` | ~20K | ZK-friendly hash |
|
||||
| `0x0502` | Poseidon2Sponge | `IHash.sol` | ~25K | Variable-length Poseidon2 |
|
||||
| `0x0503` | Pedersen | `IHash.sol` | ~30K | BN254 curve commitment |
|
||||
| `0x0504` | Blake3 | `IHash.sol` | ~5K | High-performance hash |
|
||||
|
||||
```solidity
|
||||
import "@luxfi/contracts/precompile/interfaces/IHash.sol";
|
||||
|
||||
// Poseidon2 hash (ZK-friendly, post-quantum safe)
|
||||
bytes32 hash = IHash(0x0501).hash(abi.encode(left, right));
|
||||
```
|
||||
|
||||
## ZK Proof Precompiles
|
||||
|
||||
| Address | Name | Interface | Purpose |
|
||||
|---------|------|-----------|---------|
|
||||
| `0x0900` | ZKVerify | `IZK.sol` | Generic ZK verification |
|
||||
| `0x0901` | Groth16 | `IZK.sol` | Groth16 proof verification |
|
||||
| `0x0902` | PLONK | `IZK.sol` | PLONK proof verification |
|
||||
| `0x0903` | fflonk | `IZK.sol` | fflonk proof verification |
|
||||
| `0x0904` | Halo2 | `IZK.sol` | Halo2 proof verification |
|
||||
| `0x0910` | KZG | `IZK.sol` | KZG polynomial commitments |
|
||||
| `0x0912` | IPA | `IZK.sol` | Inner Product Arguments |
|
||||
| `0x0920` | PrivacyPool | `IZK.sol` | Confidential pool operations |
|
||||
| `0x0921` | Nullifier | `IZK.sol` | Nullifier verification |
|
||||
| `0x0922` | Commitment | `IZK.sol` | Commitment verification |
|
||||
| `0x0923` | RangeProof | `IZK.sol` | Bulletproof range proofs |
|
||||
| `0x0930` | RollupVerify | `IZK.sol` | ZK rollup batch verification |
|
||||
| `0x0931` | StateRoot | `IZK.sol` | State root verification |
|
||||
| `0x0932` | BatchProof | `IZK.sol` | Batch proof aggregation |
|
||||
|
||||
## Dead/Burn Precompiles
|
||||
|
||||
| Address | Name | Interface | Purpose |
|
||||
|---------|------|-----------|---------|
|
||||
| `0x0000...0000` | DeadZero | `IDead.sol` | Zero address intercept |
|
||||
| `0x0000...dEaD` | DeadShort | `IDead.sol` | Common dead address |
|
||||
| `0xdEaD...0000` | DeadFull | `IDead.sol` | Full dead prefix |
|
||||
|
||||
Tokens sent to dead addresses are split: 50% burned (deflationary) and 50% sent to the DAO treasury as Protocol-Owned Liquidity.
|
||||
|
||||
## Gas Costs
|
||||
|
||||
| Precompile | Gas (3-of-5) | Signature Size |
|
||||
|------------|-------------|----------------|
|
||||
| FROST | 75,000 | 64 bytes |
|
||||
| CGGMP21 | 125,000 | 65 bytes |
|
||||
| Corona | 200,000 | ~4 KB |
|
||||
| ML-DSA | 100,000 | 3,309 bytes |
|
||||
| BLS (Warp) | 120,000 | 96 bytes |
|
||||
@@ -0,0 +1,119 @@
|
||||
---
|
||||
title: Contract Interfaces
|
||||
description: Solidity interfaces for Bridge.sol, ERC20B.sol, and IBridgeToken
|
||||
icon: Code
|
||||
---
|
||||
|
||||
## Bridge.sol
|
||||
|
||||
The main bridge contract uses EIP-712 typed data signing with role-based access control.
|
||||
|
||||
### EIP-712 Domain
|
||||
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Name | `TeleportBridge` |
|
||||
| Version | `1` |
|
||||
|
||||
### Roles
|
||||
|
||||
| Role | Permissions |
|
||||
|------|------------|
|
||||
| `ADMIN_ROLE` | Token whitelist, oracle management, fee config, emergency withdraw |
|
||||
| `ORACLE_ROLE` | Granted to MPC signer addresses |
|
||||
| `PAUSER_ROLE` | Pause and unpause bridge operations |
|
||||
|
||||
### Functions
|
||||
|
||||
```solidity
|
||||
// Burn tokens with committed destination data
|
||||
function bridgeBurn(
|
||||
address token,
|
||||
uint256 amount,
|
||||
uint256 toChainId,
|
||||
address recipient,
|
||||
bool vault
|
||||
) external returns (bytes32 burnId);
|
||||
|
||||
// Mint tokens with EIP-712 oracle signature
|
||||
function bridgeMint(
|
||||
ClaimData calldata claim,
|
||||
bytes calldata signature
|
||||
) external returns (bytes32 claimId);
|
||||
|
||||
// Admin: manage token whitelist
|
||||
function setAllowedToken(address token, bool allowed) external;
|
||||
|
||||
// Admin: manage oracle addresses
|
||||
function setOracle(address oracle, bool active) external;
|
||||
|
||||
// Admin: configure fee rate (max 10%)
|
||||
function setFeeRate(uint256 rate) external;
|
||||
```
|
||||
|
||||
## ERC20B.sol
|
||||
|
||||
Bridgeable ERC-20 token with restricted mint and burn.
|
||||
|
||||
```solidity
|
||||
// Only BRIDGE_ROLE can call
|
||||
function bridgeMint(address to, uint256 amount) external;
|
||||
function bridgeBurn(address from, uint256 amount) external;
|
||||
```
|
||||
|
||||
### Roles
|
||||
|
||||
| Role | Permissions |
|
||||
|------|------------|
|
||||
| `DEFAULT_ADMIN_ROLE` | Grant and revoke roles |
|
||||
| `BRIDGE_ROLE` | Mint and burn tokens |
|
||||
| `PAUSER_ROLE` | Pause all token transfers |
|
||||
|
||||
## IBridgeToken Interface
|
||||
|
||||
```solidity
|
||||
interface IBridgeToken {
|
||||
function bridgeMint(address to, uint256 amount) external;
|
||||
function bridgeBurn(address from, uint256 amount) external;
|
||||
}
|
||||
```
|
||||
|
||||
## ClaimData Struct
|
||||
|
||||
```solidity
|
||||
struct ClaimData {
|
||||
bytes32 burnId;
|
||||
address token;
|
||||
uint256 amount;
|
||||
uint256 fromChainId;
|
||||
uint256 toChainId;
|
||||
address recipient;
|
||||
bool vault;
|
||||
uint256 nonce;
|
||||
uint256 deadline;
|
||||
}
|
||||
```
|
||||
|
||||
## API Service Types
|
||||
|
||||
```typescript
|
||||
interface SignatureRequest {
|
||||
burnTxHash: string; // 0x-prefixed 32-byte hex
|
||||
fromChainId: number;
|
||||
logIndex: number;
|
||||
}
|
||||
|
||||
interface SignatureResponse {
|
||||
claimId: string;
|
||||
burnTxHash: string;
|
||||
logIndex: number;
|
||||
token: string;
|
||||
amount: string;
|
||||
toChainId: number;
|
||||
recipient: string;
|
||||
vault: boolean;
|
||||
nonce: number;
|
||||
deadline: number;
|
||||
signature: string;
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,55 @@
|
||||
---
|
||||
title: Lux Teleport
|
||||
description: Cross-chain token transfer protocol using burn-mint with MPC oracles
|
||||
icon: Zap
|
||||
---
|
||||
|
||||
Lux Teleport (`github.com/luxfi/teleport`) enables cross-chain token transfers between Lux subnets and external chains. Tokens are burned on the source chain and minted on the destination chain, with MPC oracle nodes providing signature verification.
|
||||
|
||||
## How It Works
|
||||
|
||||
```
|
||||
Source Chain MPC Oracles Destination Chain
|
||||
┌────────────┐ ┌─────────┐ ┌────────────┐
|
||||
│ bridgeBurn │──BridgeBurned│ Watch │──EIP-712 sig │ bridgeMint │
|
||||
│ (lock/burn)│ event │ + sign │ │ (mint) │
|
||||
└────────────┘ └─────────┘ └────────────┘
|
||||
```
|
||||
|
||||
1. User calls `bridgeBurn()` on the source chain Bridge contract, specifying token, amount, destination chain, and recipient
|
||||
2. The contract emits a `BridgeBurned` event with all transfer parameters committed on-chain
|
||||
3. MPC oracle nodes detect the event and derive claim data from on-chain logs (never from request parameters)
|
||||
4. Oracles produce an EIP-712 typed data signature over the claim
|
||||
5. User submits the signature to `bridgeMint()` on the destination chain
|
||||
6. The destination contract verifies the oracle signature and mints tokens to the recipient
|
||||
|
||||
## Security Architecture
|
||||
|
||||
| Protection | Mechanism |
|
||||
|-----------|-----------|
|
||||
| Signature format | EIP-712 typed data (prevents malleability) |
|
||||
| Replay prevention | ClaimId-based tracking via `keccak256(abi.encode(...))` |
|
||||
| Token safety | Admin-managed whitelist of allowed tokens |
|
||||
| Access control | Separate ADMIN, ORACLE, and PAUSER roles |
|
||||
| Emergency | Pausable on both burn and mint paths |
|
||||
| Reentrancy | ReentrancyGuard on all external functions |
|
||||
| Fee caps | Maximum 10% fee rate enforced on-chain |
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
teleport/
|
||||
├── contracts/ # Bridge.sol, ERC20B.sol, IBridgeToken.sol
|
||||
├── api/ # Bridge API service (TypeScript)
|
||||
├── mpc/ # MPC signing service (TypeScript)
|
||||
├── app/ # Frontend UI
|
||||
└── multi-party-ecdsa/ # MPC library
|
||||
```
|
||||
|
||||
## Supported Assets
|
||||
|
||||
Only admin-whitelisted tokens can be bridged. Each bridgeable token implements `ERC20B` with a `BRIDGE_ROLE` that restricts minting and burning to the Bridge contract.
|
||||
|
||||
## Trust Model
|
||||
|
||||
The current implementation (v1.1.0) uses 2-of-3 MPC threshold signatures. The trust assumption is that a majority of MPC oracle nodes are honest. Future versions will move to trustless light client verification with ZK proofs.
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Overview---","index","---Usage---","usage","---API Reference---","api"]}
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
title: Token Transfers
|
||||
description: Transfer tokens between Lux subnets using Teleport
|
||||
icon: ArrowLeftRight
|
||||
---
|
||||
|
||||
## Burning Tokens (Source Chain)
|
||||
|
||||
Call `bridgeBurn()` on the Bridge contract deployed on the source chain. All destination parameters are committed into the on-chain event.
|
||||
|
||||
```solidity
|
||||
function bridgeBurn(
|
||||
address token, // Whitelisted ERC20B token
|
||||
uint256 amount, // Amount to transfer
|
||||
uint256 toChainId, // Destination chain ID
|
||||
address recipient, // Recipient on destination chain
|
||||
bool vault // Whether to deposit into vault
|
||||
) external returns (bytes32 burnId);
|
||||
```
|
||||
|
||||
The contract emits a `BridgeBurned` event:
|
||||
|
||||
```solidity
|
||||
event BridgeBurned(
|
||||
bytes32 indexed burnId,
|
||||
address indexed token,
|
||||
address indexed sender,
|
||||
uint256 amount,
|
||||
uint256 toChainId,
|
||||
address recipient,
|
||||
bool vault,
|
||||
uint256 nonce
|
||||
);
|
||||
```
|
||||
|
||||
## Requesting a Signature
|
||||
|
||||
Submit the burn transaction hash to the API service. The service parses the on-chain event and returns an EIP-712 signature from the MPC oracle.
|
||||
|
||||
```typescript
|
||||
// POST /api/signature
|
||||
const response = await fetch('/api/signature', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
burnTxHash: '0x...', // 32-byte hex
|
||||
fromChainId: 96369,
|
||||
logIndex: 0,
|
||||
}),
|
||||
});
|
||||
|
||||
const { claimId, signature, ...claimData } = await response.json();
|
||||
```
|
||||
|
||||
## Minting Tokens (Destination Chain)
|
||||
|
||||
Submit the claim data and oracle signature to `bridgeMint()` on the destination chain.
|
||||
|
||||
```solidity
|
||||
function bridgeMint(
|
||||
ClaimData calldata claim,
|
||||
bytes calldata signature
|
||||
) external returns (bytes32 claimId);
|
||||
```
|
||||
|
||||
The contract verifies the EIP-712 signature against an authorized oracle address, checks replay protection via the claim ID, and mints tokens to the recipient.
|
||||
|
||||
## API Endpoints
|
||||
|
||||
| Endpoint | Method | Description |
|
||||
|----------|--------|-------------|
|
||||
| `/api/signature` | POST | Request claim signature for a burn tx |
|
||||
| `/api/claim/:claimId` | GET | Check claim status |
|
||||
| `/health` | GET | Service health check |
|
||||
|
||||
## Rate Limits
|
||||
|
||||
The API enforces 100 requests per 15 minutes per IP address. All sensitive operations use POST to keep parameters out of URLs and server logs.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
# Build and test contracts
|
||||
cd contracts && pnpm install && pnpm test
|
||||
|
||||
# Run API service
|
||||
cd api && pnpm install && pnpm build && pnpm start
|
||||
|
||||
# Run MPC service
|
||||
cd mpc && pnpm install && pnpm build && pnpm start
|
||||
```
|
||||
@@ -0,0 +1,114 @@
|
||||
---
|
||||
title: Threshold API Reference
|
||||
description: RegisterScheme, GetScheme, SchemeAdapter, and QuickSign helpers
|
||||
icon: Code
|
||||
---
|
||||
|
||||
## Registry Functions
|
||||
|
||||
### RegisterScheme
|
||||
|
||||
```go
|
||||
func RegisterScheme(scheme Scheme)
|
||||
```
|
||||
|
||||
Registers a threshold scheme. Call from `init()` in scheme packages. Panics if the scheme ID is already registered.
|
||||
|
||||
### GetScheme
|
||||
|
||||
```go
|
||||
func GetScheme(id SchemeID) (Scheme, error)
|
||||
```
|
||||
|
||||
Returns a registered scheme by ID. Returns `ErrSchemeNotFound` if not registered.
|
||||
|
||||
### MustGetScheme
|
||||
|
||||
```go
|
||||
func MustGetScheme(id SchemeID) Scheme
|
||||
```
|
||||
|
||||
Like `GetScheme` but panics on error. Use in initialization code where missing schemes are fatal.
|
||||
|
||||
### ListSchemes
|
||||
|
||||
```go
|
||||
func ListSchemes() []SchemeID
|
||||
```
|
||||
|
||||
Returns all registered scheme IDs.
|
||||
|
||||
### HasScheme
|
||||
|
||||
```go
|
||||
func HasScheme(id SchemeID) bool
|
||||
```
|
||||
|
||||
Returns true if the scheme is registered.
|
||||
|
||||
## SchemeAdapter
|
||||
|
||||
Convenience wrapper that creates a Signer, Aggregator, and Verifier from a single `KeyShare`.
|
||||
|
||||
```go
|
||||
adapter, err := threshold.NewAdapter(keyShare)
|
||||
|
||||
// Sign
|
||||
share, err := adapter.SignShare(ctx, message, signerIndices)
|
||||
|
||||
// Aggregate
|
||||
sig, err := adapter.Aggregate(ctx, message, shares)
|
||||
|
||||
// Verify
|
||||
valid := adapter.Verify(message, sig)
|
||||
|
||||
// Metadata
|
||||
adapter.Index() // Party index
|
||||
adapter.Threshold() // Signing threshold
|
||||
adapter.SchemeID() // Scheme identifier
|
||||
adapter.GroupKey() // Group public key
|
||||
```
|
||||
|
||||
## QuickSign
|
||||
|
||||
One-shot helper for when all signers are local (testing, single-machine setups).
|
||||
|
||||
```go
|
||||
qs, err := threshold.NewQuickSign(schemeID, groupKey, t)
|
||||
|
||||
// Sign with local signers and aggregate in one call
|
||||
sig, err := qs.SignAndAggregate(ctx, message, signers)
|
||||
|
||||
// Verify
|
||||
valid := qs.Verify(message, sig)
|
||||
```
|
||||
|
||||
`SignAndAggregate` returns `ErrInsufficientShares` if fewer than `t+1` signers are provided.
|
||||
|
||||
## SchemeInfo
|
||||
|
||||
```go
|
||||
info, err := threshold.GetSchemeInfo(schemeID)
|
||||
```
|
||||
|
||||
Returns metadata about a registered scheme:
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `ID` | `SchemeID` | Scheme identifier |
|
||||
| `Name` | `string` | Human-readable name |
|
||||
| `PostQuantum` | `bool` | Whether scheme is quantum-resistant |
|
||||
| `NonInteractive` | `bool` | Whether aggregation needs no extra rounds |
|
||||
| `KeyShareSize` | `int` | Serialized key share size in bytes |
|
||||
| `SignatureSize` | `int` | Final signature size in bytes |
|
||||
|
||||
## Errors
|
||||
|
||||
| Error | Description |
|
||||
|-------|-------------|
|
||||
| `ErrSchemeNotFound` | Scheme ID not in registry |
|
||||
| `ErrInvalidThreshold` | Threshold less than 1 |
|
||||
| `ErrInvalidPartyCount` | Fewer than 2 parties |
|
||||
| `ErrThresholdTooHigh` | Threshold >= total parties |
|
||||
| `ErrInvalidPartyIndex` | Party index out of range |
|
||||
| `ErrInsufficientShares` | Not enough shares to aggregate |
|
||||
@@ -0,0 +1,70 @@
|
||||
---
|
||||
title: Threshold Crypto
|
||||
description: Unified interfaces and registry for threshold signature schemes
|
||||
icon: Users
|
||||
---
|
||||
|
||||
Lux Threshold (`github.com/luxfi/crypto/threshold`) defines the canonical interface layer for threshold cryptography across the Lux ecosystem. It provides a unified API for key generation, signing, aggregation, and verification that works with multiple underlying schemes.
|
||||
|
||||
## Core Interfaces
|
||||
|
||||
| Interface | Purpose |
|
||||
|-----------|---------|
|
||||
| `Scheme` | Factory for creating DKG, Signer, Aggregator, and Verifier instances |
|
||||
| `DKG` | Multi-round distributed key generation protocol |
|
||||
| `TrustedDealer` | Centralized key share generation (simpler, requires trust) |
|
||||
| `KeyShare` | A party's share of the threshold secret key |
|
||||
| `Signer` | Creates signature shares from a key share |
|
||||
| `Aggregator` | Combines signature shares into a final signature |
|
||||
| `Verifier` | Verifies threshold signatures against the group public key |
|
||||
|
||||
## Registry Pattern
|
||||
|
||||
Schemes register themselves via `init()` functions. Consumers look up schemes at runtime without compile-time coupling to specific implementations.
|
||||
|
||||
```go
|
||||
import (
|
||||
"github.com/luxfi/crypto/threshold"
|
||||
_ "github.com/luxfi/crypto/threshold/bls" // Register BLS
|
||||
_ "github.com/luxfi/corona/threshold" // Register Corona
|
||||
)
|
||||
|
||||
scheme, err := threshold.GetScheme(threshold.SchemeBLS)
|
||||
```
|
||||
|
||||
## Usage Flow
|
||||
|
||||
```
|
||||
1. Get scheme threshold.GetScheme(schemeID)
|
||||
2. Generate keys scheme.NewTrustedDealer(config) or scheme.NewDKG(config)
|
||||
3. Create signers scheme.NewSigner(keyShare)
|
||||
4. Sign shares signer.SignShare(ctx, message, signers, nonce)
|
||||
5. Aggregate aggregator.Aggregate(ctx, message, shares, commitments)
|
||||
6. Verify verifier.Verify(message, signature)
|
||||
```
|
||||
|
||||
## Package Structure
|
||||
|
||||
```
|
||||
crypto/threshold/
|
||||
├── interfaces.go # Scheme, DKG, Signer, Aggregator, Verifier
|
||||
├── registry.go # RegisterScheme, GetScheme, ListSchemes
|
||||
├── session.go # SigningSession, SessionManager
|
||||
├── adapter.go # SchemeAdapter, QuickSign helpers
|
||||
├── errors.go # Sentinel errors
|
||||
└── bls/ # Built-in BLS threshold implementation
|
||||
```
|
||||
|
||||
## Dependency Graph
|
||||
|
||||
```
|
||||
crypto/threshold <-- Interface definitions (no external deps)
|
||||
^
|
||||
|
|
||||
┌────┴────┐
|
||||
| |
|
||||
bls/ corona/threshold mpc/pkg/threshold
|
||||
(built-in) (native impl) (CGGMP21/FROST adapters)
|
||||
```
|
||||
|
||||
Implementations import `crypto/threshold` for the interfaces. Consumers import `crypto/threshold` plus the scheme packages they need. No circular dependencies.
|
||||
@@ -0,0 +1,117 @@
|
||||
---
|
||||
title: Go Interfaces
|
||||
description: Detailed threshold cryptography interface definitions
|
||||
icon: FileCode
|
||||
---
|
||||
|
||||
## Scheme
|
||||
|
||||
The top-level factory interface. Every threshold implementation must satisfy `Scheme`.
|
||||
|
||||
```go
|
||||
type Scheme interface {
|
||||
ID() SchemeID
|
||||
Name() string
|
||||
KeyShareSize() int
|
||||
SignatureShareSize() int
|
||||
SignatureSize() int
|
||||
PublicKeySize() int
|
||||
NewDKG(config DKGConfig) (DKG, error)
|
||||
NewTrustedDealer(config DealerConfig) (TrustedDealer, error)
|
||||
NewSigner(share KeyShare) (Signer, error)
|
||||
NewAggregator(groupKey PublicKey) (Aggregator, error)
|
||||
NewVerifier(groupKey PublicKey) (Verifier, error)
|
||||
ParseKeyShare(data []byte) (KeyShare, error)
|
||||
ParsePublicKey(data []byte) (PublicKey, error)
|
||||
ParseSignatureShare(data []byte) (SignatureShare, error)
|
||||
ParseSignature(data []byte) (Signature, error)
|
||||
}
|
||||
```
|
||||
|
||||
## DKG (Distributed Key Generation)
|
||||
|
||||
Multi-round protocol where parties collaboratively generate key shares without any single party knowing the full secret.
|
||||
|
||||
```go
|
||||
type DKG interface {
|
||||
Round1(ctx context.Context) (DKGMessage, error)
|
||||
Round2(ctx context.Context, round1Messages map[int]DKGMessage) (DKGMessage, error)
|
||||
Round3(ctx context.Context, round2Messages map[int]DKGMessage) (KeyShare, error)
|
||||
NumRounds() int
|
||||
GroupKey() PublicKey
|
||||
}
|
||||
```
|
||||
|
||||
## KeyShare
|
||||
|
||||
A party's portion of the threshold secret key.
|
||||
|
||||
```go
|
||||
type KeyShare interface {
|
||||
Index() int
|
||||
GroupKey() PublicKey
|
||||
PublicShare() []byte
|
||||
Threshold() int
|
||||
TotalParties() int
|
||||
Bytes() []byte
|
||||
SchemeID() SchemeID
|
||||
}
|
||||
```
|
||||
|
||||
## Signer
|
||||
|
||||
Creates signature shares. For multi-round schemes, `NonceGen` must be called before `SignShare`.
|
||||
|
||||
```go
|
||||
type Signer interface {
|
||||
Index() int
|
||||
PublicShare() []byte
|
||||
NonceGen(ctx context.Context) (NonceCommitment, NonceState, error)
|
||||
SignShare(ctx context.Context, message []byte, signers []int, nonce NonceState) (SignatureShare, error)
|
||||
KeyShare() KeyShare
|
||||
}
|
||||
```
|
||||
|
||||
## Aggregator
|
||||
|
||||
Combines `t+1` signature shares into a single valid signature.
|
||||
|
||||
```go
|
||||
type Aggregator interface {
|
||||
Aggregate(ctx context.Context, message []byte, shares []SignatureShare, commitments []NonceCommitment) (Signature, error)
|
||||
VerifyShare(message []byte, share SignatureShare, publicShare []byte) error
|
||||
GroupKey() PublicKey
|
||||
}
|
||||
```
|
||||
|
||||
## Verifier
|
||||
|
||||
Checks a final threshold signature against the group public key.
|
||||
|
||||
```go
|
||||
type Verifier interface {
|
||||
Verify(message []byte, signature Signature) bool
|
||||
VerifyBytes(message, signature []byte) bool
|
||||
GroupKey() PublicKey
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
```go
|
||||
type DKGConfig struct {
|
||||
Threshold int // Minimum signers required (t)
|
||||
TotalParties int // Total parties (n)
|
||||
PartyIndex int // This party's index
|
||||
PartyID []byte // Optional identifier
|
||||
Rand io.Reader // Defaults to crypto/rand
|
||||
}
|
||||
|
||||
type DealerConfig struct {
|
||||
Threshold int
|
||||
TotalParties int
|
||||
Rand io.Reader
|
||||
}
|
||||
```
|
||||
|
||||
Both configs validate that `1 <= Threshold < TotalParties` and `TotalParties >= 2`.
|
||||
@@ -0,0 +1 @@
|
||||
{"pages":["---Overview---","index","---Concepts---","interfaces","schemes","---API Reference---","api"]}
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: Supported Schemes
|
||||
description: CGGMP21, FROST, BLS, and Corona threshold signature scheme comparison
|
||||
icon: Layers
|
||||
---
|
||||
|
||||
## Scheme Registry
|
||||
|
||||
Each scheme registers itself via `init()` and is identified by a `SchemeID` constant.
|
||||
|
||||
```go
|
||||
const (
|
||||
SchemeFROST SchemeID = 1 // Schnorr threshold (Ed25519)
|
||||
SchemeCMP SchemeID = 2 // CGGMP21 threshold ECDSA
|
||||
SchemeBLS SchemeID = 3 // BLS threshold (non-interactive)
|
||||
SchemeCorona SchemeID = 4 // Lattice-based (post-quantum)
|
||||
)
|
||||
```
|
||||
|
||||
## Comparison
|
||||
|
||||
| Property | CGGMP21 | FROST | BLS | Corona |
|
||||
|----------|---------|-------|-----|----------|
|
||||
| Signature type | ECDSA | Schnorr | BLS12-381 | Lattice |
|
||||
| Post-quantum | No | No | No | Yes |
|
||||
| Signing rounds | Multi | 2 | 1 (non-interactive) | 2 |
|
||||
| DKG rounds | Multi | 2 | 2 | Trusted dealer |
|
||||
| Aggregatable | No | No | Yes | No |
|
||||
| Chain compatibility | Bitcoin, Ethereum | Solana, Sui | Lux consensus | All (PQ bundles) |
|
||||
| Implementation | `mpc/pkg/threshold` | `mpc/pkg/threshold` | `crypto/threshold/bls` | `corona/threshold` |
|
||||
|
||||
## CGGMP21 (SchemeCMP)
|
||||
|
||||
Threshold ECDSA signing based on the Canetti-Gennaro-Goldfeder-Makriyannis-Peled protocol. Produces standard ECDSA signatures compatible with Bitcoin and Ethereum. Implemented in the `mpc` repository.
|
||||
|
||||
## FROST (SchemeFROST)
|
||||
|
||||
Flexible Round-Optimized Schnorr Threshold signatures. 2-round protocol producing Schnorr signatures compatible with Ed25519/EdDSA. Implemented in the `mpc` repository.
|
||||
|
||||
## BLS (SchemeBLS)
|
||||
|
||||
BLS12-381 threshold signatures with non-interactive aggregation. Shares can be combined without additional communication rounds. Built into `crypto/threshold/bls`. Used for Lux consensus block signing.
|
||||
|
||||
## Corona (SchemeCorona)
|
||||
|
||||
Lattice-based threshold signatures using Module-LWE. The only post-quantum scheme. 2-round signing protocol with trusted dealer key generation. Implemented natively in the `corona` repository.
|
||||
|
||||
## Selecting a Scheme
|
||||
|
||||
```go
|
||||
func schemeForChain(chain string) (threshold.Scheme, error) {
|
||||
switch chain {
|
||||
case "ethereum", "bitcoin":
|
||||
return threshold.GetScheme(threshold.SchemeCMP)
|
||||
case "solana", "sui":
|
||||
return threshold.GetScheme(threshold.SchemeFROST)
|
||||
case "lux":
|
||||
return threshold.GetScheme(threshold.SchemeBLS)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported chain: %s", chain)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Corona is used alongside BLS in Lux Quasar consensus for post-quantum security bundles, not as a standalone chain signing scheme.
|
||||
@@ -0,0 +1,104 @@
|
||||
---
|
||||
title: Warp API Reference
|
||||
description: Core types, functions, and interfaces for Warp messaging
|
||||
icon: Code
|
||||
---
|
||||
|
||||
## Core Types
|
||||
|
||||
### UnsignedMessage
|
||||
|
||||
```go
|
||||
type UnsignedMessage struct {
|
||||
NetworkID uint32
|
||||
SourceChainID ids.ID
|
||||
Payload []byte
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Returns | Description |
|
||||
|--------|---------|-------------|
|
||||
| `Verify()` | `error` | Validates format and size |
|
||||
| `Bytes()` | `[]byte` | Serialized representation |
|
||||
| `ID()` | `ids.ID` | SHA-256 hash of the serialized message |
|
||||
|
||||
### Message
|
||||
|
||||
```go
|
||||
type Message struct {
|
||||
UnsignedMessage *UnsignedMessage
|
||||
Signature Signature
|
||||
}
|
||||
```
|
||||
|
||||
| Method | Returns | Description |
|
||||
|--------|---------|-------------|
|
||||
| `Verify()` | `error` | Validates message and signature are non-nil |
|
||||
| `Bytes()` | `[]byte` | Serialized representation |
|
||||
| `ID()` | `ids.ID` | Hash of the unsigned message |
|
||||
| `Equal(other)` | `bool` | Deep equality check |
|
||||
|
||||
## Constructors
|
||||
|
||||
```go
|
||||
func NewUnsignedMessage(networkID uint32, chainID ids.ID, payload []byte) (*UnsignedMessage, error)
|
||||
func NewMessage(unsigned *UnsignedMessage, signature Signature) (*Message, error)
|
||||
func ParseMessage(b []byte) (*Message, error)
|
||||
func ParseUnsignedMessage(b []byte) (*UnsignedMessage, error)
|
||||
```
|
||||
|
||||
## Verification
|
||||
|
||||
```go
|
||||
func VerifyMessage(msg *Message, networkID uint32, state ValidatorState, quorumNum, quorumDen uint64) error
|
||||
func VerifyWeight(signedWeight, totalWeight, quorumNum, quorumDen uint64) error
|
||||
```
|
||||
|
||||
## Interfaces
|
||||
|
||||
### Signature
|
||||
|
||||
```go
|
||||
type Signature interface {
|
||||
Verify(unsignedBytes []byte, validators []Validator) error
|
||||
GetSignedWeight(validators []Validator) (uint64, error)
|
||||
Equal(other Signature) bool
|
||||
Bytes() []byte
|
||||
}
|
||||
```
|
||||
|
||||
### ValidatorState
|
||||
|
||||
```go
|
||||
type ValidatorState interface {
|
||||
GetValidatorSet(ctx context.Context, height uint64, chainID ids.ID) ([]Validator, error)
|
||||
GetCurrentHeight(ctx context.Context) (uint64, error)
|
||||
}
|
||||
```
|
||||
|
||||
### Validator
|
||||
|
||||
```go
|
||||
type Validator struct {
|
||||
PublicKey *bls.PublicKey
|
||||
PublicKeyBytes []byte
|
||||
Weight uint64
|
||||
NodeID ids.NodeID
|
||||
}
|
||||
```
|
||||
|
||||
## Constants
|
||||
|
||||
| Constant | Value | Description |
|
||||
|----------|-------|-------------|
|
||||
| `CodecVersion` | `0` | Serialization codec version |
|
||||
| `MaxMessageSize` | `256 KiB` | Maximum serialized message size |
|
||||
|
||||
## Errors
|
||||
|
||||
| Error | Description |
|
||||
|-------|-------------|
|
||||
| `ErrInvalidSignature` | Signature verification failed |
|
||||
| `ErrInvalidMessage` | Message format is invalid |
|
||||
| `ErrUnknownValidator` | Validator not in the expected set |
|
||||
| `ErrInsufficientWeight` | Signed weight below quorum |
|
||||
@@ -0,0 +1,65 @@
|
||||
---
|
||||
title: Lux Warp
|
||||
description: Native cross-chain messaging protocol using BLS aggregate signatures
|
||||
icon: Radio
|
||||
---
|
||||
|
||||
Lux Warp (`github.com/luxfi/warp`) is the cross-chain messaging protocol for Lux Network. It enables subnets to send verified messages to each other without relying on external bridges or oracles.
|
||||
|
||||
## How It Works
|
||||
|
||||
Warp uses BLS multi-signatures from source chain validators to authenticate cross-chain messages.
|
||||
|
||||
1. A VM on the source chain emits a Warp message containing a payload
|
||||
2. Validators on the source chain sign the message with their BLS keys
|
||||
3. Signatures are aggregated into a single `BitSetSignature` (a signer bitmap plus a 96-byte BLS aggregate signature)
|
||||
4. The destination chain verifies the aggregate signature against the source chain's validator set
|
||||
5. If the signed weight meets the quorum threshold (typically 67%), the message is accepted
|
||||
|
||||
```
|
||||
Source Chain Destination Chain
|
||||
┌────────────┐ ┌────────────┐
|
||||
│ VM emits │ BLS aggregate sig │ VM receives│
|
||||
│ unsigned │─────────────────────▶ │ and verifies│
|
||||
│ message │ (bitmap + 96 bytes) │ message │
|
||||
└────────────┘ └────────────┘
|
||||
│ │
|
||||
▼ ▼
|
||||
Validators ValidatorState
|
||||
sign with checks quorum
|
||||
BLS keys weight
|
||||
```
|
||||
|
||||
## Key Properties
|
||||
|
||||
| Property | Value |
|
||||
|----------|-------|
|
||||
| Signature scheme | BLS12-381 aggregate signatures |
|
||||
| Quorum default | 67% of stake weight |
|
||||
| Max message size | 256 KiB |
|
||||
| Signature size | 96 bytes + signer bitmap |
|
||||
| Trust model | Source chain validator set |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
github.com/luxfi/warp
|
||||
├── message.go # UnsignedMessage, Message
|
||||
├── payload/ # AddressedCall, Hash, L1ValidatorRegistration
|
||||
├── backend/ # Message storage and retrieval
|
||||
├── signer/ # LocalSigner, RemoteSigner
|
||||
├── signature-aggregator/ # Signature collection and aggregation
|
||||
├── precompile/ # EVM precompile for in-contract verification
|
||||
└── relayer/ # Automatic message relay
|
||||
```
|
||||
|
||||
## Dependencies
|
||||
|
||||
```go
|
||||
require (
|
||||
github.com/luxfi/crypto v1.17.25 // BLS cryptography
|
||||
github.com/luxfi/geth v1.16.53 // EVM types
|
||||
github.com/luxfi/ids v1.2.4 // ID types
|
||||
github.com/luxfi/p2p v1.4.6 // P2P networking
|
||||
)
|
||||
```
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: VM Integration
|
||||
description: Integrate Warp cross-chain messaging into a subnet VM
|
||||
icon: Plug
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
To add Warp messaging to a subnet VM, you need to handle message creation on the source side and message verification on the destination side.
|
||||
|
||||
## Source Chain: Sending Messages
|
||||
|
||||
### 1. Create an Unsigned Message
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/warp"
|
||||
|
||||
msg, err := warp.NewUnsignedMessage(
|
||||
networkID, // uint32
|
||||
sourceChainID, // ids.ID
|
||||
payload, // []byte (encoded payload)
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Request Signatures
|
||||
|
||||
Use a `Signer` to have the local validator sign the message, or a signature aggregator to collect signatures from multiple validators.
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/warp/signer"
|
||||
|
||||
// Local signer (for this validator)
|
||||
localSigner := signer.NewLocalSigner(blsSecretKey)
|
||||
sig, err := localSigner.Sign(msg)
|
||||
```
|
||||
|
||||
### 3. Aggregate Signatures
|
||||
|
||||
The signature aggregator collects individual BLS signatures and produces a single `BitSetSignature`.
|
||||
|
||||
```go
|
||||
import aggregator "github.com/luxfi/warp/signature-aggregator"
|
||||
|
||||
agg := aggregator.New(validatorState, sourceChainID)
|
||||
signature, err := agg.AggregateSignatures(ctx, msg, quorumNum, quorumDen)
|
||||
```
|
||||
|
||||
## Destination Chain: Receiving Messages
|
||||
|
||||
### 1. Parse and Verify
|
||||
|
||||
```go
|
||||
msg, err := warp.ParseMessage(rawBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = warp.VerifyMessage(msg, networkID, validatorState, 67, 100)
|
||||
if err != nil {
|
||||
return err // Insufficient quorum or invalid signature
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Extract Payload
|
||||
|
||||
```go
|
||||
import "github.com/luxfi/warp/payload"
|
||||
|
||||
addressedCall, err := payload.ParseAddressedCall(msg.UnsignedMessage.Payload)
|
||||
// Use addressedCall.SourceAddress and addressedCall.Payload
|
||||
```
|
||||
|
||||
## EVM Precompile
|
||||
|
||||
For EVM-based subnets, Warp is accessible via a precompile at a fixed address. Smart contracts can send and receive Warp messages without custom VM modifications.
|
||||
|
||||
The precompile handles:
|
||||
|
||||
- **Sending**: Emitting Warp messages from Solidity
|
||||
- **Receiving**: Verifying Warp signatures and extracting payloads in Solidity
|
||||
- **Validator queries**: Looking up the source chain validator set
|
||||
|
||||
## Backend
|
||||
|
||||
The backend stores outgoing messages and serves them to signature aggregators. Two implementations are provided:
|
||||
|
||||
| Backend | Use Case |
|
||||
|---------|----------|
|
||||
| `MemoryBackend` | Testing and lightweight nodes |
|
||||
| `ChainBackend` | Production nodes with persistent storage |
|
||||
|
||||
## Relayer
|
||||
|
||||
The relayer automatically watches for Warp messages on a source chain and delivers them to a destination chain. It handles signature aggregation and transaction submission.
|
||||
@@ -0,0 +1,90 @@
|
||||
---
|
||||
title: Messages and Payloads
|
||||
description: Warp message format, payload types, and BLS signing
|
||||
icon: FileText
|
||||
---
|
||||
|
||||
## Message Format
|
||||
|
||||
Every Warp message consists of an `UnsignedMessage` wrapped with a `Signature`.
|
||||
|
||||
### UnsignedMessage
|
||||
|
||||
The unsigned message identifies the source network and chain, and carries an arbitrary payload.
|
||||
|
||||
```go
|
||||
type UnsignedMessage struct {
|
||||
NetworkID uint32 // Lux network ID (1=mainnet, 2=testnet)
|
||||
SourceChainID ids.ID // 32-byte chain identifier
|
||||
Payload []byte // Encoded payload (up to 256 KiB total)
|
||||
}
|
||||
```
|
||||
|
||||
### Message (Signed)
|
||||
|
||||
A signed message pairs the unsigned content with a BLS aggregate signature.
|
||||
|
||||
```go
|
||||
type Message struct {
|
||||
UnsignedMessage *UnsignedMessage
|
||||
Signature Signature // BitSetSignature
|
||||
}
|
||||
```
|
||||
|
||||
### BitSetSignature
|
||||
|
||||
The signature uses a compact bitmap to indicate which validators signed, plus a single aggregated BLS signature.
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| Signers | `[]byte` | Bitmap of validator indices that signed |
|
||||
| Signature | `[96]byte` | Aggregated BLS12-381 signature |
|
||||
|
||||
## Payload Types
|
||||
|
||||
Payloads are encoded inside the `UnsignedMessage.Payload` field.
|
||||
|
||||
### AddressedCall
|
||||
|
||||
Cross-VM contract-to-contract calls. Contains a source address and arbitrary call data.
|
||||
|
||||
### Hash
|
||||
|
||||
A simple 32-byte hash payload. Used when only a content commitment is needed.
|
||||
|
||||
### L1ValidatorRegistration
|
||||
|
||||
Reports whether a validator is currently registered on the source L1. Used for cross-chain validator set synchronization.
|
||||
|
||||
### RegisterL1Validator
|
||||
|
||||
Requests adding a validator to a subnet. Carries the full validator parameters including BLS public key and weight.
|
||||
|
||||
### L1ValidatorWeight
|
||||
|
||||
Updates the weight of an existing validator. Used when stake changes on the source chain.
|
||||
|
||||
### SubnetToL1Conversion
|
||||
|
||||
Signals that a subnet has been converted to an L1. Contains the conversion data needed by destination chains.
|
||||
|
||||
## Verification
|
||||
|
||||
Messages are verified by calling `VerifyMessage` with the expected network ID and a `ValidatorState` that can look up the source chain's validator set.
|
||||
|
||||
```go
|
||||
err := warp.VerifyMessage(
|
||||
msg,
|
||||
networkID,
|
||||
validatorState,
|
||||
quorumNum, // e.g. 67
|
||||
quorumDen, // e.g. 100
|
||||
)
|
||||
```
|
||||
|
||||
The verification checks that:
|
||||
|
||||
1. The message format is valid
|
||||
2. The network ID matches
|
||||
3. The aggregate signature is correct for the indicated signers
|
||||
4. The total signed weight meets the quorum threshold
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user